"use client";

import React, {
  FC,
  Dispatch,
  SetStateAction,
  useState,
  useEffect,
} from "react";
import { useParams } from "next/navigation";
import { useTranslation } from "@/i18n/client";
import { useToast } from "@/hooks/use-toast";
import { toast as toastMessage } from "sonner";
import { Download, Trash2 } from "lucide-react";
import { saveAs } from "file-saver";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Label } from "@/components/ui/label";
import {
  FileList,
  FileListAction,
  FileListHeader,
  FileListIcon,
  FileListInfo,
  FileListItem,
  FileListName,
} from "@/components/ui/file-list";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { getReportTempList, deleteReportTempFile } from "@/lib/forms/services";
import { VendorDataReportTemps } from "@/db/schema/vendorData";

interface FormDataReportTempUploadedListTabProps {
  packageId: number;
  formId: number;
}

export const FormDataReportTempUploadedListTab: FC<
  FormDataReportTempUploadedListTabProps
> = ({ packageId, formId }) => {
  const params = useParams();
  const lng = (params?.lng as string) || "ko";
  const { t } = useTranslation(lng, "engineering");

  const [prevReportTemp, setPrevReportTemp] = useState<VendorDataReportTemps[]>(
    []
  );
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const getTempFiles = async () => {
      await updateReportTempList(packageId, formId, setPrevReportTemp);
      setIsLoading(false);
    };

    getTempFiles();
  }, [packageId, formId]);

  return (
    <div>
      <Label>{t("templateUploadedList.listLabel")}</Label>
      <UploadedTempFiles
        prevReportTemp={prevReportTemp}
        updateReportTempList={() =>
          updateReportTempList(packageId, formId, setPrevReportTemp)
        }
        isLoading={isLoading}
        t={t}
      />
    </div>
  );
};

type UpdateReportTempList = (
  packageId: number,
  formId: number,
  setPrevReportTemp: Dispatch<SetStateAction<VendorDataReportTemps[]>>
) => Promise<void>;

const updateReportTempList: UpdateReportTempList = async (
  packageId,
  formId,
  setPrevReportTemp
) => {
  const tempList = await getReportTempList(packageId, formId);
  setPrevReportTemp(tempList);
};

interface UploadedTempFiles {
  prevReportTemp: VendorDataReportTemps[];
  updateReportTempList: () => void;
  isLoading: boolean;
  t: (key: string, options?: any) => string;
}

const UploadedTempFiles: FC<UploadedTempFiles> = ({
  prevReportTemp,
  updateReportTempList,
  isLoading,
  t,
}) => {
  const { toast } = useToast();

  const downloadTempFile = async (fileName: string, filePath: string) => {
    try {
      const getTempFile = await fetch(filePath);

      if (getTempFile.ok) {
        const blob = await getTempFile.blob();

        saveAs(blob, fileName);

        toastMessage.success(t("templateUploadedList.downloadComplete"));
      } else {
        const err = await getTempFile.json();
        console.error("에러:", err);
        throw new Error(err.message);
      }
    } catch (err) {
      console.error(err);
      toast({
        title: t("templateUploadedList.error"),
        description: t("templateUploadedList.downloadError"),
        variant: "destructive",
      });
    }
  };

  const deleteTempFile = async (id: number) => {
    try {
      const { result, error } = await deleteReportTempFile(id);

      if (result) {
        updateReportTempList();
        toastMessage.success(t("templateUploadedList.deleteComplete"));
      } else {
        throw new Error(error);
      }
    } catch (err) {
      toast({
        title: t("templateUploadedList.error"),
        description: t("templateUploadedList.deleteError"),
        variant: "destructive",
      });
    }
  };

  if (isLoading) {
    return (
      <div className="min-h-[157px]">
        <Label>{t("templateUploadedList.loading")}</Label>
      </div>
    );
  }

  return (
    <ScrollArea className="min-h-[157px] max-h-[337px] overflow-auto">
      <FileList className="gap-3">
        {prevReportTemp.map((c) => {
          const { fileName, filePath, id } = c;

          return (
            <AlertDialog key={id}>
              <FileListItem className="p-3">
                <FileListHeader>
                  <FileListIcon />
                  <FileListInfo>
                    <FileListName>{fileName}</FileListName>
                  </FileListInfo>
                  <FileListAction
                    onClick={() => {
                      downloadTempFile(fileName, filePath);
                    }}
                  >
                    <Download className="h-4 w-4" />
                    <span className="sr-only">{t("templateUploadedList.download")}</span>
                  </FileListAction>
                  <AlertDialogTrigger asChild>
                    <FileListAction>
                      <Trash2 className="h-4 w-4" />
                      <span className="sr-only">{t("templateUploadedList.delete")}</span>
                    </FileListAction>
                  </AlertDialogTrigger>
                  <AlertDialogContent>
                    <AlertDialogHeader>
                      <AlertDialogTitle>
                        {t("templateUploadedList.deleteConfirmTitle", { fileName })}
                      </AlertDialogTitle>
                      <AlertDialogDescription />
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                      <AlertDialogCancel>{t("templateUploadedList.cancel")}</AlertDialogCancel>
                      <AlertDialogAction
                        onClick={() => {
                          deleteTempFile(id);
                        }}
                      >
                        {t("templateUploadedList.delete")}
                      </AlertDialogAction>
                    </AlertDialogFooter>
                  </AlertDialogContent>
                </FileListHeader>
              </FileListItem>
            </AlertDialog>
          );
        })}
      </FileList>
    </ScrollArea>
  );
};