"use client";
import React, { useEffect, useMemo, useState, useCallback } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";

import { Button } from "@/components/ui/button";
import { Form, FormControl, FormField, FormItem, FormMessage } from "@/components/ui/form";
import { t } from "@/lib/i18n";
import Image from "next/image";

import pdfIcon from "@/src/assets/images/pdficon.svg";
import pdf from "@/src/assets/images/pdf.svg";
import nationalCardIcon from "@/src/assets/images/license/nationalCardIcon.svg";
import healthy from "@/src/assets/images/license/healthy.svg";
import { DropUpload } from "./DropUpload";

// File validation helper
const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB
const ACCEPTED_IMAGE_TYPES = ["image/jpeg", "image/jpg", "image/png", "image/webp"];
const ACCEPTED_PDF_TYPES = ["application/pdf"];
const ACCEPTED_DOCUMENT_TYPES = [...ACCEPTED_IMAGE_TYPES, ...ACCEPTED_PDF_TYPES];

const makeFormSchema = (lang) =>
    z.object({
        nationalIdPhoto: z
            .any()
            .refine((file) => file && file.length > 0, {
                message: t(lang, "national_id_photo_required"),
            })
            .refine(
                (file) => {
                    if (!file || file.length === 0) return true;
                    return file[0]?.size <= MAX_FILE_SIZE;
                },
                { message: t(lang, "file_too_large") }
            )
            .refine(
                (file) => {
                    if (!file || file.length === 0) return true;
                    return ACCEPTED_IMAGE_TYPES.includes(file[0]?.type);
                },
                { message: t(lang, "invalid_file_type") }
            ),

        personalPhoto: z
            .any()
            .refine((file) => file && file.length > 0, {
                message: t(lang, "personal_photo_required"),
            })
            .refine(
                (file) => {
                    if (!file || file.length === 0) return true;
                    return file[0]?.size <= MAX_FILE_SIZE;
                },
                { message: t(lang, "file_too_large") }
            )
            .refine(
                (file) => {
                    if (!file || file.length === 0) return true;
                    return ACCEPTED_IMAGE_TYPES.includes(file[0]?.type);
                },
                { message: t(lang, "invalid_file_type") }
            ),

        fitnessCertificate: z
            .any()
            .optional()
            .refine(
                (file) => {
                    if (!file || file.length === 0) return true;
                    return file[0]?.size <= MAX_FILE_SIZE;
                },
                { message: t(lang, "file_too_large") }
            )
            .refine(
                (file) => {
                    if (!file || file.length === 0) return true;
                    return ACCEPTED_DOCUMENT_TYPES.includes(file[0]?.type);
                },
                { message: t(lang, "invalid_file_type") }
            ),

        clubApproval: z
            .any()
            .refine((file) => file && file.length > 0, {
                message: t(lang, "club_approval_required"),
            })
            .refine(
                (file) => {
                    if (!file || file.length === 0) return true;
                    return file[0]?.size <= MAX_FILE_SIZE;
                },
                { message: t(lang, "file_too_large") }
            )
            .refine(
                (file) => {
                    if (!file || file.length === 0) return true;
                    return ACCEPTED_PDF_TYPES.includes(file[0]?.type);
                },
                { message: t(lang, "invalid_file_type") }
            ),
    });

export default function DocumentsForm({
    lang,
    formData,
    setFormData,
    setStep,
    progress,
    setProgress,
    setMaxProgress,
}) {
    const [loading, setLoading] = useState(false);
    const formSchema = useMemo(() => makeFormSchema(lang), [lang]);

    const form = useForm({
        resolver: zodResolver(formSchema),
        defaultValues: {
            // ✅ use null instead of "" because your values are FileList-like
            nationalIdPhoto: formData?.nationalIdPhoto ?? null,
            personalPhoto: formData?.personalPhoto ?? null,
            fitnessCertificate: formData?.fitnessCertificate ?? null,
            clubApproval: formData?.clubApproval ?? null,
        },
        mode: "onChange",
    });

    useEffect(() => {
        //scroll to top
        window.scrollTo({ top: 0, behavior: "smooth" });
        const subscription = form.watch((value) => {
            let filledInputs = 0;
            const totalInputs = 3;

            if (value.nationalIdPhoto && value.nationalIdPhoto.length > 0) filledInputs++;
            if (value.personalPhoto && value.personalPhoto.length > 0) filledInputs++;
            if (value.clubApproval && value.clubApproval.length > 0) filledInputs++;

            setProgress(filledInputs);
            setMaxProgress(totalInputs);
        });

        return () => subscription.unsubscribe();
    }, [form, setProgress, setMaxProgress]);

    const onSubmit = (data) => {
        setFormData({ ...formData, ...data });
        setProgress(0);
        setStep(3);
    };

    return (
        <div className="personal-data-form">
            <div className="container">
                <div className="personal-data-form-content">
                    <div className="form-header">
                        <h2 className="form-title">{t(lang, "required_documents")}</h2>
                        <p className="form-subtitle">{t(lang, "required_documents_desc")}</p>
                    </div>

                    <Form {...form}>
                        <form onSubmit={form.handleSubmit(onSubmit)} className="license-form">
                            <UploadSections lang={lang} form={form} />

                            <div className="form-actions">
                                {/* <Button type="button" onClick={() => setStep(1)} className="previous-license-btn">
                                    {t(lang, "previous")}
                                </Button> */}

                                <Button type="submit" className="submit-license-btn" disabled={loading}>
                                    {loading ? <span className="loader-btn" /> : <span>{t(lang, "next")}</span>}
                                </Button>
                            </div>
                        </form>
                    </Form>
                </div>
            </div>
        </div>
    );
}

