"use client"

import React, { useEffect, useState } from "react"
import { ScrollArea } from "@/components/ui/scroll-area"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import { 
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger 
} from "@/components/ui/tooltip"
import { FileIcon, Building } from "lucide-react"
import { Button } from "@/components/ui/button"
import { getDocumentVersionsByDocId } from "@/lib/vendor-document/service"
import { Badge } from "@/components/ui/badge"

type StageListProps = {
  document: {
    id: number
    docNumber: string
    title: string
    // ...
  }
}

// 인터페이스
interface Attachment {
  id: number
  fileName: string
  filePath: string
  fileType?: string
}

interface Version {
  id: number
  stage: string
  revision: string
  uploaderType: string
  uploaderName: string | null
  comment: string | null
  status: string | null
  planDate: string | null
  actualDate: string | null
  approvedDate: string | null
  attachments: Attachment[]
}

export default function StageSHIList({ document }: StageListProps) {
  const [versions, setVersions] = useState<Version[]>([])

  useEffect(() => {
    if (!document?.id) return
    // shi 업로더 타입만 필터링
    getDocumentVersionsByDocId(document.id, ['shi']).then((data) => {
      setVersions(data)
    })
  }, [document])

  // 스테이지 옵션 추출
  const stageOptions = React.useMemo(() => {
    const stageSet = new Set<string>()
    for (const v of versions) {
      if (v.stage) {
        stageSet.add(v.stage)
      }
    }
    return Array.from(stageSet)
  }, [versions])

  // Handle file download with original filename
  const handleDownload = (attachmentPath: string, fileName: string) => {
    if (attachmentPath) {
      // Use window.document to avoid collision with the document prop
      const link = window.document.createElement('a');
      link.href = attachmentPath;
      link.download = fileName || 'download'; // Use the original filename or a default
      window.document.body.appendChild(link);
      link.click();
      window.document.body.removeChild(link);
    }
  }

  // 파일 확장자에 따른 아이콘 색상 반환
  const getFileIconColor = (fileName: string) => {
    const ext = fileName.split('.').pop()?.toLowerCase();
    
    switch(ext) {
      case 'pdf':
        return 'text-red-500';
      case 'doc':
      case 'docx':
        return 'text-blue-500';
      case 'xls':
      case 'xlsx':
        return 'text-green-500';
      case 'dwg':
        return 'text-amber-500';
      default:
        return 'text-gray-500';
    }
  }

  return (
    <>
      <div className="flex items-center justify-between p-2">
        <h2 className="font-semibold text-base flex items-center gap-2">
          {/* <Building className="h-4 w-4 text-amber-600" /> */}
          From 삼성중공업 ({document.docNumber} {document.title})
        </h2>
      </div>

      <ScrollArea className="h-full p-2">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="w-[100px]">Stage</TableHead>
              <TableHead className="w-[100px]">Revision</TableHead>
              <TableHead className="w-[150px]">첨부파일</TableHead>
              <TableHead className="w-[100px]">상태</TableHead>
              <TableHead className="w-[120px]">코멘트</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {versions.length ? (
              versions.map((ver) => (
                <TableRow key={ver.id}>
                  <TableCell>{ver.stage}</TableCell>
                  <TableCell>{ver.revision}</TableCell>
                  <TableCell>
                    <div className="flex flex-wrap gap-2">
                      {ver.attachments && ver.attachments.length > 0 ? (
                        ver.attachments.map((file) => (
                          <TooltipProvider key={file.id}>
                            <Tooltip>
                              <TooltipTrigger asChild>
                                <Button 
                                  variant="ghost" 
                                  size="sm" 
                                  className="h-8 w-8 p-0"
                                  onClick={() => handleDownload(file.filePath, file.fileName)}
                                >
                                  <FileIcon className={`h-5 w-5 ${getFileIconColor(file.fileName)}`} />
                                </Button>
                              </TooltipTrigger>
                              <TooltipContent>
                                <p>{file.fileName || "Download file"}</p>
                              </TooltipContent>
                            </Tooltip>
                          </TooltipProvider>
                        ))
                      ) : (
                        <Badge variant="outline" className="text-xs">
                          파일 없음
                        </Badge>
                      )}
                    </div>
                  </TableCell>
                  <TableCell>
                    {ver.status && (
                      <Badge variant="outline" className="bg-amber-50 text-amber-800">
                        {ver.status}
                      </Badge>
                    )}
                  </TableCell>
                  <TableCell>{ver.comment || "-"}</TableCell>
                </TableRow>
              ))
            ) : (
              <TableRow>
                <TableCell colSpan={5} className="text-center">
                  삼성중공업 문서가 없습니다.
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </ScrollArea>
    </>
  )
}