"use client";

import React, { useEffect, useMemo, useState } from "react";
import { Button } from "@/shared/common/ui/button";
import { Input } from "@/shared/common/ui/input";
import { useToast } from "@/shared/common/ui/use-toast";
import { useDocumentRequirement } from "@/shared/hooks/useOrganizationReport";
import { useMyUploads } from "@/external-portal/hooks/useMyUpload";
import { useQueries } from "@tanstack/react-query";
import { getMyUploadById } from "@/external-portal/services/portalOutgoingService";
import { useDocumentUploads } from "@/external-portal/hooks/useDocumentUploads";
import { FilterEnum } from "@/shared/services/organizationsService";
import { useAuthUser } from "@/shared/hooks/useAuthUser";
import { Check, Trash } from "lucide-react";
import { UploadFileModal } from "./UploadFileModal";
import { useTranslation } from "react-i18next";
import { useUser } from "@/shared/context/UserContext";

export interface LocalizedText {
  am?: string;
  en?: string;
}

export interface DocumentReq {
  id: string;
  title: LocalizedText;
  description?: LocalizedText;
  key?: string;
  type?: string;
  order?: number;
  isActive?: boolean;
  isOptional?: boolean;
}

type FilesRecord = Record<string, File | string | null>;

interface UploadDocumentsStepProps {
  registrationType?: "individual" | "external_organization" | string;
  uploadedFiles: FilesRecord;
  setUploadedFiles: React.Dispatch<React.SetStateAction<FilesRecord>>;
}


