import { useState, useEffect } from 'react';
import { Form, Input, Button, Upload, message, Card, Row, Col, Divider, Select } from 'antd';
import { UploadOutlined, SaveOutlined } from '@ant-design/icons';
import { getWebsite, updateWebsite } from '../../config/website';

const WebsiteManager = () => {
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [logoFileList, setLogoFileList] = useState([]);
    const [faviconFileList, setFaviconFileList] = useState([]);
    const [bannerFileList, setBannerFileList] = useState([]);

    const fetchWebsiteData = async () => {
        try {
            setLoading(true);
            const data = await getWebsite();
            if (data) {
                // Initialize file lists for existing images
                if (data.logo) {
                    setLogoFileList([
                        {
                            uid: '-1',
                            name: 'logo.png',
                            status: 'done',
                            url: `${data.logo}`,
                        },
                    ]);
                }
                if (data.favicon) {
                    setFaviconFileList([
                        {
                            uid: '-2',
                            name: 'favicon.ico',
                            status: 'done',
                            url: `${data.favicon}`,
                        },
                    ]);
                }
                if (data.banner && Array.isArray(data.banner)) {
                    const banners = data.banner.map((url, index) => ({
                        uid: `-${index + 3}`,
                        name: `banner-${index + 1}.png`,
                        status: 'done',
                        url: `${url}`,
                    }));
                    setBannerFileList(banners);
                }

                form.setFieldsValue({
                    ...data,
                });
            }
        } catch (error) {
            message.error('Không thể tải thông tin website!');
            console.error(error);
        } finally {
            setLoading(false);
        }
    };

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

    const onFinish = async (values) => {
        try {
            setLoading(true);
            const formData = new FormData();

            // Append text fields
            Object.keys(values).forEach((key) => {
                if (
                    key !== 'logo' &&
                    key !== 'favicon' &&
                    key !== 'banner' &&
                    values[key] !== undefined &&
                    values[key] !== null
                ) {
                    formData.append(key, values[key]);
                }
            });

            // Append files
            if (logoFileList.length > 0 && logoFileList[0].originFileObj) {
                formData.append('logo', logoFileList[0].originFileObj);
            }
            if (faviconFileList.length > 0 && faviconFileList[0].originFileObj) {
                formData.append('favicon', faviconFileList[0].originFileObj);
            }
            // Append banners: separate existing URLs and new files
            const existingBanners = [];
            if (bannerFileList.length > 0) {
                bannerFileList.forEach((file) => {
                    if (file.originFileObj) {
                        formData.append('banner', file.originFileObj);
                    } else if (file.url) {
                        // Extract relative path from full URL
                        const relativePath = file.url.replace(`${import.meta.env.VITE_API_URL}/uploads/websites`, '');
                        existingBanners.push(relativePath);
                    }
                });
            }
            // Append existing banners as multiple fields with same name 'banner' or handled by backend
            // To ensure array structure in backend, we append each existing banner as 'banner' text field
            existingBanners.forEach((banner) => {
                formData.append('banner', banner);
            });
            // If no banners (existing or new), we might want to send an empty indicator if needed,
            // but our backend logic checks for existence.
            // If user deleted all, existingBanners is empty, no new files. req.body.banner undefined.
            // To support "Delete All", we should append an empty string if strictly empty and we want to wipe it.
            if (bannerFileList.length === 0) {
                formData.append('banner', '');
            }

            await updateWebsite(formData);
            message.success('Cập nhật thông tin website thành công!');

            // Refresh data to ensure strict sync
            await fetchWebsiteData();
        } catch (error) {
            message.error('Cập nhật thất bại!');
            console.error(error);
        } finally {
            setLoading(false);
        }
    };

    const handleLogoChange = ({ fileList }) => setLogoFileList(fileList);
    const handleFaviconChange = ({ fileList }) => setFaviconFileList(fileList);
    const handleBannerChange = ({ fileList }) => setBannerFileList(fileList);

    return (
        <div className="p-4">
            <h2 className="text-2xl font-bold mb-6 text-gray-800">Quản lý cấu hình Website</h2>

            <Card className="shadow-md rounded-lg">
                <Form form={form} layout="vertical" onFinish={onFinish} disabled={loading}>
                    <Row gutter={24}>
                        <Col span={24} md={12}>
                            <Divider orientation="left">Thông tin chung</Divider>

                            <Form.Item
                                name="nameWebsite"
                                label="Tên Website"
                                rules={[{ required: true, message: 'Vui lòng nhập tên website!' }]}
                            >
                                <Input placeholder="Nhập tên website" />
                            </Form.Item>

                            <Form.Item
                                name="description"
                                label="Mô tả"
                                rules={[{ required: true, message: 'Vui lòng nhập mô tả website!' }]}
                            >
                                <Input.TextArea rows={4} placeholder="Nhập mô tả website" />
                            </Form.Item>

                            <Form.Item
                                name="keywords"
                                label="Từ khóa (Keywords)"
                                help="Các từ khóa ngăn cách nhau bằng dấu phẩy"
                            >
                                <Input.TextArea rows={2} placeholder="Ví dụ: game, nick, acc..." />
                            </Form.Item>

                            <Form.Item name="status" label="Trạng thái Website">
                                <Select>
                                    <Select.Option value="active">Hoạt động</Select.Option>
                                    <Select.Option value="maintenance">Bảo trì</Select.Option>
                                </Select>
                            </Form.Item>
                        </Col>

                        <Col span={24} md={12}>
                            <Divider orientation="left">Liên hệ & Chủ sở hữu</Divider>

                            <Form.Item name="author" label="Tác giả/Chủ sở hữu">
                                <Input placeholder="Tên tác giả" />
                            </Form.Item>

                            <Form.Item name="contact" label="Thông tin liên hệ (Email/SĐT)">
                                <Input placeholder="Email hoặc số điện thoại" />
                            </Form.Item>

                            <Form.Item name="social" label="Mạng xã hội">
                                <Input placeholder="Link Facebook, Zalo, etc." />
                            </Form.Item>
                        </Col>
                    </Row>

                    <Row gutter={24}>
                        <Col span={24} md={12}>
                            <Divider orientation="left">Hình ảnh</Divider>

                            <Form.Item label="Logo Website">
                                <Upload
                                    listType="picture-card"
                                    fileList={logoFileList}
                                    onChange={handleLogoChange}
                                    beforeUpload={() => false} // Prevent auto upload
                                    maxCount={1}
                                    accept="image/*"
                                >
                                    {logoFileList.length < 1 && (
                                        <div>
                                            <UploadOutlined />
                                            <div style={{ marginTop: 8 }}>Upload</div>
                                        </div>
                                    )}
                                </Upload>
                            </Form.Item>

                            <Form.Item label="Favicon">
                                <Upload
                                    listType="picture-card"
                                    fileList={faviconFileList}
                                    onChange={handleFaviconChange}
                                    beforeUpload={() => false} // Prevent auto upload
                                    maxCount={1}
                                    accept="image/*"
                                >
                                    {faviconFileList.length < 1 && (
                                        <div>
                                            <UploadOutlined />
                                            <div style={{ marginTop: 8 }}>Upload</div>
                                        </div>
                                    )}
                                </Upload>
                            </Form.Item>

                            <Form.Item label="Banner Website (Nhiều ảnh)">
                                <Upload
                                    listType="picture-card"
                                    fileList={bannerFileList}
                                    onChange={handleBannerChange}
                                    beforeUpload={() => false} // Prevent auto upload
                                    multiple={true}
                                    accept="image/*"
                                >
                                    <div>
                                        <UploadOutlined />
                                        <div style={{ marginTop: 8 }}>Upload</div>
                                    </div>
                                </Upload>
                            </Form.Item>
                        </Col>
                    </Row>

                    <Divider />

                    <div className="flex justify-end">
                        <Button
                            type="primary"
                            htmlType="submit"
                            icon={<SaveOutlined />}
                            size="large"
                            loading={loading}
                            className="bg-blue-600"
                        >
                            Lưu cấu hình
                        </Button>
                    </div>
                </Form>
            </Card>
        </div>
    );
};

export default WebsiteManager;
