"use client";

import React, { useMemo, 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 { 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;
}

// Status 집계 타입
interface StatusCount {
  status: string;
  count: number;
}

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

  // Status 집계
  const statusCounts = useMemo(() => {
    const statusMap = new Map<string, number>();
    
    documents.forEach((doc) => {
      const status = doc.LTST_ACTV_STAT || "Waiting";
      statusMap.set(status, (statusMap.get(status) || 0) + 1);
    });

    const counts: StatusCount[] = [];
    statusMap.forEach((count, status) => {
      counts.push({
        status,
        count,
      });
    });

    // 개수 순으로 정렬
    return counts.sort((a, b) => b.count - a.count);
  }, [documents]);

  // Status 필터링된 문서 목록
  const filteredDocuments = useMemo(() => {
    if (!selectedStatus) {
      return documents;
    }
    return documents.filter((doc) => (doc.LTST_ACTV_STAT || "Waiting") === selectedStatus);
  }, [documents, selectedStatus]);

  const table = useReactTable({
    data: filteredDocuments,
    columns: swpDocumentColumns,
    getCoreRowModel: getCoreRowModel(),
    enableColumnResizing: false,
    columnResizeMode: 'onChange',
  });

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

  return (
    <div className="space-y-4">
      {/* Status 필터 UI */}
      <div className="flex flex-wrap gap-2 p-4 bg-muted/30 rounded-lg">
        <Button
          variant={selectedStatus === null ? "default" : "outline"}
          size="sm"
          onClick={() => setSelectedStatus(null)}
          className="h-9"
        >
          All ({documents.length})
        </Button>
        {statusCounts.map((statusCount) => (
          <Button
            key={statusCount.status}
            variant={selectedStatus === statusCount.status ? "default" : "outline"}
            size="sm"
            onClick={() => setSelectedStatus(statusCount.status)}
            className="h-9"
          >
            {statusCount.status} ({statusCount.count})
          </Button>
        ))}
      </div>

      {/* 테이블 */}
      <div className="rounded-md border overflow-x-auto">
        <Table className="min-w-[1700px]">
          <TableHeader>
            {table.getHeaderGroups().map((headerGroup) => (
              <TableRow key={headerGroup.id}>
                {headerGroup.headers.map((header) => (
                  <TableHead 
                    key={header.id}
                    style={{
                      width: header.column.getSize(),
                      minWidth: header.column.getSize(),
                      maxWidth: header.column.getSize(),
                    }}
                  >
                    {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}
                      style={{
                        width: cell.column.getSize(),
                        minWidth: cell.column.getSize(),
                        maxWidth: cell.column.getSize(),
                      }}
                    >
                      {flexRender(cell.column.columnDef.cell, cell.getContext())}
                    </TableCell>
                  ))}
                </TableRow>
              ))
            ) : (
              <TableRow>
                <TableCell colSpan={swpDocumentColumns.length} className="h-24 text-center">
                  No data
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>

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