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

interface JobApplicationFormProps {
    jobs: Array<{ id: number; title: string }>;
    defaultJobId?: number | null;
    initialCaptcha: CaptchaPayload;
}

export default function JobApplicationForm({
    jobs,
    defaultJobId = null,
    initialCaptcha,
}: JobApplicationFormProps) {
    const { data, setData, post, processing, errors, reset } = useForm<{
        job_posting_id: string;
        full_name: string;
        phone: string;
        email: string;
        education_level: string;
        years_of_experience: string;
        specialty: string;
        cover_letter: string;
        cv_file: File | null;
        captcha: string;
    }>({
        job_posting_id: defaultJobId ? String(defaultJobId) : '',
        full_name: '',
        phone: '',
        email: '',
        education_level: 'کارشناسی',
        years_of_experience: '2',
        specialty: '',
        cover_letter: '',
        cv_file: null,
        captcha: '',
    });

    function handleSubmit(e: FormEvent) {
        e.preventDefault();
        post(careerApply.url(), {
            preserveScroll: true,
            onSuccess: () => reset('cover_letter', 'cv_file', '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">
                {!defaultJobId && (
                    <div className="col-span-2">
                        <label className="mb-1 block text-xs font-bold text-slate-700 sm:mb-1.5">
                            موقعیت شغلی مورد نظر
                        </label>
                        <Select
                            value={data.job_posting_id}
                            onChange={(val) => setData('job_posting_id', val)}
                            options={[
                                {
                                    value: '',
                                    label: 'ارسال رزومه عمومی (بانک کارگزینی)',
                                },
                                ...jobs.map((job) => ({
                                    value: String(job.id),
                                    label: job.title,
                                })),
                            ]}
                        />
                    </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.full_name}
                        onChange={(e) => setData('full_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.full_name && (
                        <p className="mt-1 text-xs text-rose-600">
                            {errors.full_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="tel"
                        inputMode="tel"
                        dir="ltr"
                        required
                        autoComplete="tel"
                        value={data.phone}
                        onChange={(e) => setData('phone', 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.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"
                    />
                </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>
                    <Select
                        value={data.education_level}
                        onChange={(val) => setData('education_level', val)}
                        options={[
                            {
                                value: 'دیپلم و کاردانی',
                                label: 'دیپلم و کاردانی فنی',
                            },
                            { value: 'کارشناسی', label: 'کارشناسی' },
                            { value: 'کارشناسی ارشد', label: 'کارشناسی ارشد' },
                            { value: 'دکتری', label: 'دکتری' },
                        ]}
                    />
                </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.specialty}
                        onChange={(e) => setData('specialty', 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.specialty && (
                        <p className="mt-1 text-xs text-rose-600">
                            {errors.specialty}
                        </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="number"
                        inputMode="numeric"
                        min={0}
                        max={60}
                        required
                        value={data.years_of_experience}
                        onChange={(e) =>
                            setData('years_of_experience', 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"
                    />
                </div>
            </div>

            <FileUpload
                label="فایل رزومه (PDF، DOC یا DOCX — حداکثر ۵ مگابایت)"
                hint="فایل رزومه خود را انتخاب کنید"
                accept=".pdf,.doc,.docx"
                required
                file={data.cv_file}
                onChange={(file) => setData('cv_file', file)}
                error={errors.cv_file}
            />

            <div>
                <label className="mb-1 block text-xs font-bold text-slate-700 sm:mb-1.5">
                    توضیحات تکمیلی
                </label>
                <textarea
                    rows={2}
                    value={data.cover_letter}
                    onChange={(e) => setData('cover_letter', 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-blue px-6 py-3.5 text-sm font-bold text-white shadow-sm transition hover:bg-blue-900 disabled:opacity-60"
            >
                {processing
                    ? 'در حال ارسال رزومه...'
                    : 'ارسال رزومه و درخواست همکاری'}
            </button>
        </form>
    );
}
