"use client";

import React from "react";
import { ColumnDef } from "@tanstack/react-table";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Download, Loader2 } from "lucide-react";
import type { DocumentListItem } from "@/lib/swp/document-service";
import { toast } from "sonner";

export const swpDocumentColumns: ColumnDef<DocumentListItem>[] = [
  {
    accessorKey: "LTST_ACTV_STAT",
    header: "Status",
    cell: ({ row }) => {
      const status = row.original.LTST_ACTV_STAT;
      if (!status) return "Waiting";

      const color =
        status.includes("Complete") ? "bg-green-100 text-green-800" :
        status.includes("Progress") ? "bg-blue-100 text-blue-800" :
        status.includes("Pending") || status.includes("Ready") ? "bg-yellow-100 text-yellow-800" :
        "bg-gray-100 text-gray-800";

      return (
        <Badge variant="outline" className={color}>
          {status}
        </Badge>
      );
    },
    size: 150,
    minSize: 150,
    maxSize: 150,
  },
  {
    accessorKey: "OWN_DOC_NO",
    header: "OWN_DOC_NO",
    cell: ({ row }) => (
      <div className="font-mono text-sm">{row.original.OWN_DOC_NO || "-"}</div>
    ),
    size: 250,
    minSize: 250,
    maxSize: 250,
  },
  {
    accessorKey: "DOC_NO",
    header: "SHI DOC NO",
    cell: ({ row }) => (
      <div className="font-mono text-sm">{row.original.DOC_NO}</div>
    ),
    size: 250,
    minSize: 250,
    maxSize: 250,
  },
  {
    accessorKey: "DOC_TITLE",
    header: "Document Title",
    cell: ({ row }) => (
      <div className="truncate" title={row.original.DOC_TITLE}>
        {row.original.DOC_TITLE}
      </div>
    ),
    size: 300,
    minSize: 300,
    maxSize: 300,
  },
  {
    accessorKey: "PROJ_NO",
    header: "Project",
    cell: ({ row }) => (
      <div>
        <div className="font-medium">{row.original.PROJ_NO}</div>
        {row.original.PROJ_NM && (
          <div className="text-xs text-muted-foreground truncate">
            {row.original.PROJ_NM}
          </div>
        )}
      </div>
    ),
    size: 150,
    minSize: 150,
    maxSize: 150,
  },
  {
    accessorKey: "PKG_NO",
    header: "Package",
    cell: ({ row }) => row.original.PKG_NO || "-",
    size: 100,
    minSize: 100,
    maxSize: 100,
  },
  {
    accessorKey: "VNDR_CD",
    header: "Vendor",
    cell: ({ row }) => (
      <div>
        {row.original.VNDR_CD && (
          <div className="text-xs text-muted-foreground">{row.original.VNDR_CD}</div>
        )}
        {row.original.CPY_NM && (
          <div className="text-sm truncate" title={row.original.CPY_NM}>
            {row.original.CPY_NM}
          </div>
        )}
      </div>
    ),
    size: 120,
    minSize: 120,
    maxSize: 120,
  },
  {
    accessorKey: "STAGE",
    header: "Latest Stage",
    cell: ({ row }) => {
      const stage = row.original.STAGE;
      if (!stage) return "-";

      const color =
        stage === "IFC" ? "bg-green-100 text-green-800" :
        stage === "IFA" ? "bg-blue-100 text-blue-800" :
        "bg-gray-100 text-gray-800";

      return (
        <Badge variant="outline" className={color}>
          {stage}
        </Badge>
      );
    },
    size: 100,
    minSize: 100,
    maxSize: 100,
  },
  {
    accessorKey: "LTST_REV_NO",
    header: "Latest REV",
    cell: ({ row }) => row.original.LTST_REV_NO || "-",
    size: 100,
    minSize: 100,
    maxSize: 100,
  },

  {
    id: "actions",
    header: "Download Cover Page",
    cell: function ActionCell({ row }) {
      const [isDownloading, setIsDownloading] = React.useState(false);

      const handleDownloadCover = async (e: React.MouseEvent) => {
        e.stopPropagation(); // 행 클릭 이벤트 방지
        
        const docNumber = row.original.DOC_NO;
        const projectCode = row.original.PROJ_NO;

        if (!docNumber || !projectCode) {
          toast.error("Missing document number or project information.");
          return;
        }

        setIsDownloading(true);

        try {
          // 1. 프로젝트 코드로 프로젝트 ID 조회
          const projectIdResponse = await fetch(
            `/api/projects/code-to-id?code=${encodeURIComponent(projectCode)}`
          );
          
          if (!projectIdResponse.ok) {
            toast.error("Project information not found.");
            return;
          }

          const { projectId } = await projectIdResponse.json();

          // 2. 커버페이지 다운로드 API 호출
          const response = await fetch(
            `/api/projects/${projectId}/cover?docNumber=${encodeURIComponent(docNumber)}`
          );

          if (!response.ok) {
            const error = await response.json();
            throw new Error(error.message || "Failed to download cover page");
          }

          // 3. 파일 다운로드
          const blob = await response.blob();
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement("a");
          a.href = url;
          a.download = `${docNumber}_cover.pdf`;
          document.body.appendChild(a);
          a.click();
          window.URL.revokeObjectURL(url);
          document.body.removeChild(a);

          toast.success("Cover page download started.");

        } catch (error) {
          console.error("커버페이지 다운로드 오류:", error);
          toast.error(
            error instanceof Error 
              ? error.message 
              : "An error occurred while downloading the cover page."
          );
        } finally {
          setIsDownloading(false);
        }
      };

      return (
        <Button
          variant="ghost"
          size="sm"
          onClick={handleDownloadCover}
          disabled={isDownloading}
          className="h-8 w-8 p-0"
          title="Download Cover Page"
        >
          {isDownloading ? (
            <Loader2 className="h-4 w-4 animate-spin" />
          ) : (
            <Download className="h-4 w-4" />
          )}
        </Button>
      );
    },
    size: 180,
    minSize: 180,
    maxSize: 180,
  },
];
