import { useState } from 'react';
import {
    Table,
    Button,
    Space,
    Modal,
    Form,
    Input,
    Select,
    Tag,
    Popconfirm,
    Upload,
    InputNumber,
    Tabs,
    message,
} from 'antd';
import { Plus, Edit, Trash2, Eye, Upload as UploadIcon } from 'lucide-react';
import {
    requestCreateProduct,
    requestGetAllProduct,
    requestUpdateProduct,
    requestDeleteProduct,
} from '../../config/product';
import { useStore } from '../../hooks/useStore';
import { useEffect } from 'react';

const { TextArea } = Input;

const ProductManager = () => {
    const [dataSource, setDataSource] = useState([]);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingRecord, setEditingRecord] = useState(null);
    const [form] = Form.useForm();
    const [fileList, setFileList] = useState([]);

    const { dataCategory } = useStore();

    // Fetch Products
    const fetchProducts = async () => {
        try {
            const res = await requestGetAllProduct();
            if (res.metadata) {
                // Add key for table
                const dataWithKey = res.metadata.map((item, index) => ({
                    ...item,
                    key: item._id, // Use _id as key
                    categoryName: dataCategory.find((c) => c._id === item.categoryId)?.nameCategory || 'Unknown',
                }));
                setDataSource(dataWithKey);
            }
        } catch (error) {
            console.log(error);
        }
    };

    useEffect(() => {
        if (dataCategory.length > 0) fetchProducts();
    }, [dataCategory]);

    // Mock Category Options
    const categoryOptions = dataCategory
        .filter((item) => item.level === 1)
        .map((item) => ({
            label: item.nameCategory,
            value: item._id,
        }));

    const handleAdd = () => {
        setEditingRecord(null);
        form.resetFields();
        setFileList([]);
        setIsModalOpen(true);
    };

    const handleEdit = (record) => {
        setEditingRecord(record);

        // Convert info object to array for Form.List
        // Info is now a top-level field, not inside account
        const detailsArray =
            record.info && typeof record.info === 'object'
                ? Object.entries(record.info).map(([key, value]) => ({ key, value }))
                : [];

        form.setFieldsValue({
            ...record,
            category: record.categoryId,
            ['account.username']: record.account?.username,
            // Don't pre-fill password for security
            ['account.password']: '',
            // Form.List with name={['account', 'details']} expects data at account.details
            account: {
                details: detailsArray,
            },
        });

        // Handle Images
        // server stores filename. Need full URL using VITE_API_URL.
        if (record.images && record.images.length > 0) {
            setFileList(
                record.images.map((img, index) => ({
                    uid: index,
                    name: `image-${index}`,
                    status: 'done',
                    url: img.startsWith('http') ? img : `${img}`,
                })),
            );
        } else {
            setFileList([]);
        }

        setIsModalOpen(true);
    };

    const handleDelete = async (key) => {
        try {
            await requestDeleteProduct(key);
            message.success('Đã xóa sản phẩm thành công!');
            fetchProducts();
        } catch (error) {
            message.error('Xóa thất bại');
        }
    };

    const handleCancel = () => {
        setIsModalOpen(false);
        form.resetFields();
        setFileList([]);
    };

    const onFinish = async (values) => {
        const formData = new FormData();
        formData.append('categoryId', values.categoryId);
        formData.append('price', values.price);
        formData.append('description', values.description || '');
        formData.append('status', values.status);

        // Handle Account Info (only username and password)
        const accountData = {
            username: values['account.username'],
        };
        // Only append password if user typed something (create or edit change)
        if (values['account.password']) {
            accountData.password = values['account.password'];
        }
        formData.append('account', JSON.stringify(accountData));

        // Handle Info (Rank, Skin, etc.) - separate from account now
        // Form.List with name={['account', 'details']} puts data at values.account.details
        const accountDetails = values.account?.details || [];
        const infoData = accountDetails.reduce((acc, curr) => {
            if (curr && curr.key && curr.value) acc[curr.key] = curr.value;
            return acc;
        }, {});
        formData.append('info', JSON.stringify(infoData));

        // Separate new files from existing images
        const oldImages = []; // Images to keep (existing ones still in fileList)
        fileList.forEach((file) => {
            if (file.originFileObj) {
                // New file to upload
                formData.append('images', file.originFileObj);
            } else if (file.url) {
                // Existing image - extract filename from URL
                const filename = file.url.split('/').pop();
                oldImages.push(filename);
            }
        });

        // Send oldImages when editing (so backend knows which to keep)
        if (editingRecord) {
            formData.append('oldImages', JSON.stringify(oldImages));
        }

        try {
            if (editingRecord) {
                await requestUpdateProduct(editingRecord._id, formData);
                message.success('Cập nhật sản phẩm thành công!');
            } else {
                await requestCreateProduct(formData);
                message.success('Thêm sản phẩm mới thành công!');
            }
            fetchProducts();
            setIsModalOpen(false);
        } catch (error) {
            message.error('Thao tác thất bại');
        }
    };

    const handleUploadChange = ({ fileList: newFileList }) => setFileList(newFileList);

    const columns = [
        {
            title: 'Sản phẩm',
            dataIndex: 'title',
            key: 'title',
            render: (text, record) => (
                <div className="flex items-center gap-3">
                    <img src={`${record.images?.[0]}`} alt="thumb" className="w-12 h-12 object-cover rounded border" />
                    <div>
                        <div className="font-bold text-gray-800">{text}</div>
                        <div className="text-xs text-gray-500">{record.categoryName}</div>
                    </div>
                </div>
            ),
        },
        {
            title: 'Danh mục',
            dataIndex: 'categoryName',
            key: 'categoryName',
            render: (categoryName) => <span className="font-semibold text-red-600">{categoryName}</span>,
        },
        {
            title: 'Giá tiền',
            dataIndex: 'price',
            key: 'price',
            render: (price) => <span className="font-semibold text-red-600">{price?.toLocaleString()} đ</span>,
        },
        {
            title: 'Trạng thái',
            dataIndex: 'status',
            key: 'status',
            render: (status) => {
                let color = 'green';
                let text = 'Sẵn sàng';
                if (status === 'sold') {
                    color = 'red';
                    text = 'Đã bán';
                }
                if (status === 'locked') {
                    color = 'gray';
                    text = 'Đã khóa';
                }
                return <Tag color={color}>{text}</Tag>;
            },
        },
        {
            title: 'Hành động',
            key: 'action',
            render: (_, record) => (
                <Space size="small">
                    <Button
                        type="text"
                        icon={<Edit size={16} className="text-blue-500" />}
                        onClick={() => handleEdit(record)}
                    />
                    <Popconfirm
                        title="Xóa tài khoản này?"
                        onConfirm={() => handleDelete(record.key)}
                        okText="Xóa"
                        cancelText="Hủy"
                        okButtonProps={{ danger: true }}
                    >
                        <Button type="text" danger icon={<Trash2 size={16} />} />
                    </Popconfirm>
                </Space>
            ),
        },
    ];

    return (
        <div>
            <div className="flex items-center justify-between mb-6">
                <h2 className="text-xl font-bold text-gray-800">Quản lý tài khoản (Sản phẩm)</h2>
                <Button type="primary" icon={<Plus size={18} />} onClick={handleAdd} className="bg-blue-600">
                    Thêm tài khoản
                </Button>
            </div>

            <Table
                dataSource={dataSource}
                columns={columns}
                pagination={{ pageSize: 10 }}
                className="shadow-sm rounded-lg overflow-hidden"
            />

            <Modal
                title={editingRecord ? 'Cập nhật tài khoản' : 'Thêm tài khoản mới'}
                open={isModalOpen}
                onCancel={handleCancel}
                width={800}
                footer={null}
            >
                <Form form={form} layout="vertical" onFinish={onFinish} initialValues={{ status: 'available' }}>
                    {/* General Information Section */}
                    <div className="mb-6">
                        <h3 className="text-sm font-bold text-gray-700 uppercase mb-3 border-b pb-1">
                            Thông tin chung
                        </h3>
                        <div className="grid grid-cols-2 gap-4">
                            <Form.Item
                                name="categoryId"
                                label="Danh mục"
                                rules={[{ required: true, message: 'Chọn danh mục!' }]}
                            >
                                <Select options={categoryOptions} placeholder="Chọn game" />
                            </Form.Item>

                            <Form.Item
                                name="price"
                                label="Giá bán (VNĐ)"
                                rules={[{ required: true, message: 'Nhập giá bán!' }]}
                            >
                                <InputNumber
                                    style={{ width: '100%' }}
                                    formatter={(value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                                    parser={(value) => value?.replace(/\$\s?|(,*)/g, '')}
                                />
                            </Form.Item>

                            <Form.Item name="status" label="Trạng thái">
                                <Select>
                                    <Select.Option value="available">Sẵn sàng</Select.Option>
                                    <Select.Option value="sold">Đã bán</Select.Option>
                                    <Select.Option value="locked">Đã khóa</Select.Option>
                                </Select>
                            </Form.Item>

                            <Form.Item name="description" label="Mô tả chi tiết" className="col-span-2">
                                <TextArea rows={4} />
                            </Form.Item>
                        </div>
                    </div>

                    {/* Account Information Section */}
                    <div className="mb-6">
                        <h3 className="text-sm font-bold text-gray-700 uppercase mb-3 border-b pb-1">
                            Thông tin đăng nhập
                        </h3>
                        <div className="bg-yellow-50 p-3 border border-yellow-200 rounded mb-4 text-xs text-yellow-700">
                            Thông tin này sẽ được gửi cho khách hàng sau khi thanh toán thành công.
                        </div>
                        <div className="grid grid-cols-2 gap-4">
                            <Form.Item
                                name="account.username"
                                label="Tài khoản (Username)"
                                rules={[{ required: true, message: 'Nhập tài khoản!' }]}
                            >
                                <Input />
                            </Form.Item>

                            <Form.Item
                                name="account.password"
                                label={editingRecord ? 'Mật khẩu mới (để trống nếu không đổi)' : 'Mật khẩu (Password)'}
                                rules={editingRecord ? [] : [{ required: true, message: 'Nhập mật khẩu!' }]}
                            >
                                <Input.Password placeholder={editingRecord ? 'Để trống nếu không thay đổi' : ''} />
                            </Form.Item>

                            <div className="col-span-2">
                                <Form.List name={['account', 'details']}>
                                    {(fields, { add, remove }) => (
                                        <>
                                            <div className="flex justify-between items-center mb-2">
                                                <label className="text-sm font-semibold text-gray-700">
                                                    Thông tin thêm (Rank, Skin, ...)
                                                </label>
                                                <Button type="dashed" onClick={() => add()} icon={<Plus size={14} />}>
                                                    Thêm dòng
                                                </Button>
                                            </div>
                                            {fields.map(({ key, name, ...restField }) => (
                                                <Space
                                                    key={key}
                                                    style={{ display: 'flex', marginBottom: 8 }}
                                                    align="baseline"
                                                >
                                                    <Form.Item
                                                        {...restField}
                                                        name={[name, 'key']}
                                                        rules={[{ required: true, message: 'Nhập tên thuộc tính' }]}
                                                    >
                                                        <Input
                                                            style={{ width: '100%' }}
                                                            placeholder="Thuộc tính (VD: Rank)"
                                                        />
                                                    </Form.Item>
                                                    <Form.Item
                                                        {...restField}
                                                        name={[name, 'value']}
                                                        rules={[{ required: true, message: 'Nhập giá trị' }]}
                                                    >
                                                        <Input
                                                            style={{ width: '100%' }}
                                                            placeholder="Giá trị (VD: Cao Thủ)"
                                                        />
                                                    </Form.Item>
                                                    <Trash2
                                                        size={16}
                                                        className="text-red-500 cursor-pointer"
                                                        onClick={() => remove(name)}
                                                    />
                                                </Space>
                                            ))}
                                        </>
                                    )}
                                </Form.List>
                            </div>
                        </div>
                    </div>

                    {/* Image Upload Section */}
                    <div>
                        <h3 className="text-sm font-bold text-gray-700 uppercase mb-3 border-b pb-1">
                            Hình ảnh sản phẩm
                        </h3>
                        <Form.Item name="images">
                            <Upload
                                listType="picture-card"
                                fileList={fileList}
                                onChange={handleUploadChange}
                                beforeUpload={() => false}
                                multiple
                            >
                                <div>
                                    <UploadIcon />
                                    <div style={{ marginTop: 8 }}>Upload</div>
                                </div>
                            </Upload>
                        </Form.Item>
                    </div>

                    <div className="flex justify-end gap-2 mt-4 pt-4 border-t">
                        <Button onClick={handleCancel}>Hủy</Button>
                        <Button type="primary" htmlType="submit" className="bg-blue-600">
                            {editingRecord ? 'Lưu thay đổi' : 'Thêm mới'}
                        </Button>
                    </div>
                </Form>
            </Modal>
        </div>
    );
};

export default ProductManager;
