import { useState, useEffect } from 'react';
import { Table, Button, Space, Card, Form, InputNumber, message, Tag, Switch, Popconfirm } from 'antd';
import { Edit, Save, RefreshCw, X } from 'lucide-react';
import { requestGetCardConfigs, requestUpdateCardConfig } from '../../config/cardType';

// We need to implement requestGetCardConfigs in cardType.jsx first
// But for now let's write the component assuming the API exists

const CardManager = () => {
    const [cardConfigs, setCardConfigs] = useState([]);
    const [loading, setLoading] = useState(false);
    const [editingKey, setEditingKey] = useState('');
    const [filterTelco, setFilterTelco] = useState('ALL');
    const [form] = Form.useForm();

    const fetchCardConfigs = async () => {
        setLoading(true);
        try {
            // Updated API call to fetch raw configs
            const response = await requestGetCardConfigs();
            setCardConfigs(response.metadata || []);
        } catch (error) {
            message.error('Không thể tải cấu hình thẻ');
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchCardConfigs();
    }, []);

    const isEditing = (record) => record.identifier === editingKey;

    const edit = (record) => {
        form.setFieldsValue({
            customFee: record.customFee !== null ? record.customFee : record.fees,
            customStatus: record.customStatus,
        });
        setEditingKey(record.identifier);
    };

    const cancel = () => {
        setEditingKey('');
    };

    const save = async (record) => {
        try {
            const row = await form.validateFields();
            const newData = {
                telco: record.telco,
                value: record.value,
                fee: row.customFee,
                status: row.customStatus !== undefined ? row.customStatus : true, // Default to true if not toggled?
            };

            await requestUpdateCardConfig(newData);
            message.success('Cập nhật cấu hình thành công!');
            setEditingKey('');
            fetchCardConfigs();
        } catch (errInfo) {
            console.error('Validate Failed:', errInfo);
            message.error('Có lỗi xảy ra!');
        }
    };

    // Get unique telcos for filter
    const uniqueTelcos = ['ALL', ...new Set(cardConfigs.map((item) => item.telco))].sort();

    const columns = [
        {
            title: 'Nhà mạng',
            dataIndex: 'telco',
            key: 'telco',
            render: (text) => <span className="font-bold text-blue-800">{text}</span>,
            sorter: (a, b) => a.telco.localeCompare(b.telco),
        },
        {
            title: 'Mệnh giá',
            dataIndex: 'value',
            key: 'value',
            render: (val) => <span className="font-medium">{val.toLocaleString()}đ</span>,
            sorter: (a, b) => a.value - b.value,
        },
        {
            title: 'Phí gốc (TSR)',
            dataIndex: 'fees',
            key: 'fees',
            render: (fee) => <Tag color="default">{fee}%</Tag>,
        },
        {
            title: 'Chiết khấu của tôi',
            dataIndex: 'customFee',
            key: 'customFee',
            render: (fee, record) => {
                const editable = isEditing(record);
                if (editable) {
                    return (
                        <Form.Item
                            name="customFee"
                            style={{ margin: 0 }}
                            rules={[
                                {
                                    required: true,
                                    message: 'Vui lòng nhập phí!',
                                },
                            ]}
                        >
                            <InputNumber
                                min={0}
                                max={100}
                                formatter={(value) => `${value}%`}
                                parser={(value) => value.replace('%', '')}
                            />
                        </Form.Item>
                    );
                }
                return (
                    <Tag color={fee !== null ? 'green' : 'orange'} className="font-bold text-base">
                        {fee !== null ? fee : record.fees}%
                    </Tag>
                );
            },
        },
        {
            title: 'Trạng thái',
            dataIndex: 'customStatus',
            key: 'customStatus',
            render: (status, record) => {
                const editable = isEditing(record);
                if (editable) {
                    return (
                        <Form.Item
                            name="customStatus"
                            style={{ margin: 0 }}
                            valuePropName="checked"
                            initialValue={status}
                        >
                            <Switch checkedChildren="Bật" unCheckedChildren="Tắt" />
                        </Form.Item>
                    );
                }
                return <Tag color={status ? 'blue' : 'red'}>{status ? 'Hoạt động' : 'Đang tắt'}</Tag>;
            },
        },
        {
            title: 'Thao tác',
            dataIndex: 'operation',
            render: (_, record) => {
                const editable = isEditing(record);
                return editable ? (
                    <Space>
                        <Button type="primary" size="small" icon={<Save size={16} />} onClick={() => save(record)}>
                            Lưu
                        </Button>
                        <Button size="small" icon={<X size={16} />} onClick={cancel}>
                            Hủy
                        </Button>
                    </Space>
                ) : (
                    <Button
                        type="text"
                        disabled={editingKey !== ''}
                        icon={<Edit size={16} className="text-blue-600" />}
                        onClick={() => edit(record)}
                    >
                        Sửa
                    </Button>
                );
            },
        },
    ];

    // Filter data
    const filteredData = cardConfigs.filter((item) => {
        if (filterTelco !== 'ALL') return item.telco === filterTelco;
        return true;
    });

    // Add unique identifier to records for table keys
    const dataSource = filteredData.map((item, index) => ({
        ...item,
        identifier: `${item.telco}-${item.value}`, // Unique key
    }));

    return (
        <Card
            title={
                <Space>
                    <span>Cấu hình Chiết khấu Thẻ cào</span>
                    <span className="text-sm font-normal text-gray-400">({dataSource.length} mục)</span>
                </Space>
            }
            extra={
                <Space>
                    <div className="flex gap-2 mr-4">
                        {uniqueTelcos.map((telco) => (
                            <Button
                                key={telco}
                                size="small"
                                type={filterTelco === telco ? 'primary' : 'default'}
                                onClick={() => setFilterTelco(telco)}
                            >
                                {telco === 'ALL' ? 'Tất cả' : telco}
                            </Button>
                        ))}
                    </div>
                    <Button icon={<RefreshCw size={16} />} onClick={fetchCardConfigs}>
                        Làm mới
                    </Button>
                </Space>
            }
        >
            <Form form={form} component={false}>
                <Table
                    components={{
                        body: {
                            cell: ({ children }) => <td>{children}</td>,
                        },
                    }}
                    dataSource={dataSource}
                    columns={columns}
                    rowKey="identifier"
                    loading={loading}
                    pagination={{ pageSize: 20 }}
                />
            </Form>
        </Card>
    );
};

export default CardManager;
