import { useEffect, useState } from 'react';
import { Button, Form, Input, Spin, Upload, message } from 'antd';
import type { UploadFile, UploadProps } from 'antd';
import ImgCrop from 'antd-img-crop';
import { SaveOutlined, ShopOutlined, UploadOutlined } from '@ant-design/icons';
import { AppContainer } from '../../../components/AppContainer';
import jwtAxios from '../../../api/axiosInstance';
import { ENDPOINTS } from '../../../api/endpoints';

const ENTITY_LABEL = 'Shop Settings';
const ENTITY_ENDPOINT = ENDPOINTS.SHOP; // add SHOP: '/shop' to your endpoints file

interface ShopRecord {
    id: number;
    shopName: string;
    shortName?: string | null;
    address: string;
    mobile: string;
    mobile2?: string | null;
    mapUrl?: string | null;
    godName1?: string | null;
    godName2?: string | null;
    godName3?: string | null;
    logo: string | null;
    logoUrl: string | null;
    godImage1?: string | null;
    godImage1Url?: string | null;
    godImage2?: string | null;
    godImage2Url?: string | null;
    authorizedSign: string | null;
    authorizedSignUrl: string | null;
    createdAt: string;
    updatedAt: string;
}

const Shop = () => {
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [saving, setSaving] = useState(false);
    const [record, setRecord] = useState<ShopRecord | null>(null);

    // Holds the new logo file the user just picked, if any.
    const [fileList, setFileList] = useState<UploadFile[]>([]);

    // Holds God Image 1 & 2 files
    const [godImage1List, setGodImage1List] = useState<UploadFile[]>([]);
    const [godImage2List, setGodImage2List] = useState<UploadFile[]>([]);

    // Holds the authorized signature image.
    const [signList, setSignList] = useState<UploadFile[]>([]);

    // -----------------------------
    // Fetch the single shop record on mount.
    // -----------------------------
    const fetchData = async () => {
        setLoading(true);
        try {
            const res = await jwtAxios.get(ENTITY_ENDPOINT);
            const shop: ShopRecord | null = res.data?.data ?? null;

            if (shop) {
                form.setFieldsValue({
                    shopName: shop.shopName,
                    shortName: shop.shortName || 'AVS',
                    godName1: shop.godName1,
                    godName2: shop.godName2,
                    godName3: shop.godName3,
                    address: shop.address,
                    mobile: shop.mobile,
                    mobile2: shop.mobile2,
                    mapUrl: shop.mapUrl,
                });
                setRecord(shop);
            }
        } catch (err: any) {
            message.error(err.response?.data?.message || `Failed to load ${ENTITY_LABEL.toLowerCase()}`);
        } finally {
            setLoading(false);
        }
    };

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

    const uploadProps: UploadProps = {
        listType: 'picture-card',
        fileList,
        maxCount: 1,
        accept: 'image/*',
        beforeUpload: () => false,
        onChange: ({ fileList: newList }) => setFileList(newList.slice(-1)),
        onRemove: () => setFileList([]),
    };

    const godImage1Props: UploadProps = {
        listType: 'picture-card',
        fileList: godImage1List,
        maxCount: 1,
        accept: 'image/*',
        beforeUpload: () => false,
        onChange: ({ fileList: newList }) => setGodImage1List(newList.slice(-1)),
        onRemove: () => setGodImage1List([]),
    };

    const godImage2Props: UploadProps = {
        listType: 'picture-card',
        fileList: godImage2List,
        maxCount: 1,
        accept: 'image/*',
        beforeUpload: () => false,
        onChange: ({ fileList: newList }) => setGodImage2List(newList.slice(-1)),
        onRemove: () => setGodImage2List([]),
    };

    const signatureProps: UploadProps = {
        listType: 'picture-card',
        fileList: signList,
        maxCount: 1,
        accept: 'image/*',
        beforeUpload: () => false,
        onChange: ({ fileList: newList }) => setSignList(newList.slice(-1)),
        onRemove: () => setSignList([]),
    };

    const handleSubmit = async (values: any) => {
        setSaving(true);

        const formData = new FormData();
        formData.append('shopName', values.shopName);
        formData.append('shortName', (values.shortName?.trim() || 'AVS').slice(0, 3));
        if (values.godName1) formData.append('godName1', values.godName1);
        if (values.godName2) formData.append('godName2', values.godName2);
        if (values.godName3) formData.append('godName3', values.godName3);
        formData.append('address', values.address);
        formData.append('mobile', values.mobile);
        if (values.mobile2) formData.append('mobile2', values.mobile2);
        if (values.mapUrl) formData.append('mapUrl', values.mapUrl);

        const newLogo = fileList[0]?.originFileObj;
        if (newLogo) {
            formData.append('logo', newLogo);
        }

        const newGodImage1 = godImage1List[0]?.originFileObj;
        if (newGodImage1) {
            formData.append('godImage1', newGodImage1);
        }

        const newGodImage2 = godImage2List[0]?.originFileObj;
        if (newGodImage2) {
            formData.append('godImage2', newGodImage2);
        }

        const newSignature = signList[0]?.originFileObj;
        if (newSignature) {
            formData.append('authorizedSign', newSignature);
        }

        try {
            const res = await jwtAxios.post(`${ENTITY_ENDPOINT}`, formData, {
                headers: { 'Content-Type': 'multipart/form-data' },
            });

            message.success(res.data?.message || `${ENTITY_LABEL} saved successfully`);
            setRecord(res.data?.data ?? null);
            setFileList([]);
            setGodImage1List([]);
            setGodImage2List([]);
            setSignList([]);
        } catch (err: any) {
            message.error(err.response?.data?.message || `Failed to save ${ENTITY_LABEL.toLowerCase()}`);
        } finally {
            setSaving(false);
        }
    };

    const currentLogoUrl = record?.logoUrl ?? null;
    const currentGodImage1Url = record?.godImage1Url ?? record?.godImage1 ?? null;
    const currentGodImage2Url = record?.godImage2Url ?? record?.godImage2 ?? null;
    const currentSignUrl = record?.authorizedSignUrl ?? null;

    return (
        <div>
            <Spin spinning={loading}>
                <AppContainer
                    title={ENTITY_LABEL}
                    headerAction={
                        <Button
                            type="primary"
                            icon={<SaveOutlined />}
                            loading={saving}
                            onClick={() => form.submit()}
                            className="bg-green-600"
                        >
                            Save
                        </Button>
                    }
                >
                    <div className="flex items-center gap-2 mb-4 pb-4 border-b border-gray-200 text-gray-500">
                        <ShopOutlined />
                        <span>This information appears on receipts, invoices, and shop headers.</span>
                    </div>

                    <Form form={form} layout="vertical" onFinish={handleSubmit} initialValues={{ shortName: 'AVS' }}>
                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-x-6">
                            <Form.Item label="Shop Name" name="shopName" rules={[{ required: true, message: "Shop Name is required" }]}>
                                <Input placeholder="AVS Super Market" />
                            </Form.Item>

                            <Form.Item
                                label="Short Name (Max 3 Chars)"
                                name="shortName"
                                rules={[
                                    { max: 3, message: "Maximum 3 characters allowed" },
                                ]}
                            >
                                <Input placeholder="AVS" maxLength={3} />
                            </Form.Item>

                            <Form.Item label="God Name 1" name="godName1" rules={[{ required: true, message: "God Name 1 is required" }]}>
                                <Input placeholder="ஸ்ரீ உருமணசாமி துணை" />
                            </Form.Item>

                            <Form.Item label="God Name 2" name="godName2" rules={[{ required: true, message: "God Name 2 is required" }]}>
                                <Input placeholder="ஸ்ரீ சமயபுர மாரியம்மன் துணை" />
                            </Form.Item>

                            <Form.Item label="God Name 3" name="godName3" rules={[{ required: true, message: "God Name 3 is required" }]}>
                                <Input placeholder="ஸ்ரீ காளியம்மன் துணை" />
                            </Form.Item>

                            <Form.Item
                                label="Mobile"
                                name="mobile"
                                rules={[
                                    { required: true, message: "Mobile number is required" },
                                    { pattern: /^[6-9]\d{9}$/, message: "Please enter a valid 10-digit Indian mobile number" },
                                ]}
                            >
                                <Input placeholder="9876543210" maxLength={10} />
                            </Form.Item>

                            <Form.Item
                                label="Mobile 2"
                                name="mobile2"
                                rules={[
                                    { pattern: /^[6-9]\d{9}$/, message: "Please enter a valid 10-digit Indian mobile number" },
                                ]}
                            >
                                <Input placeholder="9876543210" maxLength={10} />
                            </Form.Item>


                        </div>
                        <Form.Item
                            label="Map URL"
                            name="mapUrl"
                            rules={[{ required: true, message: "Map URL is required" }]}

                        >
                            <Input placeholder="https://maps.google.com/" />
                        </Form.Item>

                        <Form.Item label="Address" name="address" rules={[{ required: true, message: "Address is required" }]}>
                            <Input.TextArea rows={3} placeholder="25, Anna Nagar, Madurai" />
                        </Form.Item>

                        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 mt-4">
                            <Form.Item label="Logo (1:1)">
                                <ImgCrop aspect={1} rotationSlider>
                                    <Upload {...uploadProps}>
                                        {fileList.length === 0 && (
                                            currentLogoUrl ? (
                                                <img
                                                    src={currentLogoUrl}
                                                    alt="Current logo"
                                                    className="w-full h-full object-cover"
                                                />
                                            ) : (
                                                <div className="flex flex-col items-center justify-center">
                                                    <UploadOutlined />
                                                    <span className="mt-2 text-xs">Upload Logo</span>
                                                </div>
                                            )
                                        )}
                                    </Upload>
                                </ImgCrop>
                                {currentLogoUrl && fileList.length === 0 && (
                                    <span className="text-xs text-gray-400">Click to replace</span>
                                )}
                            </Form.Item>

                            <Form.Item label="God Image 1 (1:1)">
                                <ImgCrop aspect={1} rotationSlider>
                                    <Upload {...godImage1Props}>
                                        {godImage1List.length === 0 && (
                                            currentGodImage1Url ? (
                                                <img
                                                    src={currentGodImage1Url}
                                                    alt="Current God Image 1"
                                                    className="w-full h-full object-cover"
                                                />
                                            ) : (
                                                <div className="flex flex-col items-center justify-center">
                                                    <UploadOutlined />
                                                    <span className="mt-2 text-xs">Upload Image 1</span>
                                                </div>
                                            )
                                        )}
                                    </Upload>
                                </ImgCrop>
                                {currentGodImage1Url && godImage1List.length === 0 && (
                                    <span className="text-xs text-gray-400">Click to replace</span>
                                )}
                            </Form.Item>

                            <Form.Item label="God Image 2 (1:1)">
                                <ImgCrop aspect={1} rotationSlider>
                                    <Upload {...godImage2Props}>
                                        {godImage2List.length === 0 && (
                                            currentGodImage2Url ? (
                                                <img
                                                    src={currentGodImage2Url}
                                                    alt="Current God Image 2"
                                                    className="w-full h-full object-cover"
                                                />
                                            ) : (
                                                <div className="flex flex-col items-center justify-center">
                                                    <UploadOutlined />
                                                    <span className="mt-2 text-xs">Upload Image 2</span>
                                                </div>
                                            )
                                        )}
                                    </Upload>
                                </ImgCrop>
                                {currentGodImage2Url && godImage2List.length === 0 && (
                                    <span className="text-xs text-gray-400">Click to replace</span>
                                )}
                            </Form.Item>

                            <Form.Item label="Authorized Signature">
                                <ImgCrop aspect={3 / 1} rotationSlider>
                                    <Upload {...signatureProps}>
                                        {signList.length === 0 && (
                                            currentSignUrl ? (
                                                <img
                                                    src={currentSignUrl}
                                                    alt="Current signature"
                                                    className="w-full h-full object-contain"
                                                />
                                            ) : (
                                                <div className="flex flex-col items-center justify-center">
                                                    <UploadOutlined />
                                                    <span className="mt-2 text-xs">Upload Sign</span>
                                                </div>
                                            )
                                        )}
                                    </Upload>
                                </ImgCrop>
                                {currentSignUrl && signList.length === 0 && (
                                    <span className="text-xs text-gray-400">Click to replace</span>
                                )}
                            </Form.Item>
                        </div>
                    </Form>
                </AppContainer>
            </Spin>
        </div>
    );
};

export default Shop;