"use client";

import {
  FormControl,
  FormField,
  FormItem,
  FormMessage,
} from "@/shared/ui/form";
import { Input } from "@/shared/ui/input";
import { Label } from "@/shared/ui/label";
import { ImagePlus, XIcon } from "lucide-react";
import { useEffect, useId, useState } from "react";
import { useTranslation } from "react-i18next";

interface TicketsImagesModelProps {
  form: any; // React Hook Form control
  name: string;
  label?: string;
  imageUrl?: string | string[] | undefined;
  multiple?: boolean;
}

export default function TicketsImagesModel({
  form,
  name,
  label = "Rasmlar",
  multiple = true,
  imageUrl,
}: TicketsImagesModelProps) {
  const { t } = useTranslation();
  const [previews, setPreviews] = useState<string[]>([]);
  const inputId = useId();

  useEffect(() => {
    if (imageUrl) {
      if (Array.isArray(imageUrl)) {
        setPreviews(imageUrl);
      } else {
        setPreviews([imageUrl]);
      }
    }
  }, [imageUrl]);

  return (
    <FormField
      control={form.control}
      name={name}
      render={() => (
        <FormItem>
          <Label className="text-md">{label}</Label>

          <FormControl>
            <div className="flex flex-col gap-3">
              {/* File Input */}
              <Input
                id={inputId}
                type="file"
                accept="image/*"
                multiple={multiple}
                className="hidden"
                onChange={(e) => {
                  const newFiles = e.target.files
                    ? Array.from(e.target.files)
                    : [];

                  if (multiple) {
                    // ✅ Bir nechta rasm
                    const allFiles = [
                      ...(form.getValues(name) || []),
                      ...newFiles,
                    ];
                    form.setValue(name, allFiles);
                    const urls = allFiles.map((file: File) =>
                      URL.createObjectURL(file),
                    );
                    setPreviews(urls);
                  } else {
                    // ✅ Faqat bitta rasm (banner)
                    const singleFile = newFiles[0] || null;
                    form.setValue(name, singleFile);
                    setPreviews(
                      singleFile ? [URL.createObjectURL(singleFile)] : [],
                    );
                  }
                }}
              />

              {/* Upload Zone */}
              <label
                htmlFor={inputId}
                className="border-2 border-dashed border-gray-300 h-40 rounded-2xl flex flex-col justify-center items-center cursor-pointer hover:bg-muted/20 transition"
              >
                <ImagePlus className="size-8 text-muted-foreground mb-2" />
                <p className="font-semibold text-white">
                  {t("Rasmlarni tanlang")}
                </p>
                {multiple ? (
                  <p className="text-sm text-white">
                    {t("Bir nechta rasm yuklashingiz mumkin")}
                  </p>
                ) : (
                  <p className="text-sm text-white">
                    {t("Faqat bitta rasm yuklash mumkin")}
                  </p>
                )}
              </label>

              {/* Preview Images */}
              {previews.length > 0 && (
                <div className="flex flex-wrap gap-3">
                  {previews.map((src, i) => (
                    <div
                      key={i}
                      className="relative size-24 rounded-md overflow-hidden border"
                    >
                      <img
                        src={src}
                        alt={`preview-${i}`}
                        className="object-cover w-full h-full"
                      />

                      {/* Delete Button */}
                      <button
                        type="button"
                        onClick={() => {
                          if (multiple) {
                            // ✅ Ko‘p rasm holati
                            const currentFiles = form.getValues(name) || [];
                            const newFiles = currentFiles.filter(
                              (_: File, idx: number) => idx !== i,
                            );
                            form.setValue(name, newFiles);
                            const newPreviews = previews.filter(
                              (_: string, idx: number) => idx !== i,
                            );
                            setPreviews(newPreviews);
                          } else {
                            // ✅ Bitta rasm holati
                            form.setValue(name, null);
                            setPreviews([]);
                          }
                        }}
                        className="absolute top-1 right-1 bg-white/80 rounded-full p-1 shadow hover:bg-white transition"
                      >
                        <XIcon className="size-4 text-destructive" />
                      </button>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </FormControl>

          <FormMessage />
        </FormItem>
      )}
    />
  );
}
