"use client"

import * as React from "react"
import { Loader, Database, Check } from "lucide-react"
import { toast } from "sonner"
import {
  useReactTable,
  getCoreRowModel,
  getPaginationRowModel,
  getFilteredRowModel,
  ColumnDef,
  flexRender,
} from "@tanstack/react-table"

import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import { Checkbox } from "@/components/ui/checkbox"
import { ScrollArea } from "@/components/ui/scroll-area"

import { getSSLVWPurInqReqData } from "@/lib/basic-contract/sslvw-service"
import { SSLVWPurInqReq } from "@/lib/basic-contract/sslvw-service"

interface SSLVWPurInqReqDialogProps {
  onConfirm?: (selectedRows: SSLVWPurInqReq[]) => void
}

export function SSLVWPurInqReqDialog({ onConfirm }: SSLVWPurInqReqDialogProps) {
  const [open, setOpen] = React.useState(false)
  const [isLoading, setIsLoading] = React.useState(false)
  const [data, setData] = React.useState<SSLVWPurInqReq[]>([])
  const [error, setError] = React.useState<string | null>(null)
  const [rowSelection, setRowSelection] = React.useState<Record<string, boolean>>({})

  const loadData = async () => {
    setIsLoading(true)
    setError(null)
    try {
      const result = await getSSLVWPurInqReqData()
      if (result.success) {
        setData(result.data)
        if (result.isUsingFallback) {
          toast.info("테스트 데이터를 표시합니다.")
        }
      } else {
        setError(result.error || "데이터 로딩 실패")
        toast.error(result.error || "데이터 로딩 실패")
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : "알 수 없는 오류"
      setError(errorMessage)
      toast.error(errorMessage)
    } finally {
      setIsLoading(false)
    }
  }

  React.useEffect(() => {
    if (open) {
      loadData()
    } else {
      // 다이얼로그 닫힐 때 데이터 초기화
      setData([])
      setError(null)
      setRowSelection({})
    }
  }, [open])

  // 테이블 컬럼 정의 (동적 생성)
  const columns = React.useMemo<ColumnDef<SSLVWPurInqReq>[]>(() => {
    if (data.length === 0) return []

    const dataKeys = Object.keys(data[0])

    return [
      {
        id: "select",
        header: ({ table }) => (
          <Checkbox
            checked={
              table.getIsAllPageRowsSelected() ||
              (table.getIsSomePageRowsSelected() && "indeterminate")
            }
            onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
            aria-label="모든 행 선택"
          />
        ),
        cell: ({ row }) => (
          <Checkbox
            checked={row.getIsSelected()}
            onCheckedChange={(value) => row.toggleSelected(!!value)}
            aria-label="행 선택"
          />
        ),
        enableSorting: false,
        enableHiding: false,
      },
      ...dataKeys.map((key) => ({
        accessorKey: key,
        header: key,
        cell: ({ getValue }: any) => {
          const value = getValue()
          return value !== null && value !== undefined ? String(value) : ""
        },
      })),
    ]
  }, [data])

  // 테이블 인스턴스 생성
  const table = useReactTable({
    data,
    columns,
    getCoreRowModel: getCoreRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    onRowSelectionChange: setRowSelection,
    state: {
      rowSelection,
    },
  })

  // 선택된 행들 가져오기
  const selectedRows = table.getFilteredSelectedRowModel().rows.map(row => row.original)

  // 확인 버튼 핸들러
  const handleConfirm = () => {
    if (selectedRows.length === 0) {
      toast.error("행을 선택해주세요.")
      return
    }

    if (onConfirm) {
      onConfirm(selectedRows)
      toast.success(`${selectedRows.length}개의 행을 선택했습니다.`)
    } else {
      // 임시로 선택된 데이터 콘솔 출력
      console.log("선택된 행들:", selectedRows)
      toast.success(`${selectedRows.length}개의 행이 선택되었습니다. (콘솔 확인)`)
    }

    setOpen(false)
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button variant="outline" size="sm">
          <Database className="mr-2 size-4" aria-hidden="true" />
          법무검토 요청 데이터 조회
        </Button>
      </DialogTrigger>
      <DialogContent className="max-w-7xl max-h-[90vh] flex flex-col">
        <DialogHeader>
          <DialogTitle>법무검토 요청 데이터</DialogTitle>
          <DialogDescription>
            법무검토 요청 데이터를 조회합니다.
            {data.length > 0 && ` (${data.length}건, ${selectedRows.length}개 선택됨)`}
          </DialogDescription>
        </DialogHeader>

        <div className="flex flex-col h-full max-h-[calc(90vh-8rem)]">
          {isLoading ? (
            <div className="flex items-center justify-center flex-1 min-h-[200px]">
              <Loader className="mr-2 size-6 animate-spin" />
              <span>데이터 로딩 중...</span>
            </div>
          ) : error ? (
            <div className="flex items-center justify-center flex-1 min-h-[200px] text-red-500">
              <span>오류: {error}</span>
            </div>
          ) : data.length === 0 ? (
            <div className="flex items-center justify-center flex-1 min-h-[200px] text-muted-foreground">
              <span>데이터가 없습니다.</span>
            </div>
          ) : (
            <div className="flex flex-col flex-1 min-h-0">
              {/* 테이블 영역 - 스크롤 가능 */}
              <ScrollArea className="flex-1 border rounded-md">
                <Table className="min-w-full">
                  <TableHeader className="sticky top-0 bg-background z-10">
                    {table.getHeaderGroups().map((headerGroup) => (
                      <TableRow key={headerGroup.id}>
                        {headerGroup.headers.map((header) => (
                          <TableHead key={header.id} className="font-medium bg-background">
                            {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"}
                        >
                          {row.getVisibleCells().map((cell) => (
                            <TableCell key={cell.id} className="text-sm">
                              {flexRender(
                                cell.column.columnDef.cell,
                                cell.getContext()
                              )}
                            </TableCell>
                          ))}
                        </TableRow>
                      ))
                    ) : (
                      <TableRow>
                        <TableCell
                          colSpan={columns.length}
                          className="h-24 text-center"
                        >
                          데이터가 없습니다.
                        </TableCell>
                      </TableRow>
                    )}
                  </TableBody>
                </Table>
              </ScrollArea>

              {/* 페이지네이션 컨트롤 - 고정 영역 */}
              <div className="flex items-center justify-between px-2 py-4 border-t bg-background flex-shrink-0">
                <div className="flex-1 text-sm text-muted-foreground">
                  {table.getFilteredSelectedRowModel().rows.length}개 행 선택됨
                </div>
                <div className="flex items-center space-x-6 lg:space-x-8">
                  <div className="flex items-center space-x-2">
                    <p className="text-sm font-medium">페이지당 행 수</p>
                    <select
                      value={table.getState().pagination.pageSize}
                      onChange={(e) => {
                        table.setPageSize(Number(e.target.value))
                      }}
                      className="h-8 w-[70px] rounded border border-input bg-transparent px-3 py-1 text-sm ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2"
                    >
                      {[10, 20, 30, 40, 50].map((pageSize) => (
                        <option key={pageSize} value={pageSize}>
                          {pageSize}
                        </option>
                      ))}
                    </select>
                  </div>
                  <div className="flex w-[100px] items-center justify-center text-sm font-medium">
                    {table.getState().pagination.pageIndex + 1} /{" "}
                    {table.getPageCount()}
                  </div>
                  <div className="flex items-center space-x-2">
                    <Button
                      variant="outline"
                      className="h-8 w-8 p-0"
                      onClick={() => table.setPageIndex(0)}
                      disabled={!table.getCanPreviousPage()}
                    >
                      <span className="sr-only">첫 페이지로</span>
                      {"<<"}
                    </Button>
                    <Button
                      variant="outline"
                      className="h-8 w-8 p-0"
                      onClick={() => table.previousPage()}
                      disabled={!table.getCanPreviousPage()}
                    >
                      <span className="sr-only">이전 페이지</span>
                      {"<"}
                    </Button>
                    <Button
                      variant="outline"
                      className="h-8 w-8 p-0"
                      onClick={() => table.nextPage()}
                      disabled={!table.getCanNextPage()}
                    >
                      <span className="sr-only">다음 페이지</span>
                      {">"}
                    </Button>
                    <Button
                      variant="outline"
                      className="h-8 w-8 p-0"
                      onClick={() => table.setPageIndex(table.getPageCount() - 1)}
                      disabled={!table.getCanNextPage()}
                    >
                      <span className="sr-only">마지막 페이지로</span>
                      {">>"}
                    </Button>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>

        <DialogFooter className="gap-2">
          <Button variant="outline" onClick={() => setOpen(false)}>
            닫기
          </Button>
          {/* <Button onClick={loadData} disabled={isLoading} variant="outline">
            {isLoading ? (
              <>
                <Loader className="mr-2 size-4 animate-spin" />
                로딩 중...
              </>
            ) : (
              "새로고침"
            )}
          </Button> */}
          <Button onClick={handleConfirm} disabled={selectedRows.length === 0}>
            <Check className="mr-2 size-4" />
            확인 ({selectedRows.length})
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
