import { useState } from "react";
import Header from "@/layout/components/Header";
import { Button } from "@/shared/common/ui/button";
import { useToast } from "@/shared/common/ui/use-toast";
import { useLocalizedName } from "@/shared/common/localizedName";

import { useDocumentRequirement } from "@/shared/hooks/useOrganizationReport";
import { useMyUploads } from "@/external-portal/hooks/useMyUpload";
import { useQueries } from "@tanstack/react-query";
import {
  getMyUploadById,
  LatestUploadInfo,
  submitApplication,
} from "@/external-portal/services/portalOutgoingService";
import { useAuthUser } from "@/shared/hooks/useAuthUser";
import { FilterEnum } from "@/shared/services/organizationsService";

import { UploadFileModal } from "./UploadFileModal";
import { useUser } from "@/shared/context/UserContext";

interface LocalizedText {
  am: string;
  en: string;
}
type Upload = {
  uploadId: string;
  // add other fields if needed
};

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

const UploadSteps = () => {
  const { toast } = useToast();
  const localized = useLocalizedName();

  const userDetails = useUser();
  const filterDataStr = userDetails?.userType;
  const mappedType =
    filterDataStr === "external_organization" ? "organization" : filterDataStr;

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

  // Fetch required docs
  const { requirementDoc } = useDocumentRequirement(filterData);
  const { data: myUploads } = useMyUploads();

  // Step 1: Collect latest upload IDs for each document
  const latestUploadIds = (requirementDoc.items ?? []).map((doc) => {
    const uploadsForDoc = (myUploads ?? []).filter(
      (u) => u.documentId === doc.id
    );

    if (uploadsForDoc.length) {
      const latestUpload = uploadsForDoc.reduce((prev, current) =>
        new Date(prev.createdAt) > new Date(current.createdAt) ? prev : current
      );

      return {
        docId: doc.id,
        uploadId: latestUpload.id,
        fileInfo: latestUpload.fileInfo,
      };
    }

    return { docId: doc.id, uploadId: null, fileInfo: null };
  });
  // Step 2: Query presigned URLs for latest uploads
  const queriesToRun = (latestUploadIds as LatestUploadInfo[]).filter(
    ({ uploadId }) => !!uploadId
  );
  const uploadQueries = useQueries({
    queries: queriesToRun.map(({ uploadId }) => ({
      queryKey: ["myUpload", uploadId],
      queryFn: () => getMyUploadById(uploadId!),
    })),
  });

  // Step 3: Build files record
  const filesRecord: Record<string, File | string | null> =
    latestUploadIds.reduce((acc, { docId, fileInfo }, idx) => {
      const queryIndex = queriesToRun.findIndex(
        (q) => q.uploadId === latestUploadIds[idx].uploadId
      );
      const uploadData =
        queryIndex >= 0 ? uploadQueries[queryIndex]?.data : undefined;
      acc[docId] = uploadData?.presigned || fileInfo?.fileName || null;
      return acc;
    }, {} as Record<string, File | string | null>);

  // State for modal and files
  const [uploadedFiles, setUploadedFiles] = useState(filesRecord);
  const [selectedDoc, setSelectedDoc] = useState<Document | null>(null);
  const [modalOpen, setModalOpen] = useState(false);

  const handleOpenModal = (doc: Document) => {
    setSelectedDoc(doc);
    setModalOpen(true);
  };

  const handleUploadComplete = (file: File | string | null) => {
    if (selectedDoc) {
      const newFiles = {
        ...uploadedFiles,
        [selectedDoc.id]: file,
      };
      setUploadedFiles(newFiles);
      setSelectedDoc(null);
      setModalOpen(false);

      if (file) {
        toast({
          title: "Success",
          description:
            "File uploaded successfully. You will be notified of your status via SMS shortly.",
          variant: "default",
        });
      }
    }
  };

  const handleSubmit = async () => {
    try {
      const response = await submitApplication();
      if (!response) {
        toast({
          title: "Error",
          description: "User ID is missing. Cannot submit application.",
          variant: "destructive",
        });
        return;
      }

      toast({
        title: "Success",
        description:
          "You have submitted your application and will be notified of the status. Thank you!",
        variant: "default",
      });
    } catch (error) {
      console.error(error);
      toast({
        title: "Error",
        description: "Failed to submit application.",
        variant: "destructive",
      });
    }
  };

  return (
    <div className="flex flex-col gap-4 w-full">
      <Header />

      <div className="p-4 bg-white shadow rounded-lg w-full">
        <h2 className="text-lg font-semibold text-center">Upload Documents</h2>
        <p className="text-sm text-gray-600 text-center">
          Please upload the required documents for verification.
        </p>

        <div className="w-full max-w-5xl mx-auto mt-4 space-y-4">
          {requirementDoc?.items.length === 0 && (
            <div>No Document Requirements available.</div>
          )}

          {requirementDoc?.items.map((doc: Document) => (
            <div
              key={doc.id}
              className="flex items-center justify-between p-4 border rounded-md">
              <div className="flex flex-col">
                <span className="font-medium">{localized(doc.title)}</span>
                {doc.description && (
                  <span className="text-sm text-muted-foreground">
                    {localized(doc.description)}
                  </span>
                )}
              </div>

              <div className="flex gap-2">
                {uploadedFiles[doc.id] && (
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => {
                      const file = uploadedFiles[doc.id];
                      if (!file) return;

                      if (typeof file === "string") {
                        window.open(file, "_blank");
                      } else if (file instanceof File) {
                        const url = URL.createObjectURL(file);
                        window.open(url, "_blank");
                      }
                    }}>
                    View
                  </Button>
                )}

                <Button
                  size="sm"
                  className="bg-primary-600"
                  onClick={() => handleOpenModal(doc)}>
                  {uploadedFiles[doc.id] ? "Replace" : "Upload"}
                </Button>
              </div>
            </div>
          ))}

          <div className="pt-4">
            <Button
              size="sm"
              className="bg-primary-600 w-full"
              disabled={
                Object.values(uploadedFiles).filter((file) => file !== null)
                  .length === 0
              }
              onClick={handleSubmit}>
              Submit
            </Button>
          </div>
        </div>
      </div>

      {/* Modal Overlay */}
      {modalOpen && selectedDoc && (
        <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) => {
            if (file === null) handleUploadComplete(null);
            else if (file instanceof File) handleUploadComplete(file);
            else if (Array.isArray(file) && file[0])
              handleUploadComplete(file[0]);
          }}
          fileUploadFields={{
            requiredDocumentId: selectedDoc.id,
          }}
        />
      )}
    </div>
  );
};

export default UploadSteps;