// Upload Sections Component
function UploadSectionsBase({ lang, form }) {
    const [nationalIdPreview, setNationalIdPreview] = useState(null); // string or null
    const [personalPhotoPreview, setPersonalPhotoPreview] = useState(null);
    const [fitnessCertificatePreview, setFitnessCertificatePreview] = useState(null); // {type:"pdf", name:string} or dataUrl

    const [clubApprovalPreview, setClubApprovalPreview] = useState(null); // {type:"pdf", name:string} or null

    // ✅ read preview safely
    const setSinglePreviewFromFiles = useCallback((files, setPreview) => {
        const file = files?.[0];
        if (!file) return setPreview(null);

        if (file.type === "application/pdf") return setPreview({ type: "pdf", name: file.name });

        // for images -> use data URL and render with <img>
        const reader = new FileReader();
        reader.onloadend = () => setPreview(typeof reader.result === "string" ? reader.result : null);
        reader.readAsDataURL(file);
    }, []);

    const setMultiPreviewFromFiles = useCallback((files, setPreview) => {
        if (!files || files.length === 0) return setPreview([]);

        const filesArr = Array.from(files);
        const previews = [];
        let done = 0;

        filesArr.forEach((file, index) => {
            if (file.type === "application/pdf") {
                previews.push({ type: "pdf", name: file.name, index });
                done++;
                if (done === filesArr.length) setPreview([...previews].sort((a, b) => a.index - b.index));
            } else {
                const reader = new FileReader();
                reader.onloadend = () => {
                    previews.push({
                        type: "image",
                        src: typeof reader.result === "string" ? reader.result : "",
                        name: file.name,
                        index,
                    });
                    done++;
                    if (done === filesArr.length) setPreview([...previews].sort((a, b) => a.index - b.index));
                };
                reader.readAsDataURL(file);
            }
        });
    }, []);

    return (
        <>
            {/* National ID Photo */}
            <div className="section-header">
                <div className="section-icon">
                    <Image src={nationalCardIcon} alt="National ID Icon" />
                </div>
                <h3 className="section-title">{t(lang, "national_id_photo")}</h3>
            </div>

            <div className="form-grid-single">
                <FormField
                    control={form.control}
                    name="nationalIdPhoto"
                    render={({ field }) => (
                        <FormItem className="form-field">
                            <FormControl>
                                <DropUpload
                                    lang={lang}
                                    id="nationalIdPhoto"
                                    name={field.name}
                                    accept={{ "image/*": [] }}
                                    multiple={false}
                                    value={field.value}
                                    hasError={!!form.formState.errors.nationalIdPhoto}
                                    descKey="national_id_desc"
                                    onFiles={(files) => {
                                        field.onChange(files);
                                        setSinglePreviewFromFiles(files, setNationalIdPreview);
                                        form.trigger("nationalIdPhoto");
                                    }}
                                >
                                    {nationalIdPreview && (
                                        <div className="file-preview">
                                            {/* ✅ use <img> for data URL previews */}
                                            <img
                                                src={nationalIdPreview}
                                                alt="Preview"
                                                className="preview-image"
                                                style={{ width: "100%", height: "auto", display: "block" }}
                                            />
                                        </div>
                                    )}
                                </DropUpload>
                            </FormControl>
                            <FormMessage className="field-error" />
                        </FormItem>
                    )}
                />
            </div>

            {/* Personal Photo */}
            <div className="section-header">
                <div className="section-icon">
                    <Image src={nationalCardIcon} alt="Profile Icon" />
                </div>
                <h3 className="section-title">{t(lang, "personal_photo")}</h3>
            </div>

            <div className="form-grid-single">
                <FormField
                    control={form.control}
                    name="personalPhoto"
                    render={({ field }) => (
                        <FormItem className="form-field">
                            <FormControl>
                                <DropUpload
                                    lang={lang}
                                    id="personalPhoto"
                                    name={field.name}
                                    accept={{ "image/*": [] }}
                                    multiple={false}
                                    value={field.value}
                                    hasError={!!form.formState.errors.personalPhoto}
                                    descKey="personal_photo_desc"
                                    onFiles={(files) => {
                                        field.onChange(files);
                                        setSinglePreviewFromFiles(files, setPersonalPhotoPreview);
                                        form.trigger("personalPhoto");
                                    }}
                                >
                                    {personalPhotoPreview && (
                                        <div className="file-preview">
                                            <img
                                                src={personalPhotoPreview}
                                                alt="Preview"
                                                className="preview-image"
                                                style={{ width: "100%", height: "auto", display: "block" }}
                                            />
                                        </div>
                                    )}
                                </DropUpload>
                            </FormControl>
                            <FormMessage className="field-error" />
                        </FormItem>
                    )}
                />
            </div>

            {/* Fitness Certificate */}
            <div className="section-header">
                <div className="section-icon">
                    <Image src={healthy} alt="Document Icon" />
                </div>
                <h3 className="section-title">{t(lang, "fitness_certificate")}</h3>
            </div>

            <div className="form-grid-single">
                <FormField
                    control={form.control}
                    name="fitnessCertificate"
                    render={({ field }) => (
                        <FormItem className="form-field">
                            <FormControl>
                                <DropUpload
                                    lang={lang}
                                    id="fitnessCertificate"
                                    name={field.name}
                                    accept={{ "application/pdf": [] }}
                                    multiple={false}
                                    value={field.value}
                                    hasError={!!form.formState.errors.fitnessCertificate}
                                    descKey="fitness_certificate_desc"
                                    onFiles={(files) => {
                                        field.onChange(files);
                                        setSinglePreviewFromFiles(files, setFitnessCertificatePreview);
                                        form.trigger("fitnessCertificate");
                                    }}
                                >
                                    {fitnessCertificatePreview && (
                                        <div className="file-preview">
                                            {fitnessCertificatePreview?.type === "pdf" ? (
                                                <div className="pdf-indicator">
                                                    <Image src={pdf} alt="Document Icon" />
                                                    <p className="pdf-text">{fitnessCertificatePreview.name}</p>
                                                </div>
                                            ) : (
                                                <img
                                                    src={fitnessCertificatePreview}
                                                    alt="Preview"
                                                    className="preview-image"
                                                    style={{ width: "100%", height: "auto", display: "block" }}
                                                />
                                            )}
                                        </div>
                                    )}
                                </DropUpload>
                            </FormControl>
                            <FormMessage className="field-error" />
                        </FormItem>
                    )}
                />
            </div>

            {/* Club Approval */}
            <div className="section-header">
                <div className="section-icon">
                    <Image src={pdfIcon} alt="Document Icon" />
                </div>
                <h3 className="section-title">{t(lang, "club_approval")}</h3>
            </div>

            <div className="form-grid-single">
                <FormField
                    control={form.control}
                    name="clubApproval"
                    render={({ field }) => (
                        <FormItem className="form-field">
                            <FormControl>
                                <DropUpload
                                    lang={lang}
                                    id="clubApproval"
                                    name={field.name}
                                    accept={{ "application/pdf": [] }}
                                    multiple={false}
                                    value={field.value}
                                    hasError={!!form.formState.errors.clubApproval}
                                    descKey="club_approval_desc"
                                    onFiles={(files) => {
                                        field.onChange(files);
                                        setSinglePreviewFromFiles(files, setClubApprovalPreview);
                                        form.trigger("clubApproval");
                                    }}
                                >
                                    {clubApprovalPreview && (
                                        <div className="file-preview">
                                            {clubApprovalPreview?.type === "pdf" ? (
                                                <div className="pdf-indicator">
                                                    <Image src={pdf} alt="Document Icon" />
                                                    <p className="pdf-text">{clubApprovalPreview.name}</p>
                                                </div>
                                            ) : (
                                                <img
                                                    src={clubApprovalPreview}
                                                    alt="Preview"
                                                    className="preview-image"
                                                    style={{ width: "100%", height: "auto", display: "block" }}
                                                />
                                            )}
                                        </div>
                                    )}
                                </DropUpload>
                            </FormControl>
                            <FormMessage className="field-error" />
                        </FormItem>
                    )}
                />
            </div>
        </>
    );
}

export const UploadSections = React.memo(UploadSectionsBase);
