"use client"

import * as React from "react"
import { useRouter } from "next/navigation"
import { toast } from "sonner"

import { useDataTable } from "@/hooks/use-data-table"
import { DataTable } from "@/components/data-table/data-table"
import { DataTableAdvancedToolbar } from "@/components/data-table/data-table-advanced-toolbar"
import { createPQListsColumns, type PQList } from "./pq-lists-columns"
import {
  createPQListAction,
  deletePQListsAction,
  copyPQListAction,
  togglePQListsAction,
  updatePqValidToAction,
} from "@/lib/pq/service"
import { CopyPqDialog } from "./copy-pq-list-dialog"
import { AddPqDialog } from "./add-pq-list-dialog"
import { PQListsToolbarActions } from "./pq-lists-toolbar"
import { EditValidToSheet } from "./pq-lists-columns"
import type { DataTableRowAction } from "@/types/table"

interface Project {
  id: number
  name: string
  code: string
}

interface PqListsTableProps {
  promises: Promise<[{ data: PQList[]; pageCount: number }, Project[]]>
}

export function PqListsTable({ promises }: PqListsTableProps) {
  const router = useRouter()
  const [rowAction, setRowAction] = React.useState<DataTableRowAction<PQList> | null>(null)
  const [createDialogOpen, setCreateDialogOpen] = React.useState(false)
  const [copyDialogOpen, setCopyDialogOpen] = React.useState(false)
  const [editValidToSheetOpen, setEditValidToSheetOpen] = React.useState(false)
  const [selectedPqList, setSelectedPqList] = React.useState<PQList | null>(null)
  const [isPending, startTransition] = React.useTransition()

  const [{ data, pageCount }, projects] = React.use(promises)
  // const activePqLists = data.filter((item) => !item.isDeleted)

  const columns = React.useMemo(() => createPQListsColumns({ setRowAction }), [setRowAction])

  const { table } = useDataTable({
    data,
    columns,
    pageCount,
    enablePinning: true,
    enableAdvancedFilter: false,
    initialState: {
      sorting: [{ id: "createdAt", desc: true }],
      columnPinning: { right: ["actions"] },
    },
    getRowId: (row) => String(row.id),
    shallow: false,
    clearOnDefault: true,
  })

  const handleCreate = async (formData: {
    name: string
    type: "GENERAL" | "PROJECT" | "NON_INSPECTION"
    projectId?: number | null
    validTo?: Date | null
  }) => {
    startTransition(async () => {
      const result = await createPQListAction(formData)
      if (result.success) {
        toast.success("PQ 목록이 생성되었습니다")
        setCreateDialogOpen(false)
        router.refresh()
      } else {
        toast.error(result.error || "PQ 목록 생성 실패")
      }
    })
  }

  const handleToggleActive = async (ids: number[], newIsDeleted: boolean) => {
    startTransition(async () => {
      const result = await togglePQListsAction(ids, newIsDeleted)
      if (result.success) {
        toast.success(newIsDeleted ? "PQ 목록이 비활성화되었습니다" : "PQ 목록이 활성화되었습니다")
        router.refresh()
      } else {
        toast.error(result.error || "PQ 목록 상태 변경 실패")
      }
    })
  }

  const handleDelete = async (ids: number[]) => {
    startTransition(async () => {
      const result = await deletePQListsAction(ids)
      if (result.success) {
        toast.success("PQ 목록이 삭제되었습니다")
        router.refresh()
      } else {
        toast.error("PQ 목록 삭제 실패")
      }
    })
  }

  const handleCopy = async (copyData: {
    sourcePqListId: number
    targetProjectId: number
    newName?: string
    validTo?: Date | null
  }) => {
    startTransition(async () => {
      const result = await copyPQListAction(copyData)
      if (result.success) {
        toast.success("PQ 목록이 복사되었습니다")
        setCopyDialogOpen(false)
        router.refresh()
      } else {
        toast.error("PQ 목록 복사 실패")
      }
    })
  }

  const handleUpdateValidTo = React.useCallback(async (pqListId: number, newValidTo: Date | null) => {
    startTransition(async () => {
      try {
        const result = await updatePqValidToAction({ pqListId, validTo: newValidTo })
        if (result.success) {
          toast.success(result.message || "유효일이 성공적으로 수정되었습니다")
          setEditValidToSheetOpen(false)
          setSelectedPqList(null)
          router.refresh()
        } else {
          toast.error(`유효일 수정 실패: ${result.error}`)
        }
      } catch (error) {
        console.error("유효일 수정 실패:", error)
        toast.error("유효일 수정 실패")
      }
    })
  }, [])

  React.useEffect(() => {
    if (!rowAction) return
    const pqList = rowAction.row.original
    switch (rowAction.type) {
      case "view":
        router.push(`/evcp/pq-criteria/${pqList.id}`)
        break
      case "delete":
        handleDelete([pqList.id])
        break
      case "editValidTo":
        setSelectedPqList(pqList)
        setEditValidToSheetOpen(true)
        break
    }
    setRowAction(null)
  }, [rowAction])

  return (
    <>
      <DataTable table={table}>
        <DataTableAdvancedToolbar
          table={table}
          filterFields={[]}
          shallow={false}
        >
          <PQListsToolbarActions
            table={table}
            onAddClick={() => setCreateDialogOpen(true)}
            onCopyClick={() => setCopyDialogOpen(true)}
            onToggleActive={(rows, newIsDeleted) =>
              handleToggleActive(rows.map((r) => r.id), newIsDeleted)
            }
          />
        </DataTableAdvancedToolbar>
      </DataTable>

      <AddPqDialog
        open={createDialogOpen}
        onOpenChange={setCreateDialogOpen}
        onSubmit={handleCreate}
        isLoading={isPending}
      />

      <CopyPqDialog
        open={copyDialogOpen}
        onOpenChange={setCopyDialogOpen}
        pqLists={data}
        projects={projects}
        onCopy={handleCopy}
        isLoading={isPending}
      />

      <EditValidToSheet
        pqList={selectedPqList}
        open={editValidToSheetOpen}
        onOpenChange={setEditValidToSheetOpen}
        onUpdate={handleUpdateValidTo}
      />
    </>
  )
}
