"use client"

import { ColumnDef } from "@tanstack/react-table"
import { Badge } from "@/components/ui/badge"
// import { DataTableColumnHeader } from "@/components/data-table/data-table-column-header"
import { DataTableRowAction } from "@/types/table"
import { Ellipsis } from "lucide-react"
import { formatDate } from "@/lib/utils"
import { 
  DropdownMenu, 
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger 
} from "@/components/ui/dropdown-menu"
import { Button } from "@/components/ui/button"
import React, { useMemo, useState } from "react"
import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header"
import { Checkbox } from "@/components/ui/checkbox"
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetFooter,
  SheetHeader,
  SheetTitle,
} from "@/components/ui/sheet"
import { DatePicker } from "@/components/ui/date-picker"
import { toast } from "sonner"

export interface PQList {
  id: number
  name: string
  type: "GENERAL" | "PROJECT" | "NON_INSPECTION"
  projectId?: number | null
  projectCode?: string | null
  projectName?: string | null
  isDeleted: boolean
  validTo?: Date | null
  createdBy?: string | null // 이제 사용자 이름(users.name)
  createdAt: Date
  updatedAt: Date
  updatedBy?: string | null
  criteriaCount?: number
}

const typeLabels = {
  GENERAL: "일반 PQ",
  PROJECT: "프로젝트 PQ", 
  NON_INSPECTION: "미실사 PQ"
}

const typeColors = {
  GENERAL: "bg-blue-100 text-blue-800",
  PROJECT: "bg-green-100 text-green-800",
  NON_INSPECTION: "bg-orange-100 text-orange-800"
}

interface GetColumnsProps {
  setRowAction: React.Dispatch<React.SetStateAction<DataTableRowAction<PQList> | null>>
}

// 유효일 수정 시트 컴포넌트
interface EditValidToSheetProps {
  pqList: PQList | null
  open: boolean
  onOpenChange: (open: boolean) => void
  onUpdate: (pqListId: number, newValidTo: Date | null) => Promise<void>
}

