"use client"

import { format } from "date-fns"
import { EyeIcon, EyeOffIcon, PlusIcon, TrashIcon } from "lucide-react"
import { Suspense, useCallback, useEffect, useMemo, useState } from "react"
import { getAllProduct, getPageProductSku } from "@/actions/product"
import { DataTable, useDataTable } from "@/components/data-table"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/components/ui/tooltip"
import { cn } from "@/lib/utils"
import type { Product } from "@/models/product"

export default function ProductPage() {
  const [selected, setSelected] = useState<number | undefined>(undefined)

  return (
    <div className="size-full flex gap-6 items-stretch">
      <Products selected={selected} onSelect={setSelected} />
      <ProductSkus selected={selected} />
    </div>
  )
}

function Products(props: {
  selected?: number
  onSelect?: (id: number) => void
}) {
  const [list, setList] = useState<Product[]>([])

  const refresh = useCallback(async () => {
    const resp = await getAllProduct()
    if (resp.success) {
      setList(resp.data)
      console.log(resp.data)
    }
  }, [])

  const selected = useMemo(() => {
    return list.find(item => item.id === props.selected)
  }, [list, props.selected])

  useEffect(() => {
    refresh()
  }, [refresh])

  return (
    <section className="flex-none basis-64 bg-background rounded-lg">
      <header className="pl-3 pr-1 h-10 border-b flex items-center justify-between">
        <h3 className="text-sm">产品列表</h3>
        <div>
          <Tooltip>
            <TooltipTrigger asChild>
              <Button variant="ghost" size="icon" className="size-8">
                <PlusIcon />
              </Button>
            </TooltipTrigger>
            <TooltipContent>
              <p>新建产品</p>
            </TooltipContent>
          </Tooltip>

          {!!selected && (
            <Tooltip>
              <TooltipTrigger asChild>
                <Button variant="ghost" size="icon" className="size-8">
                  {selected.status ? <EyeOffIcon /> : <EyeIcon />}
                </Button>
              </TooltipTrigger>
              <TooltipContent>
                <p>{selected.status ? "禁用产品" : "启用产品"}</p>
              </TooltipContent>
            </Tooltip>
          )}

          <Tooltip>
            <TooltipTrigger asChild>
              <Button variant="ghost" size="icon" className="size-8">
                <TrashIcon />
              </Button>
            </TooltipTrigger>
            <TooltipContent>
              <p>删除产品</p>
            </TooltipContent>
          </Tooltip>
        </div>
      </header>
      <ul>
        {list.map(item => (
          <li key={item.id} className="p-1">
            <Button
              variant="ghost"
              className={cn(
                "size-full box-border p-2 rounded-md flex justify-between items-center select-none",
                selected?.id === item.id && "bg-primary/20",
              )}
              onClick={() => props.onSelect?.(item.id)}
            >
              <div>
                <p>{item.name}</p>
                <p className="text-sm text-gray-500">{item.description}</p>
              </div>
              <Badge className="bg-green-600/60">已启用</Badge>
            </Button>
          </li>
        ))}
      </ul>
    </section>
  )
}

function ProductSkus(props: { selected?: number }) {
  const action = useCallback(
    (page: number, size: number) => {
      return getPageProductSku({ page, size, product_id: props.selected })
    },
    [props.selected],
  )

  const table = useDataTable(action)

  return (
    <div className="flex-auto overflow-hidden flex flex-col items-stretch gap-3">
      <div>
        <Button>新建套餐</Button>
      </div>
      <Suspense>
        <DataTable
          classNames={{
            root: "overflow-auto",
          }}
          {...table}
          columns={[
            { header: "套餐编码", accessorKey: "code" },
            { header: "套餐名称", accessorKey: "name" },
            { header: "单价", accessorKey: "price" },
            { header: "折扣", accessorKey: "discount" },
            {
              header: "最终价格",
              accessorFn: row => Number(row.price) * row.discount,
            },
            {
              header: "创建时间",
              accessorFn: row => format(row.created_at, "yyyy-MM-dd HH:mm"),
            },
            {
              header: "更新时间",
              accessorFn: row => format(row.updated_at, "yyyy-MM-dd HH:mm"),
            },
            { header: "操作", cell: () => <div></div> },
          ]}
        />
      </Suspense>
    </div>
  )
}
