import { useEffect, useState } from "react";
import { useForm, useFieldArray } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import { Input } from "@/components/ui/Input";
import { FileUploader } from "@/components/ui/FileUploader";
import { Button } from "@/components/ui/Button";
import { useLandingHero, useUpdateLandingHero } from "./core/_hooks";
import { LandingHeroData, HeroImage } from "./core/_models";
import { PlusCircle, Trash2, Save } from "lucide-react";
import { useFileUpload, useFileDelete } from "@/hooks/useFileUpload";
import { Modal } from "@/components/ui/Modal";
import { PageContainer } from "@/components/ui/Typography";

const heroImageSchema = yup.object({
    alt_text: yup.string().required("متن ALT الزامی است"),
    url: yup.string()
        .transform((v) => (v === "" ? null : v))
        .required("آدرس تصویر الزامی است")
        .url("آدرس معتبر نیست"),
    thumbnail: yup.string().url().nullable().notRequired(),
});

const landingHeroSchema = yup.object({
    main: heroImageSchema,
    side: yup.array().of(heroImageSchema).min(0),
});

export const HeroSliderPage = () => {
    const { data, isLoading } = useLandingHero();
    const { mutate: updateHero, isPending: isSaving } = useUpdateLandingHero();
    const [preview, setPreview] = useState<{ url: string; alt: string } | null>(null);

    const {
        control,
        handleSubmit,
        formState: { errors, isDirty, isValid },
        reset,
        setValue,
        watch,
    } = useForm<LandingHeroData>({
        resolver: yupResolver(landingHeroSchema) as any,
        mode: "onChange",
        defaultValues: {
            main: { alt_text: "", url: "", thumbnail: "" },
            side: [],
        },
    });

    const { fields, append, remove } = useFieldArray({
        control,
        name: "side",
    });

    // File upload hooks
    const { mutateAsync: uploadFile } = useFileUpload();
    const { mutate: deleteFile } = useFileDelete();

    // Handlers for main slide image
    const handleMainFileUpload = async (file: File) => {
        const result = await uploadFile(file);
        setValue("main.url", result.url, { shouldValidate: true, shouldDirty: true });
        return result;
    };

    const handleMainFileRemove = (fileId: string) => {
        deleteFile(fileId);
        setValue("main.url", "", { shouldValidate: true, shouldDirty: true });
    };

    // Handlers for side slide images (returns functions bound to index)
    const handleSideFileUpload = (index: number) => async (file: File) => {
        const result = await uploadFile(file);
        setValue(`side.${index}.url`, result.url, { shouldValidate: true, shouldDirty: true });
        return result;
    };

    const handleSideFileRemove = (index: number) => (fileId: string) => {
        deleteFile(fileId);
        setValue(`side.${index}.url`, "", { shouldValidate: true, shouldDirty: true });
    };

    useEffect(() => {
        if (data) {
            reset(data);
        }
    }, [data, reset]);

    const onSubmit = (formData: LandingHeroData) => {
        updateHero(formData);
    };

    if (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 max-w-4xl mx-auto">
            <h1 className="text-2xl font-bold mb-6 text-gray-900 dark:text-gray-100">مدیریت اسلایدر صفحه اصلی</h1>

            <form onSubmit={handleSubmit(onSubmit)} className="space-y-8">
                {/* Main slide */}
                <div className="card p-6 space-y-6">
                    <h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">اسلاید اصلی</h2>
                    <Input
                        label="ALT Text"
                        {...control.register("main.alt_text" as const)}
                        error={(errors as any).main?.alt_text?.message}
                    />

                    {watch("main.url") && (
                        <div className="flex items-center gap-3">
                            <img
                                src={watch("main.url") as string}
                                alt={watch("main.alt_text") as string}
                                className="w-40 h-24 object-cover rounded border cursor-zoom-in"
                                onClick={() => setPreview({ url: watch("main.url") as string, alt: (watch("main.alt_text") as string) || "" })}
                            />
                            <Button
                                type="button"
                                variant="secondary"
                                onClick={() => setValue("main.url", "", { shouldDirty: true, shouldValidate: true })}
                            >
                                حذف تصویر فعلی
                            </Button>
                        </div>
                    )}

                    {!watch("main.url") && (
                        <FileUploader
                            onUpload={handleMainFileUpload}
                            onRemove={handleMainFileRemove}
                            acceptedTypes={["image/*"]}
                            maxFileSize={5 * 1024 * 1024}
                            maxFiles={1}
                            mode="single"
                            label="تصویر اسلاید"
                            description="تصویر را انتخاب کنید (حداکثر 5MB)"
                            error={(errors as any).main?.url?.message}
                        />
                    )}
                </div>

                {/* Side slides */}
                <div className="card p-6 space-y-6">
                    <div className="flex items-center justify-between">
                        <h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">اسلایدهای جانبی</h2>
                        <Button
                            type="button"
                            variant="secondary"
                            onClick={() =>
                                append({ alt_text: "", url: "", thumbnail: "" } as HeroImage)
                            }
                        >
                            <PlusCircle className="h-4 w-4 ml-2" /> افزودن اسلاید
                        </Button>
                    </div>

                    {fields.map((field, index) => (
                        <div key={field.id} className="border p-4 rounded-lg space-y-4 relative">
                            <button
                                type="button"
                                className="absolute top-2 left-2 text-red-600"
                                onClick={() => remove(index)}
                            >
                                <Trash2 className="h-4 w-4" />
                            </button>
                            <Input
                                label="ALT Text"
                                {...control.register(`side.${index}.alt_text` as const)}
                                error={
                                    (errors as any).side?.[index]?.alt_text?.message as string | undefined
                                }
                            />

                            {watch(`side.${index}.url` as const) && (
                                <div className="flex items-center gap-3">
                                    <img
                                        src={watch(`side.${index}.url` as const) as string}
                                        alt={(watch(`side.${index}.alt_text` as const) as string) || "preview"}
                                        className="w-32 h-20 object-cover rounded border cursor-zoom-in"
                                        onClick={() => setPreview({ url: watch(`side.${index}.url` as const) as string, alt: (watch(`side.${index}.alt_text` as const) as string) || "" })}
                                    />
                                    <Button
                                        type="button"
                                        variant="secondary"
                                        onClick={() => setValue(`side.${index}.url` as const, "", { shouldDirty: true, shouldValidate: true })}
                                    >
                                        حذف تصویر فعلی
                                    </Button>
                                </div>
                            )}

                            {!watch(`side.${index}.url` as const) && (
                                <FileUploader
                                    onUpload={handleSideFileUpload(index)}
                                    onRemove={handleSideFileRemove(index)}
                                    acceptedTypes={["image/*"]}
                                    maxFileSize={5 * 1024 * 1024}
                                    maxFiles={1}
                                    mode="single"
                                    label="تصویر اسلاید"
                                    description="تصویر را انتخاب کنید (حداکثر 5MB)"
                                    error={(errors as any).side?.[index]?.url?.message as string | undefined}
                                />
                            )}
                        </div>
                    ))}
                </div>

                <div className="flex items-center justify-end space-x-4 space-x-reverse">
                    <Button
                        type="submit"
                        loading={isSaving}
                        disabled={!isDirty || !isValid}
                    >
                        <Save className="h-4 w-4 ml-2" /> ذخیره تغییرات
                    </Button>
                </div>
            </form>
            <Modal isOpen={!!preview} onClose={() => setPreview(null)} title={preview?.alt || "مشاهده تصویر"}>
                {preview && (
                    <img src={preview.url} alt={preview.alt} className="max-h-[70vh] w-auto mx-auto rounded" />
                )}
            </Modal>
        </div>
    );
};

export default HeroSliderPage;