export function EditValidToSheet({ pqList, open, onOpenChange, onUpdate }: EditValidToSheetProps) {
  const [newValidTo, setNewValidTo] = useState<Date | null>(pqList?.validTo || null)
  const [isLoading, setIsLoading] = useState(false)

  const handleSave = async () => {
    if (!pqList) return

    setIsLoading(true)
    try {
      await onUpdate(pqList.id, newValidTo)
      onOpenChange(false)
    } catch (error) {
      console.error("유효일 수정 실패:", error)
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent>
        <SheetHeader>
          <SheetTitle>유효일 수정</SheetTitle>
          <SheetDescription>
            {pqList && (
              <>
                <strong>{pqList.name}</strong>의 유효일을 수정합니다.
              </>
            )}
          </SheetDescription>
        </SheetHeader>

        <div className="py-6">
          <div className="space-y-4">
            <div>
              <label className="text-sm font-medium">현재 유효일</label>
              <div className="mt-1 p-2 bg-muted rounded-md">
                {pqList?.validTo ? formatDate(pqList.validTo, "ko-KR") : "설정되지 않음"}
              </div>
            </div>

            <div>
              <label className="text-sm font-medium">새 유효일</label>
              <div className="mt-1">
                <DatePicker
                  date={newValidTo ?? undefined}
                  onSelect={(date) => setNewValidTo(date ?? null)}
                  placeholder="새 유효일을 선택하세요"
                  minDate={new Date()}
                />
              </div>
            </div>
          </div>
        </div>

        <SheetFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            취소
          </Button>
          <Button onClick={handleSave} disabled={isLoading}>
            {isLoading && <div className="mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent" />}
            저장
          </Button>
        </SheetFooter>
      </SheetContent>
    </Sheet>
  )
}

export function createPQListsColumns({
  setRowAction
}: GetColumnsProps): ColumnDef<PQList>[] {
  return [
    {
      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"
        />
      ),
      size:40,
      enableSorting: false,
      enableHiding: false,
    },
    {
      accessorKey: "name",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="PQ 리스트명" />
      ),
      cell: ({ row }) => (
        <div className="max-w-[200px] truncate font-medium">
          {row.getValue("name")}
        </div>
      ),
    },
    {
      accessorKey: "type",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="PQ 종류" />
      ),
      cell: ({ row }) => {
        const type = row.getValue("type") as keyof typeof typeLabels
        return (
          <Badge className={typeColors[type]}>
            {typeLabels[type]}
          </Badge>
        )
      },
      filterFn: (row, id, value) => {
        return value.includes(row.getValue(id))
      },
    },
    {
      accessorKey: "projectCode",
      header: "프로젝트",
      cell: ({ row }) => row.original.projectCode ?? "-",
    },
    {
      accessorKey: "projectName",
      header: "프로젝트명",
      cell: ({ row }) => row.original.projectName ?? "-",
    },
    {
      accessorKey: "validTo",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="유효일" />
      ),
      cell: ({ row }) => {
        const validTo = row.getValue("validTo") as Date | null

        const dateInfo = useMemo(() => {
          if (!validTo) return { formattedDate: "-", isExpired: false }

          const now = new Date()
          const isExpired = validTo < now
          const formattedDate = formatDate(validTo, "ko-KR")

          return { formattedDate, isExpired }
        }, [validTo])

        return (
          <div className="text-sm">
            <span className={dateInfo.isExpired ? "text-red-600 font-medium" : ""}>
              {dateInfo.formattedDate}
            </span>
            {dateInfo.isExpired && (
              <Badge variant="destructive" className="ml-2 text-xs">
                만료
              </Badge>
            )}
          </div>
        )
      },
    },
    {
      accessorKey: "isDeleted",
      header: "상태",
      cell: ({ row }) => {
        const isDeleted = row.getValue("isDeleted") as boolean;
        return (
          <Badge variant={isDeleted ? "destructive" : "success"}>
            {isDeleted ? "비활성" : "활성"}
          </Badge>
        );
      },
    },
    {
      accessorKey: "createdBy",
      header: "생성자",
      cell: ({ row }) => row.original.createdBy ?? "-",
    },
    {
      accessorKey: "updatedBy",
      header: "변경자",
      cell: ({ row }) => row.original.updatedBy ?? "-",
    },
    {
      accessorKey: "createdAt",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="생성일" />
      ),
      cell: ({ row }) => {
        const createdAt = row.getValue("createdAt") as Date
        return useMemo(() => formatDate(createdAt, "ko-KR"), [createdAt])
      },
    },
    {
      accessorKey: "updatedAt",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="변경일" />
      ),
      cell: ({ row }) => {
        const updatedAt = row.getValue("updatedAt") as Date
        return useMemo(() => formatDate(updatedAt, "ko-KR"), [updatedAt])
      },
    },
    {
      id: "actions",
      cell: ({ row }) => (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
          <Button
                aria-label="Open menu"
                variant="ghost"
                className="flex size-7 p-0 data-[state=open]:bg-muted"
              >
                <Ellipsis className="size-4" aria-hidden="true" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end" className="w-40">
            <DropdownMenuItem
              onSelect={() => setRowAction({ row, type: "view" })}
            >
              상세보기
            </DropdownMenuItem>
            <DropdownMenuItem
              onSelect={() => setRowAction({ row, type: "editValidTo" })}
            >
              유효일 수정
            </DropdownMenuItem>
            {/* <DropdownMenuSeparator />
            <DropdownMenuItem
              onSelect={() => setRowAction({ row, type: "delete" })}
              className="text-destructive"
            >
              삭제
              <DropdownMenuShortcut>⌘⌫</DropdownMenuShortcut>
            </DropdownMenuItem> */}
          </DropdownMenuContent>
        </DropdownMenu>
      ),
      size: 40,
      enableSorting: false,
      enableHiding: false,
    }
  
  ]
} 