"use client"

import * as React from "react"
import { type DataTableRowAction } from "@/types/table"
import { type ColumnDef } from "@tanstack/react-table"

import { formatDateTime } from "@/lib/utils"
import { Badge } from "@/components/ui/badge"
import { Checkbox } from "@/components/ui/checkbox"
import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header"
import { Button } from "@/components/ui/button"
import { MoreHorizontal, Eye, FileText, Calendar } from "lucide-react"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { useRouter } from "next/navigation"
import { BasicContractTemplateStatsView } from "@/db/schema"

type NextRouter = ReturnType<typeof useRouter>;


interface GetColumnsProps {
  setRowAction: React.Dispatch<React.SetStateAction<DataTableRowAction<BasicContractTemplateStatsView> | null>>
  router: NextRouter;

}

/**
 * BasicContractTemplateStatsView용 컬럼 정의
 */
export function getColumns({ setRowAction, router }: GetColumnsProps): ColumnDef<BasicContractTemplateStatsView>[] {
  // ----------------------------------------------------------------
  // 1) select 컬럼 (체크박스)
  // ----------------------------------------------------------------
  const selectColumn: ColumnDef<BasicContractTemplateStatsView> = {
    id: "select",
    header: ({ table }) => (
      <Checkbox
        checked={
          table.getIsAllPageRowsSelected() ||
          (table.getIsSomePageRowsSelected() && "indeterminate")
        }
        onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
        aria-label="Select all"
        className="translate-y-0.5"
      />
    ),
    cell: ({ row }) => (
      <Checkbox
        checked={row.getIsSelected()}
        onCheckedChange={(value) => row.toggleSelected(!!value)}
        aria-label="Select row"
        className="translate-y-0.5"
      />
    ),
    maxSize: 30,
    enableSorting: false,
    enableHiding: false,
  }

  // ----------------------------------------------------------------
  // 2) Actions 컬럼
  // ----------------------------------------------------------------
  const actionsColumn: ColumnDef<BasicContractTemplateStatsView> = {
    id: "actions",
    header: "작업",
    cell: ({ row }) => {
      const template = row.original
      const detailUrl = `/evcp/basic-contract/${template.templateId}`;
      
      return (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="ghost" className="h-8 w-8 p-0">
              <span className="sr-only">Open menu</span>
              <MoreHorizontal className="h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem onClick={() => router.push(detailUrl)}>
              <Eye className="mr-2 h-4 w-4" />
              상세 보기
            </DropdownMenuItem>
            <DropdownMenuItem onClick={() => setRowAction({ type: "view", row })}>
              <FileText className="mr-2 h-4 w-4" />
              템플릿 보기
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      )
    },
    enableSorting: false,
    enableHiding: false,
    maxSize: 80,
  }

  // ----------------------------------------------------------------
  // 3) 기본 정보 컬럼들
  // ----------------------------------------------------------------
  const basicInfoColumns: ColumnDef<BasicContractTemplateStatsView>[] = [
    {
      accessorKey: "templateName",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="템플릿명" />
      ),
      cell: ({ row }) => {
        const name = row.getValue("templateName") as string
        return (
          <div className="font-medium">
            {name}
          </div>
        )
      },
      minSize: 200,
    },
    {
      accessorKey: "revision",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="리비전" />
      ),
      cell: ({ row }) => {
        const revision = row.getValue("revision") as number
        return (
          <Badge variant="outline">
            v{revision}
          </Badge>
        )
      },
      minSize: 80,
    },
  ]

  // ----------------------------------------------------------------
  // 4) 발송/처리 현황 컬럼들
  // ----------------------------------------------------------------
  const processStatusColumns: ColumnDef<BasicContractTemplateStatsView>[] = [
    {
      accessorKey: "totalSentCount",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="발송건수" />
      ),
      cell: ({ row }) => {
        const count = row.getValue("totalSentCount") as number
        return (
          <div className="text-center font-medium">
            {count.toLocaleString()}
          </div>
        )
      },
      minSize: 100,
    },
    {
      accessorKey: "overdueCount",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="지연건수" />
      ),
      cell: ({ row }) => {
        const count = row.getValue("overdueCount") as number
        const total = row.getValue("totalSentCount") as number
        const isHigh = total > 0 && (count / total) > 0.2
        
        return (
          <div className={`text-center font-medium ${isHigh ? 'text-red-600' : 'text-gray-900'}`}>
            {count.toLocaleString()}
          </div>
        )
      },
      minSize: 100,
    },
    {
      accessorKey: "unsignedCount",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="미서명건수" />
      ),
      cell: ({ row }) => {
        const count = row.getValue("unsignedCount") as number
        return (
          <div className="text-center font-medium text-orange-600">
            {count.toLocaleString()}
          </div>
        )
      },
      minSize: 120,
    },
  ]

  // ----------------------------------------------------------------
  // 5) 법무검토 현황 컬럼들
  // ----------------------------------------------------------------
  const legalReviewColumns: ColumnDef<BasicContractTemplateStatsView>[] = [
    {
      accessorKey: "legalRequestCount",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="법무요청" />
      ),
      cell: ({ row }) => {
        const count = row.getValue("legalRequestCount") as number
        return (
          <div className="text-center font-medium text-purple-600">
            {count.toLocaleString()}
          </div>
        )
      },
      minSize: 100,
    },
    {
      accessorKey: "legalCompletedCount",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="법무완료" />
      ),
      cell: ({ row }) => {
        const count = row.getValue("legalCompletedCount") as number
        return (
          <div className="text-center font-medium text-indigo-600">
            {count.toLocaleString()}
          </div>
        )
      },
      minSize: 100,
    },
    {
      accessorKey: "contractCompletedCount",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="계약완료" />
      ),
      cell: ({ row }) => {
        const count = row.getValue("contractCompletedCount") as number
        return (
          <div className="text-center font-medium text-indigo-600">
            {count.toLocaleString()}
          </div>
        )
      },
      minSize: 100,
    },
  ]

  // ----------------------------------------------------------------
  // 6) 성과 지표 컬럼들
  // ----------------------------------------------------------------
  const performanceColumns: ColumnDef<BasicContractTemplateStatsView>[] = [
    {
      accessorKey: "avgProcessingDays",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="평균처리일" />
      ),
      cell: ({ row }) => {
        const days = row.getValue("avgProcessingDays") as number | null
        if (!days) return "-"
        
        const rounded = Math.round(days * 10) / 10
        const isGood = rounded <= 5
        const isWarning = rounded > 5 && rounded <= 10
        
        let colorClass = "text-gray-900"
        if (isGood) colorClass = "text-green-600"
        else if (isWarning) colorClass = "text-orange-600"
        else colorClass = "text-red-600"
        
        return (
          <div className={`text-center font-medium ${colorClass}`}>
            {rounded}일
          </div>
        )
      },
      minSize: 100,
    },
  ]

  // ----------------------------------------------------------------
  // 7) 시간 정보 컬럼들
  // ----------------------------------------------------------------
  const timeInfoColumns: ColumnDef<BasicContractTemplateStatsView>[] = [
    {
      accessorKey: "templateCreatedAt",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="생성일" />
      ),
      cell: ({ row }) => {
        const date = row.getValue("templateCreatedAt") as Date
        return formatDateTime(date, "KR")
      },
      minSize: 120,
    },
    {
      accessorKey: "lastActivityDate",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="최근활동" />
      ),
      cell: ({ row }) => {
        const date = row.getValue("lastActivityDate") as Date | null
        return date ? formatDateTime(date, "KR") : "-"
      },
      minSize: 120,
    },
  ]

  // ----------------------------------------------------------------
  // 8) 최종 컬럼 배열 (평면 구조)
  // ----------------------------------------------------------------
  return [
    selectColumn,
    ...basicInfoColumns,
    ...processStatusColumns,
    ...legalReviewColumns,
    ...performanceColumns,
    ...timeInfoColumns,
    actionsColumn,
  ]
}