import { useState } from 'react';
import { Table, Tag, Button, Space, Modal, Form, Input, Select, Switch, message, Popconfirm, Upload } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { Plus, Edit, Trash2 } from 'lucide-react';
import {
    requestCreateCategory,
    requestUpdateCategory,
    requestDeleteCategory,
    requestGetAllCategory,
} from '../../config/category';
import { useEffect } from 'react';
import { useStore } from '../../hooks/useStore';

const CategoryManager = () => {
    // Initial Mock Data

    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingRecord, setEditingRecord] = useState(null);
    const [form] = Form.useForm();

    const { dataCategory, fetchCategory } = useStore();

    // Helper to get parent options (Level 0 categories)
    const parentOptions = dataCategory
        .filter((item) => item.level === 0)
        .map((item) => ({
            label: item.nameCategory,
            value: item._id,
        }));

    console.log(parentOptions);

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

    const handleEdit = (record) => {
        setEditingRecord(record);
        form.setFieldsValue({
            ...record,
            parentId: record.parentId,
            // For fileList in Upload, we don't necessarily prepopulate it from URL for now unless we have a preview
            // But if we wanted to show existing image, we'd need to mock a fileList object.
            // keeping it simple for now or strictly following 'image' string logic from backend.
        });
        setIsModalOpen(true);
    };

    const handleDelete = async (key) => {
        try {
            await requestDeleteCategory(key);
            dataCategory.filter((item) => item._id !== key && item.key !== key);
            fetchCategory();
            message.success('Đã xóa danh mục thành công!');
        } catch (error) {
            message.error('Xóa danh mục thất bại!');
        }
    };

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

    const onFinish = async (values) => {
        // Determine level based on parentId
        const level = values.parentId ? 1 : 0;

        const formData = new FormData();
        formData.append('nameCategory', values.nameCategory);
        formData.append('slug', values.slug);
        formData.append('level', level);
        formData.append('parentId', values.parentId || '');
        formData.append('isActive', values.isActive);

        // Handle Single Image Upload
        if (values.image && values.image.length > 0) {
            formData.append('image', values.image[0].originFileObj);
        }

        try {
            if (editingRecord) {
                // Should pass oldImage name if it exists, so backend can delete it
                if (editingRecord.image) {
                    formData.append('oldImage', editingRecord.image);
                }

                await requestUpdateCategory(editingRecord.key, formData);
                message.success('Cập nhật danh mục thành công!');

                // Update local state for immediate feedback (mock logic)
                const newData = dataCategory.map((item) => {
                    if (item.key === editingRecord.key) {
                        return {
                            ...item,
                            ...values,
                            level,
                            parentName: values.parentId
                                ? parentOptions.find((opt) => opt.value === values.parentId)?.label
                                : null,
                        };
                    }
                    return item;
                });
            } else {
                await requestCreateCategory(formData);
                message.success('Thêm danh mục mới thành công!');
                // For real app we would reload data. For now, pushing simplified item.
                const newKey = (dataCategory.length + 1).toString();
                const newItem = {
                    key: newKey,
                    ...values,
                    level,
                    parentName: values.parentId
                        ? parentOptions.find((opt) => opt.value === values.parentId)?.label
                        : null,
                    createdAt: new Date().toISOString(),
                };
            }
            await fetchCategory();
            setIsModalOpen(false);
        } catch (error) {
            message.error(editingRecord ? 'Cập nhật thất bại!' : 'Thêm mới thất bại!');
            console.error(error);
        }
    };

    const columns = [
        {
            title: 'Tên Danh Mục',
            dataIndex: 'nameCategory',
            key: 'nameCategory',
            render: (text) => <span className="font-medium text-blue-600">{text}</span>,
        },
        {
            title: 'Slug',
            dataIndex: 'slug',
            key: 'slug',
            render: (text) => <Tag>{text}</Tag>,
        },
        {
            title: 'Danh mục cha',
            dataIndex: 'parentId',
            key: 'parentId',
            render: (parentId) => {
                if (!parentId) return <span className="text-gray-400">---</span>;
                const parent = dataCategory.find((item) => item._id === parentId);
                return parent ? parent.nameCategory : 'Unknown';
            },
        },
        {
            title: 'Trạng thái',
            dataIndex: 'isActive',
            key: 'isActive',
            render: (active) => <Tag color={active ? 'success' : 'error'}>{active ? 'Hoạt động' : 'Tạm ẩn'}</Tag>,
        },
        {
            title: 'Hành động',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <Button
                        type="text"
                        icon={<Edit size={16} className="text-blue-500" />}
                        onClick={() => handleEdit(record)}
                    />
                    <Popconfirm
                        title="Xóa danh mục này?"
                        description="Hành động này không thể hoàn tác!"
                        onConfirm={() => handleDelete(record._id)}
                        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ý danh mục</h2>
                <Button type="primary" icon={<Plus size={18} />} onClick={handleAdd} className="bg-blue-600">
                    Thêm danh mục
                </Button>
            </div>

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

            <Modal
                title={editingRecord ? 'Cập nhật danh mục' : 'Thêm danh mục mới'}
                open={isModalOpen}
                onCancel={handleCancel}
                footer={null}
            >
                <Form form={form} layout="vertical" onFinish={onFinish} initialValues={{ isActive: true }}>
                    <Form.Item
                        name="nameCategory"
                        label="Tên danh mục"
                        rules={[{ required: true, message: 'Vui lòng nhập tên danh mục!' }]}
                    >
                        <Input placeholder="Ví dụ: Liên Quân Mobile" />
                    </Form.Item>

                    <Form.Item name="parentId" label="Danh mục cha (Nếu có)">
                        <Select allowClear placeholder="Chọn danh mục cha" options={parentOptions} />
                    </Form.Item>

                    <Form.Item noStyle dependencies={['parentId']}>
                        {({ getFieldValue }) => {
                            const parentId = getFieldValue('parentId');
                            return parentId ? (
                                <Form.Item
                                    name="image"
                                    label="Ảnh danh mục"
                                    valuePropName="fileList"
                                    getValueFromEvent={(e) => {
                                        if (Array.isArray(e)) return e;
                                        return e?.fileList;
                                    }}
                                >
                                    <Upload name="image" listType="picture" maxCount={1} beforeUpload={() => false}>
                                        <Button icon={<UploadOutlined />}>Tải ảnh lên</Button>
                                    </Upload>
                                </Form.Item>
                            ) : null;
                        }}
                    </Form.Item>

                    <Form.Item name="isActive" label="Trạng thái" valuePropName="checked">
                        <Switch checkedChildren="Hoạt động" unCheckedChildren="Tạm ẩn" />
                    </Form.Item>

                    <div className="flex justify-end gap-2 mt-4">
                        <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 CategoryManager;
