"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 ImageObject {
  id?: number;
  image: string | File;
}

interface TicketsImagesModelProps {
  form: any;
  name: string;
  label?: string;
  imageUrl?: string | File | ImageObject | (string | File | ImageObject)[];
  multiple?: boolean;
  includeId?: boolean; // agar true bo‘lsa — {id, image} jo‘natiladi
}

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

  useEffect(() => {
    if (!imageUrl) return;
    const items = Array.isArray(imageUrl) ? imageUrl : [imageUrl];

    if (multiple) {
      const values: any[] = [];
      const urls: string[] = [];

      items.forEach((item) => {
        if (typeof item === "string") {
          urls.push(item);
          values.push(includeId ? { image: item } : item);
        } else if (item instanceof File) {
          urls.push(URL.createObjectURL(item));
          values.push(includeId ? { image: item } : item);
        } else if (typeof item === "object" && "image" in item) {
          const img = item.image;
          urls.push(typeof img === "string" ? img : URL.createObjectURL(img));
          values.push(includeId ? { id: item.id, image: img } : img);
        }
      });

      setPreviews(urls);
      form.setValue(name, values);
    } else {
      const single = items[0];
      let url = "";
      let valueToSet: any = null;

      if (typeof single === "string") {
        url = single;
        valueToSet = single;
      } else if (single instanceof File) {
        url = URL.createObjectURL(single);
        valueToSet = single;
      } else if (typeof single === "object" && "image" in single) {
        const img = single.image;
        url = typeof img === "string" ? img : URL.createObjectURL(img);
        valueToSet =
          includeId && single.id ? { id: single.id, image: img } : img;
      }

      setPreviews(url ? [url] : []);
      form.setValue(name, valueToSet); // 🔥 array emas
    }
  }, [imageUrl, form, name, multiple, includeId]);

  const handleFileChange = (files: FileList | null) => {
    if (!files) return;
    const newFiles = Array.from(files);

    if (multiple) {
      const current = form.getValues(name) || [];
      const newValue = includeId
        ? [...current, ...newFiles.map((f) => ({ image: f }))]
        : [...current, ...newFiles];
      form.setValue(name, newValue);
      setPreviews([
        ...previews,
        ...newFiles.map((f) => URL.createObjectURL(f)),
      ]);
    } else {
      const singleFile = newFiles[0];
      const valueToSet = includeId ? { image: singleFile } : singleFile;
      form.setValue(name, valueToSet); // 🔥 array emas
      setPreviews(singleFile ? [URL.createObjectURL(singleFile)] : []);
    }
  };

  const handleDelete = (index: number) => {
    if (multiple) {
      const current = form.getValues(name) || [];
      const newValue = current.filter((_: any, i: number) => i !== index);
      form.setValue(name, newValue);
      setPreviews(previews.filter((_, i) => i !== index));
    } else {
      form.setValue(name, null);
      setPreviews([]);
    }
  };

  return (
    <FormField
      control={form.control}
      name={name}
      render={() => (
        <FormItem>
          <Label className="text-md">{label}</Label>
          <FormControl>
            <div className="flex flex-col gap-3">
              <Input
                id={inputId}
                type="file"
                accept="image/*"
                multiple={multiple}
                className="hidden"
                onChange={(e) => handleFileChange(e.target.files)}
              />

              <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>
                <p className="text-sm text-white">
                  {multiple
                    ? t("Bir nechta rasm yuklashingiz mumkin")
                    : t("Faqat bitta rasm yuklash mumkin")}
                </p>
              </label>

              {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"
                      />
                      <button
                        type="button"
                        onClick={() => handleDelete(i)}
                        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>
      )}
    />
  );
}
