import { useForm } from '@inertiajs/react';
import type { FormEvent } from 'react';
import { store as quoteStore } from '@/actions/App/Http/Controllers/QuoteRequestController';
import FileUpload from '@/components/FileUpload';
import InteractiveCaptcha from '@/components/InteractiveCaptcha';
import Select from '@/components/Select';
import type { CaptchaPayload } from '@/types/binder';

interface QuoteRequestFormProps {
    products: Array<{ id: number; name: string; unit?: string }>;
    defaultProductId?: number | null;
    initialCaptcha: CaptchaPayload;
}

export default function QuoteRequestForm({
    products,
    defaultProductId = null,
    initialCaptcha,
}: QuoteRequestFormProps) {
    const { data, setData, post, processing, errors, reset } = useForm<{
        company_or_person_name: string;
        contact_person: string;
        phone: string;
        email: string;
        product_id: string;
        quantity_label: string;
        project_location: string;
        delivery_timeframe: string;
        notes: string;
        attachment: File | null;
        captcha: string;
    }>({
        company_or_person_name: '',
        contact_person: '',
        phone: '',
        email: '',
        product_id: defaultProductId ? String(defaultProductId) : '',
        quantity_label: '',
        project_location: '',
        delivery_timeframe: '',
        notes: '',
        attachment: null,
        captcha: '',
    });

    function handleSubmit(e: FormEvent) {
        e.preventDefault();
        post(quoteStore.url(), {
            preserveScroll: true,
            onSuccess: () =>
                reset('quantity_label', 'notes', 'attachment', 'captcha'),
            onError: () => {
                requestAnimationFrame(() => {
                    document
                        .querySelector<HTMLElement>('[aria-invalid="true"]')
                        ?.scrollIntoView({
                            behavior: 'smooth',
                            block: 'center',
                        });
                });
            },
        });
    }

    return (
        <form onSubmit={handleSubmit} className="space-y-3 sm:space-y-4">
            <div className="grid grid-cols-2 gap-2.5 sm:gap-4">
                <div className="col-span-2 sm:col-span-1">
                    <label className="mb-1 block text-xs font-bold text-slate-700 sm:mb-1.5">
                        نام شرکت / کارفرما{' '}
                        <span className="text-rose-600">*</span>
                    </label>
                    <input
                        type="text"
                        required
                        autoComplete="organization"
                        value={data.company_or_person_name}
                        onChange={(e) =>
                            setData('company_or_person_name', e.target.value)
                        }
                        className="h-10 w-full rounded-xl border border-slate-300 px-3 text-base focus:border-brand-blue focus:outline-none sm:h-11 sm:px-3.5 sm:text-sm"
                    />
                    {errors.company_or_person_name && (
                        <p className="mt-1 text-xs text-rose-600">
                            {errors.company_or_person_name}
                        </p>
                    )}
                </div>

                <div>
                    <label className="mb-1 block text-xs font-bold text-slate-700 sm:mb-1.5">
                        نام و نام خانوادگی رابط{' '}
                        <span className="text-rose-600">*</span>
                    </label>
                    <input
                        type="text"
                        required
                        autoComplete="name"
                        value={data.contact_person}
                        onChange={(e) =>
                            setData('contact_person', e.target.value)
                        }
                        className="h-10 w-full rounded-xl border border-slate-300 px-3 text-base focus:border-brand-blue focus:outline-none sm:h-11 sm:px-3.5 sm:text-sm"
                    />
                    {errors.contact_person && (
                        <p className="mt-1 text-xs text-rose-600">
                            {errors.contact_person}
                        </p>
                    )}
                </div>

                <div>
                    <label className="mb-1 block text-xs font-bold text-slate-700 sm:mb-1.5">
                        تلفن تماس <span className="text-rose-600">*</span>
                    </label>
                    <input
                        type="tel"
                        inputMode="tel"
                        dir="ltr"
                        required
                        autoComplete="tel"
                        value={data.phone}
                        onChange={(e) => setData('phone', e.target.value)}
                        placeholder="0916..."
                        className="h-10 w-full rounded-xl border border-slate-300 px-3 text-left text-base focus:border-brand-blue focus:outline-none sm:h-11 sm:px-3.5 sm:text-sm"
                    />
                    {errors.phone && (
                        <p className="mt-1 text-xs text-rose-600">
                            {errors.phone}
                        </p>
                    )}
                </div>

                <div>
                    <label className="mb-1 block text-xs font-bold text-slate-700 sm:mb-1.5">
                        ایمیل (اختیاری)
                    </label>
                    <input
                        type="email"
                        inputMode="email"
                        dir="ltr"
                        autoComplete="email"
                        value={data.email}
                        onChange={(e) => setData('email', e.target.value)}
                        className="h-10 w-full rounded-xl border border-slate-300 px-3 text-left text-base focus:border-brand-blue focus:outline-none sm:h-11 sm:px-3.5 sm:text-sm"
                    />
                    {errors.email && (
                        <p className="mt-1 text-xs text-rose-600">
                            {errors.email}
                        </p>
                    )}
                </div>

                <div>
                    <label className="mb-1 block text-xs font-bold text-slate-700 sm:mb-1.5">
                        محصول درخواستی
                    </label>
                    <Select
                        value={data.product_id}
                        onChange={(val) => setData('product_id', val)}
                        searchPlaceholder="جستجوی محصول..."
                        options={[
                            {
                                value: '',
                                label: 'انتخاب محصول یا استعلام چندگانه',
                            },
                            ...products.map((p) => ({
                                value: String(p.id),
                                label: p.name,
                                description: p.unit
                                    ? `واحد: ${p.unit}`
                                    : undefined,
                            })),
                        ]}
                    />
                </div>

                <div>
                    <label className="mb-1 block text-xs font-bold text-slate-700 sm:mb-1.5">
                        مقدار / تناژ برآوردی{' '}
                        <span className="text-rose-600">*</span>
                    </label>
                    <input
                        type="text"
                        required
                        value={data.quantity_label}
                        onChange={(e) =>
                            setData('quantity_label', e.target.value)
                        }
                        placeholder="مثلاً ۵۰۰ تن"
                        className="h-10 w-full rounded-xl border border-slate-300 px-3 text-base focus:border-brand-blue focus:outline-none sm:h-11 sm:px-3.5 sm:text-sm"
                    />
                    {errors.quantity_label && (
                        <p className="mt-1 text-xs text-rose-600">
                            {errors.quantity_label}
                        </p>
                    )}
                </div>

                <div>
                    <label className="mb-1 block text-xs font-bold text-slate-700 sm:mb-1.5">
                        محل پروژه / تحویل{' '}
                        <span className="text-rose-600">*</span>
                    </label>
                    <input
                        type="text"
                        required
                        value={data.project_location}
                        onChange={(e) =>
                            setData('project_location', e.target.value)
                        }
                        placeholder="شهر / محور اجرایی"
                        className="h-10 w-full rounded-xl border border-slate-300 px-3 text-base focus:border-brand-blue focus:outline-none sm:h-11 sm:px-3.5 sm:text-sm"
                    />
                    {errors.project_location && (
                        <p className="mt-1 text-xs text-rose-600">
                            {errors.project_location}
                        </p>
                    )}
                </div>

                <div className="col-span-2 sm:col-span-1">
                    <label className="mb-1 block text-xs font-bold text-slate-700 sm:mb-1.5">
                        زمان‌بندی نیاز
                    </label>
                    <input
                        type="text"
                        value={data.delivery_timeframe}
                        onChange={(e) =>
                            setData('delivery_timeframe', e.target.value)
                        }
                        placeholder="مثلاً فوری / ماه آینده"
                        className="h-10 w-full rounded-xl border border-slate-300 px-3 text-base focus:border-brand-blue focus:outline-none sm:h-11 sm:px-3.5 sm:text-sm"
                    />
                </div>
            </div>

            <FileUpload
                label="فایل مشخصات یا برآورد (اختیاری — حداکثر ۵ مگابایت)"
                hint="فرمت‌های مجاز: PDF، JPG، PNG، XLSX، DOCX"
                accept=".pdf,.jpg,.jpeg,.png,.xlsx,.docx"
                file={data.attachment}
                onChange={(file) => setData('attachment', file)}
                error={errors.attachment}
            />

            <div>
                <label className="mb-1 block text-xs font-bold text-slate-700 sm:mb-1.5">
                    توضیحات تکمیلی
                </label>
                <textarea
                    rows={2}
                    value={data.notes}
                    onChange={(e) => setData('notes', e.target.value)}
                    className="w-full rounded-xl border border-slate-300 p-3 text-base focus:border-brand-blue focus:outline-none sm:text-sm"
                />
            </div>

            <InteractiveCaptcha
                initialCaptcha={initialCaptcha}
                value={data.captcha}
                onChange={(val) => setData('captcha', val)}
                error={errors.captcha}
            />

            <button
                type="submit"
                disabled={processing}
                className="w-full rounded-xl bg-brand-orange px-6 py-3.5 text-sm font-bold text-white shadow-sm transition hover:bg-orange-700 disabled:opacity-60"
            >
                {processing
                    ? 'در حال ثبت درخواست...'
                    : 'ارسال درخواست استعلام قیمت و دریافت کد پیگیری'}
            </button>
        </form>
    );
}