export const UploadDocumentsStep: React.FC<UploadDocumentsStepProps> = ({
  registrationType,
  uploadedFiles,
  setUploadedFiles,
}) => {
  const userDetails = useUser();
  const {t} = useTranslation()
  // For other registration types, map to FilterEnum
  const mappedType =
    registrationType === "external_organization"
      ? "organization"
      : (registrationType as string) || userDetails?.userType;

  const filterData: FilterEnum | undefined =
    mappedType && Object.values(FilterEnum).includes(mappedType as FilterEnum)
      ? (mappedType as FilterEnum)
      : undefined;

  const { requirementDoc } = useDocumentRequirement(filterData);
  const { data: myUploads } = useMyUploads();

  const latestUploadIds = useMemo(() => {
    if (!requirementDoc?.items?.length) return [];
    return requirementDoc.items.map((doc: DocumentReq) => {
      const uploadsForDoc = myUploads?.filter(
        (u: any) => u.documentId === doc.id
      );
      if (uploadsForDoc?.length) {
        const latest = uploadsForDoc.reduce((prev: any, cur: any) =>
          new Date(prev.createdAt) > new Date(cur.createdAt) ? prev : cur
        );
        return {
          docId: doc.id,
          uploadId: latest.id,
          fileInfo: latest.fileInfo,
        };
      }
      return { docId: doc.id, uploadId: null, fileInfo: null };
    });
  }, [requirementDoc?.items, myUploads]);

  const presignedQueries = useQueries({
    queries:
      latestUploadIds?.map(({ uploadId }: any) => ({
        queryKey: ["myUpload", uploadId],
        queryFn: () =>
          uploadId ? getMyUploadById(uploadId) : Promise.resolve(null),
        enabled: !!uploadId,
      })) || [],
  });

  const prefills = useMemo(() => {
    const map: FilesRecord = {};
    if (!latestUploadIds?.length) return map;
    latestUploadIds.forEach(({ docId, fileInfo }, idx) => {
      const q = presignedQueries[idx];
      const presigned = q?.data?.presigned;
      map[docId] = presigned || fileInfo?.fileName || null;
    });
    return map;
  }, [latestUploadIds, presignedQueries]);

  useEffect(() => {
    if (
      Object.keys(uploadedFiles).length === 0 &&
      Object.keys(prefills).length > 0
    ) {
      setUploadedFiles((prev) => ({ ...prefills, ...prev }));
    }
  }, [prefills, uploadedFiles, setUploadedFiles]);

  const [modalOpen, setModalOpen] = React.useState(false);
  const [selectedDoc, setSelectedDoc] = React.useState<DocumentReq | null>(null);

  // When user clicks "Upload" button
  const handleOpenModal = (doc: DocumentReq) => {
    setSelectedDoc(doc);
    setModalOpen(true);
  };

  // When file is selected in modal
  const handleFileSelect = (file: File | null) => {
    if (selectedDoc) {
      setUploadedFiles((prev) => ({
        ...prev,
        [selectedDoc.id]: file,
      }));
    }
    setModalOpen(false);
    setSelectedDoc(null);
  };


  const handleRemove = (docId: string) => {
    setUploadedFiles((prev: FilesRecord) => ({
      ...prev,
      [docId]: null,
    }));
  };


  const [faydaValue, setFaydaValue] = useState<string>("");

  // If registration type is individual, show Fayda input
  if (registrationType === "individual") {
    return (
      <div className="space-y-3">
        <label className="block">
          <span className="font-medium">
            {t("registration.documents.fayda")}
          </span>
          <Input
            type="text"
            value={faydaValue}
            onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
              setFaydaValue(e.target.value)
            }
            placeholder={t("registration.documents.faydaMessage")}
            className="mt-1 block w-full rounded-md border px-3 py-2"
          />
        </label>
      </div>
    );
  }

  return (
    <div className="space-y-3">
      {requirementDoc?.items?.length === 0 ? (
        <div className="text-sm text-gray-500">
          {t("registration.documents.noRequirements")}
        </div>
      ) : (
        requirementDoc.items.map((doc) => {
          const current = uploadedFiles[doc.id];
          const isNewFile = current instanceof File;
          return (
            <div
              key={doc.id}
              className="flex items-center gap-2 p-3 border rounded-lg">
              <div className="flex-1">
                <div className="font-medium">{doc.title?.en || doc.id}</div>
                {doc.description?.en && (
                  <div className="text-sm text-muted-foreground">
                    {doc.description.en}
                  </div>
                )}
                {current && (
                  <div className="text-xs mt-1 flex items-center gap-1">
                    <Check className="h-3 w-3" />
                    <span
                      className={
                        isNewFile ? "text-blue-600" : "text-primary-600"
                      }>
                      {isNewFile
                        ? `Ready to upload: ${current.name}`
                        : `Previously uploaded: ${current}`}
                    </span>
                    {isNewFile && (
                      <span className="text-orange-500 ml-2">
                        ({t("registration.documents.willUploadOnSubmit")})
                      </span>
                    )}
                  </div>
                )}
                {!doc.isOptional && !current && (
                  <div className="text-xs text-red-600 mt-1">
                    {t("registration.documents.required")}
                  </div>
                )}
              </div>
              <div className="flex items-center gap-2">
                {current && (
                  <Button
                    variant="ghost"
                    size="icon"
                    onClick={() => handleRemove(doc.id)}
                    className="h-8 w-8 text-destructive">
                    <Trash className="h-4 w-4" />
                  </Button>
                )}
                <Button
                  size="sm"
                  variant={current ? "outline" : "default"}
                  className={current ? "" : "bg-primary-600"}
                  onClick={() => handleOpenModal(doc)}>
                  {current ? "Change" : "Upload"}
                </Button>
              </div>
            </div>
          );
        })
      )}

      {modalOpen && selectedDoc && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <UploadFileModal
            value={uploadedFiles[selectedDoc.id] || null}
            multiple={false}
            accept={[
              ".png",
              ".jpg",
              ".jpeg",
              ".pdf",
              ".dwg",
              ".dxf",
              ".dwt",
              ".bak",
              ".sv$",
              ".dws",
              ".mxd",
              ".aprx",
              ".rar",
              ".zip",
            ]}
            onChange={(file) => {
              handleFileSelect(
                file instanceof File
                  ? file
                  : Array.isArray(file)
                  ? file[0]
                  : null
              );
            }}
            onClose={() => {
              setModalOpen(false);
              setSelectedDoc(null);
            }}
            fileUploadFields={{
              requiredDocumentId: selectedDoc.id,
            }}
          />
        </div>
      )}
    </div>
  );
};
export default UploadDocumentsStep;
