"use client";

import { useAtom } from "jotai";
import { Section } from "../section";
import { formAtom } from "@/components/state/autionAtoms";
import DynamicInput from "@/components/input";
import { useTranslations } from "next-intl";
import Image from "next/image";
import { uploadImage, removeImage } from "@/actions/upload-image";
import { AuctionForm } from "@/components/state/autionAtoms";
import { toast } from "react-toastify";
import { useSession } from "@/auth/session-provider";
import { BaseModal } from "@/components/modal";
import PdfViewer from "@/components/viewers/PdfViewer";
import { useState } from "react";

export function Step5() {
  const t = useTranslations("ADD_LISTING.STEP5");
  const [form, setForm] = useAtom(formAtom);
  const session = useSession();

  const [pdfModalOpen, setPdfModalOpen] = useState(false);
  const [selectedPdf, setSelectedPdf] = useState<{
    url: string;
    title: string;
  } | null>(null);

  const getFileKind = (f: any): "video" | "pdf" | "image" | "other" => {
    const url = String(f?.url || "").toLowerCase();
    const type = String(f?.type || "").toLowerCase();
    const name = String(f?.name || "").toLowerCase();

    if (String(f?.collection_name || "") === "video") return "video";
    if (type.includes("pdf") || url.endsWith(".pdf") || name.endsWith(".pdf"))
      return "pdf";
    if (
      type.startsWith("image/") ||
      url.match(/\.(jpg|jpeg|png|gif|webp)$/i) ||
      name.match(/\.(jpg|jpeg|png|gif|webp)$/i)
    )
      return "image";
    return "other";
  };

  const openPdf = (url: string, title: string) => {
    setSelectedPdf({ url, title });
    setPdfModalOpen(true);
  };

  const inferCollectionKey = (fieldName: string) => {
    const m = String(fieldName || "").match(/\[(.*?)\]/);
    return m?.[1] || fieldName;
  };

  const handleFileChange = async (
    name: keyof AuctionForm,
    fieldName: string,
    files: FileList | null,
  ) => {
    if (!files?.length) return;

    const modelName = form?.offer === "auction" ? "Auction" : "Offer";

    const localId = `local_${Date.now()}_${Math.random().toString(16).slice(2)}`;
    const file0 = files[0];
    const localUrl = URL.createObjectURL(file0);
    const collectionKey = inferCollectionKey(fieldName);

    setForm((prev) => ({
      ...prev,
      files: [
        ...(prev.files || []),
        {
          localId,
          uploading: true,
          name: file0.name,
          type: file0.type,
          collection_name: collectionKey,
          url: localUrl,
        },
      ],
    }));

    const toastId = toast.loading(t("toast.uploading"), {
      autoClose: false,
      closeOnClick: false,
    });

    try {
      const results = await Promise.all(
        Array.from(files).map(async (file) => {
          const formData = new FormData();
          formData.append("model_name", modelName);
          formData.append(fieldName, file);

          const res = await uploadImage(formData);
          if (res?.success && Array.isArray(res.data)) {
            const fileData = res.data[0];
            toast.update(toastId, {
              render: `✅ ${t("toast.uploaded")} ${fileData.collection_name}`,
              type: "success",
              isLoading: false,
              autoClose: 3000,
              closeOnClick: true,
            });
            return fileData;
          }
          toast.update(toastId, {
            render: t("toast.upload_failed"),
            type: "error",
            isLoading: false,
            autoClose: 4000,
            closeOnClick: true,
          });
          return null;
        }),
      );

      const newFiles = results.filter(Boolean);

      if (newFiles.length > 0) {
        const f = newFiles[0] as any;
        setForm((prev) => ({
          ...prev,
          files: (prev.files || []).map((x: any) =>
            x?.localId === localId
              ? {
                  id: f.id,
                  collection_name: f.collection_name,
                  url: f.url,
                  uploading: false,
                  name: file0.name,
                  type: file0.type,
                }
              : x,
          ),
        }));
      } else {
        setForm((prev) => ({
          ...prev,
          files: (prev.files || []).filter((x: any) => x?.localId !== localId),
        }));
      }
    } catch (err) {
      console.error("❌ File upload failed:", err);
      setForm((prev) => ({
        ...prev,
        files: (prev.files || []).filter((x: any) => x?.localId !== localId),
      }));
      toast.update(toastId, {
        render: t("toast.upload_failed"),
        type: "error",
        isLoading: false,
        autoClose: 4000,
        closeOnClick: true,
      });
    }
  };

  const handleRemoveFile = async (f: any) => {
    const mediaId = (f as any)?.id as number | undefined;
    if (!mediaId) {
      setForm((prev) => ({
        ...prev,
        files: (prev.files || []).filter((x: any) => {
          if ((f as any)?.localId && (x as any)?.localId)
            return (x as any).localId !== (f as any).localId;
          return !(
            String((x as any)?.url || "") === String((f as any)?.url || "") &&
            String((x as any)?.collection_name || "") ===
              String((f as any)?.collection_name || "")
          );
        }),
      }));
      return;
    }

    try {
      const token = session?.access_token;
      if (!token) {
        toast.error(t("toast.auth_required"));
        return;
      }
      const res = await removeImage({ mediaIds: [mediaId], token });

      if ((res as any)?.success) {
        toast.success(t("toast.removed"));
        setForm((prev) => ({
          ...prev,
          files: (prev.files || []).filter(
            (x: any) => String((x as any)?.id) !== String(mediaId),
          ),
        }));
      } else {
        console.error("❌ خطأ من السيرفر:", res);
        toast.error(t("toast.remove_failed"));
      }
    } catch (err) {
      console.error("❌ File remove failed:", err);
      toast.error(t("toast.remove_failed"));
    }
  };

  const docKeys = [
    {
      key: "medicalCert",
      label: t("medical_cert"),
      fieldName: "media[medical_exam_certificate]",
      collection: "medical_exam_certificate",
    },
    {
      key: "animalInfoCert",
      label: t("animal_info_cert"),
      fieldName: "media[info_certificate]",
      collection: "info_certificate",
    },
    {
      key: "ownerDoc",
      label: t("owner_document"),
      fieldName: "media[owner_document]",
      collection: "owner_document",
    },
  ];

  // Filter files to show only documents (not media like images/video)
  const documentCollections = docKeys.map((d) => d.collection);
  const documentFiles = (form.files || []).filter((f: any) =>
    documentCollections.includes(f.collection_name),
  );

  return (
    <Section title={t("title")}>
      <div className="grid sm:grid-cols-2 gap-4 text-start">
        {docKeys.map(({ key, label, fieldName }) => (
          <div key={key}>
            <DynamicInput
              field={{
                name: key,
                value: (form as Record<string, any>)[key] || [],
                onChange: (files) =>
                  handleFileChange(key as any, fieldName, files),
              }}
              label={label}
              type="file"
            />
          </div>
        ))}
      </div>
      <div className="mt-6">
        <h3 className="text-lg text-start font-semibold mb-2">
          {t("uploaded_images")}
        </h3>

        {documentFiles.length ? (
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
            {documentFiles.map((f: any, i) => (
              <div
                key={`${f.id || f.localId || i}-${i}`}
                className="relative w-full aspect-square border rounded-lg overflow-hidden group"
              >
                {getFileKind(f) === "video" ? (
                  <div className="w-full h-full relative">
                    <video
                      src={f.url}
                      className="w-full h-full object-cover"
                      controls={!f.uploading}
                    />
                    {f.uploading && (
                      <div className="absolute inset-0 bg-black/40 text-white text-xs flex items-center justify-center">
                        جاري الرفع...
                      </div>
                    )}
                  </div>
                ) : getFileKind(f) === "pdf" ? (
                  <button
                    type="button"
                    onClick={() =>
                      openPdf(
                        String(f.url),
                        String(f.name || f.collection_name || "PDF"),
                      )
                    }
                    className="w-full h-full bg-slate-50 flex flex-col items-center justify-center gap-2 p-3"
                  >
                    <div className="w-12 h-12 rounded-xl bg-red-50 text-red-600 flex items-center justify-center font-extrabold">
                      PDF
                    </div>
                    <div className="text-xs text-slate-700 line-clamp-2">
                      {String(f.name || "ملف PDF")}
                    </div>
                    <div className="text-[11px] text-slate-500">اضغط للعرض</div>
                  </button>
                ) : getFileKind(f) === "image" ? (
                  <Image
                    src={f.url}
                    alt={f.collection_name}
                    fill
                    className="object-cover"
                    unoptimized
                  />
                ) : (
                  <div className="w-full h-full bg-slate-50 flex flex-col items-center justify-center gap-2 p-3">
                    <div className="w-12 h-12 rounded-xl bg-slate-200 text-slate-700 flex items-center justify-center font-extrabold">
                      FILE
                    </div>
                    <div className="text-xs text-slate-700 line-clamp-2">
                      {String(f.name || f.collection_name || "ملف")}
                    </div>
                  </div>
                )}
                <button
                  type="button"
                  onClick={() => void handleRemoveFile(f)}
                  className="absolute top-1 right-1 bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center text-sm opacity-80 group-hover:opacity-100"
                >
                  ×
                </button>

                <p className="absolute bottom-0 left-0 bg-black/40 text-white text-xs w-full text-center py-0.5">
                  {f.uploading
                    ? "قيد الرفع"
                    : `#${f.id ?? "—"} — ${f.collection_name}`}
                </p>
              </div>
            ))}
          </div>
        ) : (
          <p className="text-sm text-slate-500">{t("no_uploaded_images")}</p>
        )}
      </div>

      <BaseModal
        isOpen={pdfModalOpen}
        onOpenChange={setPdfModalOpen}
        placement="center"
        contentClassName="w-full max-w-4xl max-h-[85vh] overflow-y-auto rounded-2xl p-3"
        title={selectedPdf?.title || "PDF"}
      >
        {selectedPdf ? (
          <PdfViewer fileUrl={selectedPdf.url} fileName={selectedPdf.title} />
        ) : null}
      </BaseModal>
    </Section>
  );
}
