import React, { useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useCreateShippingMethod, useShippingMethod, useUpdateShippingMethod } from '../core/_hooks';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { LoadingSpinner } from '@/components/ui/LoadingSpinner';
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,
        cost: '',
        max_weight: '',
        min_weight: '',
        priority: '',
    });

    useEffect(() => {
        if (isEdit && data) {
            setForm({
                name: data.name || '',
                description: data.description || '',
                code: data.code || '',
                enabled: data.enabled,
                cost: formatWithThousands(data.cost ?? ''),
                max_weight: formatWithThousands(data.max_weight ?? ''),
                min_weight: formatWithThousands(data.min_weight ?? ''),
                priority: formatWithThousands(data.priority ?? ''),
            });
        }
    }, [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,
            cost: parseFormattedNumber(form.cost) ?? 0,
            max_weight: parseFormattedNumber(form.max_weight) ?? 0,
            min_weight: parseFormattedNumber(form.min_weight) ?? 0,
            priority: parseFormattedNumber(form.priority) ?? 0,
        };
        if (isEdit && id) {
            update({ id: Number(id), ...payload }, { onSuccess: () => navigate('/shipping-methods') });
        } else {
            create(payload, { onSuccess: () => navigate('/shipping-methods') });
        }
    };

    if (isEdit && isLoading) {
        return (
            <div className="min-h-[200px] flex items-center justify-center">
                <LoadingSpinner />
            </div>
        );
    }

    return (
        <div className="p-6 space-y-6">
            <div>
                <h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100 flex items-center gap-2">
                    <Truck className="h-6 w-6" />
                    {isEdit ? 'ویرایش روش ارسال' : 'ایجاد روش ارسال'}
                </h1>
            </div>

            <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="cost" value={form.cost} 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="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>
                        <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>

                <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;


