import React, { useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useCreateShippingMethod, useShippingMethod, useUpdateShippingMethod } from '../core/_hooks';
import { ShippingOpenHour } from '../core/_models';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { TagInput } from '@/components/ui/TagInput';
import { PageContainer } from '@/components/ui/Typography';
import { PageHeader } from '@/components/layout/PageHeader';
import { Truck } from 'lucide-react';
import { formatWithThousands, parseFormattedNumber } from '@/utils/numberUtils';

const ShippingMethodFormPage = () => {
    const navigate = useNavigate();
    const { id } = useParams();

    const isEdit = Boolean(id);
    const { data, isLoading } = useShippingMethod(id || '');
    const { mutate: create, isPending: creating } = useCreateShippingMethod();
    const { mutate: update, isPending: updating } = useUpdateShippingMethod();

    const [form, setForm] = React.useState({
        name: '',
        description: '',
        code: '',
        enabled: true,
        max_weight: '',
        min_weight: '',
        priority: '',
        time_note: '',
        open_hours: [
            {
                from_hour: '',
                to_hour: '',
            },
        ],
        addresses: [] as string[],
        needs_address: false,
    });

    useEffect(() => {
        if (isEdit && data) {
            const normalizedOpenHours = (data.open_hours || []).map((item: ShippingOpenHour) => ({
                from_hour: item?.from_hour?.toString() || '',
                to_hour: item?.to_hour?.toString() || '',
            }));
            setForm({
                name: data.name || '',
                description: data.description || '',
                code: data.code || '',
                enabled: data.enabled,
                max_weight: formatWithThousands(data.max_weight ?? ''),
                min_weight: formatWithThousands(data.min_weight ?? ''),
                priority: formatWithThousands(data.priority ?? ''),
                time_note: data.time_note || '',
                open_hours: normalizedOpenHours.length
                    ? normalizedOpenHours
                    : [
                        {
                            from_hour: '',
                            to_hour: '',
                        },
                    ],
                addresses: data.addresses || [],
                needs_address: data.needs_address ?? false,
            });
        }
    }, [isEdit, data]);

    const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
        const { name, value, type, checked } = e.target as any;
        setForm(prev => ({
            ...prev,
            [name]: type === 'checkbox' ? checked : value,
        }));
    };

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        const payload = {
            name: form.name,
            description: form.description,
            code: form.code,
            enabled: form.enabled,
            max_weight: parseFormattedNumber(form.max_weight) ?? 0,
            min_weight: parseFormattedNumber(form.min_weight) ?? 0,
            priority: parseFormattedNumber(form.priority) ?? 0,
            time_note: form.time_note,
            open_hours: form.open_hours
                .map((item) => ({
                    from_hour: Number(item.from_hour),
                    to_hour: Number(item.to_hour),
                }))
                .filter(
                    (item) =>
                        !Number.isNaN(item.from_hour) &&
                        !Number.isNaN(item.to_hour)
                ),
            addresses: form.addresses,
            needs_address: form.needs_address,
        };
        if (isEdit && id) {
            update({ id: Number(id), ...payload }, { onSuccess: () => navigate('/shipping-methods') });
        } else {
            create(payload, { onSuccess: () => navigate('/shipping-methods') });
        }
    };

    if (isEdit && isLoading) {
        return (
            <PageContainer>
                <div className="space-y-6 animate-pulse">
                    <div className="h-8 bg-gray-200 dark:bg-gray-700 rounded w-48"></div>
                    <div className="card p-6 space-y-6">
                        {[...Array(5)].map((_, i) => (
                            <div key={i}>
                                <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-32 mb-2"></div>
                                <div className="h-10 bg-gray-200 dark:bg-gray-700 rounded"></div>
                            </div>
                        ))}
                    </div>
                </div>
            </PageContainer>
        );
    }

    return (
        <div className="p-6 space-y-6">
            <PageHeader
                title={isEdit ? 'ویرایش روش ارسال' : 'ایجاد روش ارسال'}
                icon={Truck}
            />

            <form onSubmit={handleSubmit} className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg p-4 space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">نام</label>
                        <Input name="name" value={form.name} onChange={handleChange} placeholder="مثلاً Standard Shipping" />
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">کد</label>
                        <Input name="code" value={form.code} onChange={handleChange} placeholder="مثلاً standard" />
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">اولویت</label>
                        <Input name="priority" value={form.priority} onChange={handleChange} thousandSeparator numeric />
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">کمترین وزن</label>
                        <Input name="min_weight" value={form.min_weight} onChange={handleChange} thousandSeparator numeric />
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">بیشترین وزن</label>
                        <Input name="max_weight" value={form.max_weight} onChange={handleChange} thousandSeparator numeric />
                    </div>
                    <div className="md:col-span-2">
                        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">یادداشت زمان تحویل</label>
                        <Input name="time_note" value={form.time_note} onChange={handleChange} placeholder="مثلاً تحویل طی ۲۴ ساعت" />
                    </div>
                    <div className="md:col-span-2 space-y-3">
                        <div className="flex items-start justify-between gap-3">
                            <div className="space-y-1">
                                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300">ساعات پاسخگویی</label>
                                <p className="text-xs text-gray-500 dark:text-gray-400">بازه‌های زمانی را به ساعت ۲۴ ساعته وارد کنید</p>
                            </div>
                            <Button size="sm" type="button" variant="secondary" onClick={() => setForm(prev => ({
                                ...prev,
                                open_hours: [
                                    ...prev.open_hours,
                                    { from_hour: '', to_hour: '' },
                                ],
                            }))}>
                                افزودن بازه
                            </Button>
                        </div>
                        <div className="space-y-3">
                            {form.open_hours.map((item, index) => (
                                <div key={index} className="border border-gray-200 dark:border-gray-700 rounded-lg bg-gray-50 dark:bg-gray-700/50 p-3 space-y-3">
                                    <div className="grid grid-cols-1 md:grid-cols-5 gap-3 items-end">
                                        <div className="md:col-span-2">
                                            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">از ساعت</label>
                                            <Input
                                                name={`open_hours_from_${index}`}
                                                value={item.from_hour}
                                                onChange={(e) => {
                                                    const value = (e.target as HTMLInputElement).value;
                                                    setForm(prev => {
                                                        const open_hours = [...prev.open_hours];
                                                        open_hours[index] = { ...open_hours[index], from_hour: value };
                                                        return { ...prev, open_hours };
                                                    });
                                                }}
                                                numeric
                                                placeholder="مثلاً 9"
                                            />
                                        </div>
                                        <div className="md:col-span-2">
                                            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">تا ساعت</label>
                                            <Input
                                                name={`open_hours_to_${index}`}
                                                value={item.to_hour}
                                                onChange={(e) => {
                                                    const value = (e.target as HTMLInputElement).value;
                                                    setForm(prev => {
                                                        const open_hours = [...prev.open_hours];
                                                        open_hours[index] = { ...open_hours[index], to_hour: value };
                                                        return { ...prev, open_hours };
                                                    });
                                                }}
                                                numeric
                                                placeholder="مثلاً 18"
                                            />
                                        </div>
                                        <div className="flex md:justify-end">
                                            <Button
                                                type="button"
                                                variant="danger"
                                                size="sm"
                                                onClick={() => setForm(prev => {
                                                    const open_hours = prev.open_hours.filter((_, i) => i !== index);
                                                    return {
                                                        ...prev,
                                                        open_hours: open_hours.length ? open_hours : [
                                                            {
                                                                from_hour: '',
                                                                to_hour: '',
                                                            },
                                                        ],
                                                    };
                                                })}
                                            >
                                                حذف
                                            </Button>
                                        </div>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                    <div className="md:col-span-2">
                        <TagInput
                            values={form.addresses}
                            onChange={(values) => setForm(prev => ({ ...prev, addresses: values }))}
                            label="محدوده‌های پوشش"
                            placeholder="آدرس را تایپ و Enter کنید"
                        />
                    </div>
                    <div className="md:col-span-2">
                        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">توضیحات</label>
                        <textarea name="description" value={form.description} onChange={handleChange} className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-1 focus:ring-primary-500 dark:bg-gray-700 dark:text-gray-100" rows={3} />
                    </div>
                    <div className="md:col-span-2">
                        <label className="inline-flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
                            <input type="checkbox" name="enabled" checked={form.enabled} onChange={handleChange} className="rounded border-gray-300 dark:border-gray-600" />
                            فعال
                        </label>
                    </div>
                    <div className="md:col-span-2">
                        <label className="inline-flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
                            <input type="checkbox" name="needs_address" checked={form.needs_address} onChange={handleChange} className="rounded border-gray-300 dark:border-gray-600" />
                            نیاز به آدرس اجباری است
                        </label>
                        <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                            در صورت فعال بودن، کاربر باید حتماً آدرس تحویل را وارد کند
                        </p>
                    </div>
                </div>

                <div className="flex justify-end gap-2">
                    <Button type="button" variant="secondary" onClick={() => navigate('/shipping-methods')}>
                        انصراف
                    </Button>
                    <Button type="submit" loading={creating || updating}>
                        {isEdit ? 'ذخیره تغییرات' : 'ایجاد'}
                    </Button>
                </div>
            </form>
        </div>
    );
};

export default ShippingMethodFormPage;


