import React, { useState, useEffect } from "react";
import { Card, CardContent } from "@/shared/common/ui/card";
import { Button } from "@/shared/common/ui/button";
import { ArrowBigDownDash, ExternalLink, File, Trash2 } from "lucide-react";

import { useQuery } from "@tanstack/react-query";
import {
  getAttachmentsById,
  getSealedAttachmentsById,
} from "../services/api/userRecordService";
import { useTranslation } from "react-i18next";

export interface IAttachmentInfoWithId {
  id?: string;
  fileInfo: {
    fileName: string;
    contentType?: string;
    size?: number;
    type?: string;
    lastModified?: number;
    originalname?: string;
  };
  presigned?: string;
  length?: number;
  itemId?: string;
}

interface FileListProps {
  attachments: IAttachmentInfoWithId[];
  showDelete: boolean;
  onDelete?: (fileId: string) => void;
}
const formatFileSize = (sizeInBytes: number): string => {
  if (sizeInBytes < 1024) return `${sizeInBytes} B`;
  if (sizeInBytes < 1024 * 1024) return `${(sizeInBytes / 1024).toFixed(2)} KB`;
  return `${(sizeInBytes / (1024 * 1024)).toFixed(2)} MB`;
};
const FileList: React.FC<FileListProps> = ({
  attachments,
  onDelete,
  showDelete,
}) => {
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const [selectedFile, setSelectedFile] = useState<string | null>(null);
  const { t } = useTranslation();

  const { data: fetchedFile, isSuccess } = useQuery({
    queryKey: ["record-attachment", selectedId],
    queryFn: async () => {
      if (!selectedId) return null;

      try {
        // Try regular attachment first
        return await getAttachmentsById(selectedId);
      } catch (error) {
        // If it fails, try sealed attachment
        return await getSealedAttachmentsById(selectedId);
      }
    },
    enabled: !!selectedId,
    staleTime: 1000 * 60 * 5,
  });
  // Open presigned URL when fetched
  useEffect(() => {
    if (fetchedFile?.presigned && isSuccess) {
      const url = fetchedFile.presigned;
      openFile(url, fetchedFile);
      setSelectedId(null);
    } else if (selectedFile) {
      openFile(selectedFile, fetchedFile);
      setSelectedFile(null);
    }
  }, [fetchedFile, isSuccess, selectedFile]);

  const openFile = (url: string, fetchedFile: any) => {
    const contentType = fetchedFile?.fileInfo?.contentType;
    // Detect Office file types
    if (
      contentType === "application/vnd.ms-excel" ||
      contentType ===
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    ) {
      window.location.href = `ms-excel:ofe|u|${url}`;
    } else if (
      contentType === "application/vnd.ms-powerpoint" ||
      contentType ===
        "application/vnd.openxmlformats-officedocument.presentationml.presentation"
    ) {
      window.location.href = `ms-powerpoint:ofe|u|${url}`;
    } else if (
      contentType === "application/msword" ||
      contentType ===
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
    ) {
      window.location.href = `ms-word:ofe|u|${url}`;
    } else {
      // Fallback: open normally in browser tab
      window.open(url, "_blank", "noopener,noreferrer");
    }
  };

  const downloadFile = async (url: string, fileName: string) => {
    const response = await fetch(url, {
      // credentials optional based on your API
      // credentials: "include"
    });

    const blob = await response.blob();
    const blobUrl = URL.createObjectURL(blob);

    const link = document.createElement("a");
    link.href = blobUrl;
    link.download = fileName;

    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    URL.revokeObjectURL(blobUrl);
  };

  const handleOpen = (id: string | undefined) => {
    if (id) setSelectedId(id);
  };
  return (
    <Card className="w-full">
      <CardContent>
        {attachments.length > 0 ? (
          <ul className="space-y-2">
            {attachments.map((file) => (
              <li
                key={
                  file?.id ||
                  file?.itemId ||
                  file?.fileInfo.fileName ||
                  Math.random().toString()
                }
                className="flex flex-col sm:flex-row sm:items-center justify-between border p-3 rounded-lg bg-white dark:bg-gray-800 dark:border-gray-700 w-full gap-3">
                <div className="flex items-start sm:items-center space-x-3 min-w-0 w-full sm:w-auto">
                  <File className="w-8 h-8 text-primary-600 dark:text-primary-300 flex-shrink-0 mt-0.5 sm:mt-0" />
                  <div className="flex flex-col min-w-0 flex-1 sm:flex-initial" title={file?.fileInfo.originalname}>
                    <span className="truncate font-medium text-gray-700 dark:text-gray-100 text-sm sm:text-base" title={file?.fileInfo.originalname}>
                      {file?.fileInfo.originalname}
                    </span>
                    <span className="text-xs sm:text-sm text-gray-500 dark:text-gray-300">
                      {formatFileSize(file?.fileInfo.size || 0)}
                    </span>
                  </div>
                </div>

                <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-2 w-full sm:w-auto">
                  <Button
                    size="sm"
                    variant="outline"
                    className="w-full sm:w-auto justify-center flex items-center space-x-1 bg-primary-50 hover:bg-primary-100 text-primary-700 dark:bg-primary-900/50 dark:hover:bg-primary-800/70 dark:text-white dark:border-primary-700"
                    onClick={() =>
                      handleOpen(
                        file?.id ?? setSelectedFile(file.presigned || "") ?? "",
                      )
                    }>
                    <ExternalLink className="w-4 h-4" />
                    <span>{t("viewDetail.open")}</span>
                  </Button>
                  <Button
                    size="sm"
                    variant="outline"
                    className="w-full sm:w-auto justify-center flex items-center space-x-1 bg-primary-50 hover:bg-primary-100 text-primary-700 dark:bg-primary-900/50 dark:hover:bg-primary-800/70 dark:text-white dark:border-primary-700"
                    onClick={() =>
                      downloadFile(
                        file.presigned || "",
                        file?.fileInfo?.originalname || "",
                      )
                    }>
                    <ArrowBigDownDash className="w-4 h-4" />
                    <span>{t("userRecord.Download")}</span>
                  </Button>
                  {showDelete && onDelete && (
                    <Button
                      size="sm"
                      variant="ghost"
                      className="w-full sm:w-auto justify-center flex items-center space-x-1 text-red-600 hover:bg-red-50 dark:text-red-400 dark:hover:bg-red-900/50"
                      onClick={() => onDelete(file?.id || file.itemId || "")}>
                      <Trash2 className="w-4 h-4" />
                      <span className="sm:hidden">{t("common.delete", "Delete")}</span>
                    </Button>
                  )}
                </div>
              </li>
            ))}
          </ul>
        ) : (
          <p className="text-gray-500 dark:text-gray-400">
            {t("viewDetail.noAttachmentsAvailable")}
          </p>
        )}
      </CardContent>
    </Card>
  );
};

export default FileList;
