"use client";

import React, { useState } from "react";
import {
  useReactTable,
  getCoreRowModel,
  flexRender,
} from "@tanstack/react-table";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import { ChevronRight } from "lucide-react";
import { swpDocumentColumns } from "./swp-table-columns";
import { SwpDocumentDetailDialog } from "./swp-document-detail-dialog";
import type { DocumentListItem } from "@/lib/swp/document-service";

interface SwpTableProps {
  documents: DocumentListItem[];
  projNo: string;
  vendorCode: string;
  userId: string;
}

export function SwpTable({
  documents,
  projNo,
  vendorCode,
  userId,
}: SwpTableProps) {
  const [dialogOpen, setDialogOpen] = useState(false);
  const [selectedDocument, setSelectedDocument] = useState<DocumentListItem | null>(null);

  const table = useReactTable({
    data: documents,
    columns: swpDocumentColumns,
    getCoreRowModel: getCoreRowModel(),
  });

  // 문서 클릭 핸들러 - Dialog 열기
  const handleDocumentClick = (document: DocumentListItem) => {
    setSelectedDocument(document);
    setDialogOpen(true);
  };

  return (
    <div className="space-y-4">
      {/* 테이블 */}
      <div className="rounded-md border">
        <Table>
          <TableHeader>
            {table.getHeaderGroups().map((headerGroup) => (
              <TableRow key={headerGroup.id}>
                {headerGroup.headers.map((header) => (
                  <TableHead key={header.id}>
                    {header.isPlaceholder
                      ? null
                      : flexRender(
                          header.column.columnDef.header,
                          header.getContext()
                        )}
                  </TableHead>
                ))}
              </TableRow>
            ))}
          </TableHeader>
          <TableBody>
            {table.getRowModel().rows?.length ? (
              table.getRowModel().rows.map((row) => (
                <TableRow
                  key={row.id}
                  data-state={row.getIsSelected() && "selected"}
                  className="hover:bg-muted/50 cursor-pointer"
                  onClick={() => handleDocumentClick(row.original)}
                >
                  {row.getVisibleCells().map((cell) => (
                    <TableCell key={cell.id}>
                      {cell.column.id === "expander" ? (
                        <Button
                          variant="ghost"
                          size="sm"
                          className="h-8 w-8 p-0"
                        >
                          <ChevronRight className="h-4 w-4" />
                        </Button>
                      ) : (
                        flexRender(cell.column.columnDef.cell, cell.getContext())
                      )}
                    </TableCell>
                  ))}
                </TableRow>
              ))
            ) : (
              <TableRow>
                <TableCell colSpan={swpDocumentColumns.length} className="h-24 text-center">
                  데이터 없음
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>

      {/* 문서 상세 Dialog */}
      <SwpDocumentDetailDialog
        open={dialogOpen}
        onOpenChange={setDialogOpen}
        document={selectedDocument}
        projNo={projNo}
        vendorCode={vendorCode}
        userId={userId}
      />
    </div>
  );
}
