"use client";

import { useEffect, useMemo, useState } from "react";
import { Layers, Pencil, Search } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { TableQueryPanel } from "@/components/common/TableQueryPanel";
import { cn } from "@/lib/utils";

type DemoCropRow = {
  id: string;
  crop_name: string;
  category: string;
  region: string;
  status: string;
  updatedAt: string;
};

const MOCK_ROWS: DemoCropRow[] = [
  {
    id: "c99207c170904d73a888b1fad25f8517",
    crop_name: "Maize",
    category: "Grain",
    region: "North China Plain",
    status: "Active",
    updatedAt: "2026-03-01",
  },
  {
    id: "4e31c03bdb204bb680dbc82216975ff3",
    crop_name: "Rice",
    category: "Grain",
    region: "Yangtze River Basin",
    status: "Active",
    updatedAt: "2026-02-18",
  },
  {
    id: "8b2d1f4a6c3e4d5f9a0b1c2d3e4f5a6b",
    crop_name: "Wheat",
    category: "Grain",
    region: "Huang-Huai Plain",
    status: "Active",
    updatedAt: "2026-02-10",
  },
  {
    id: "1a2b3c4d5e6f708192a3b4c5d6e7f809",
    crop_name: "Soybean",
    category: "Oilseed",
    region: "Northeast China",
    status: "Draft",
    updatedAt: "2026-01-22",
  },
  {
    id: "9f8e7d6c5b4a39281726354453627180",
    crop_name: "Cotton",
    category: "Fiber",
    region: "Xinjiang Production Area",
    status: "Active",
    updatedAt: "2026-01-15",
  },
  {
    id: "aa11bb22cc33dd44ee55ff6677889900",
    crop_name: "Potato",
    category: "Tuber",
    region: "Inner Mongolia Plateau",
    status: "Inactive",
    updatedAt: "2025-12-30",
  },
  {
    id: "bb22cc33dd44ee55ff6677889900aa11",
    crop_name: "Tomato",
    category: "Vegetable",
    region: "Shandong Peninsula",
    status: "Active",
    updatedAt: "2025-12-12",
  },
  {
    id: "cc33dd44ee55ff6677889900aa11bb22",
    crop_name: "Sorghum",
    category: "Grain",
    region: "Loess Plateau",
    status: "Active",
    updatedAt: "2025-11-08",
  },
  {
    id: "dd44ee55ff6677889900aa11bb22cc33",
    crop_name: "Rapeseed",
    category: "Oilseed",
    region: "Middle Yangtze Region",
    status: "Draft",
    updatedAt: "2025-10-21",
  },
  {
    id: "ee55ff6677889900aa11bb22cc33dd44",
    crop_name: "Barley",
    category: "Grain",
    region: "Qinghai-Tibet Fringe",
    status: "Active",
    updatedAt: "2025-09-03",
  },
  {
    id: "ff6677889900aa11bb22cc33dd44ee55",
    crop_name: "Peanut",
    category: "Oilseed",
    region: "Henan Province",
    status: "Active",
    updatedAt: "2025-08-17",
  },
  {
    id: "6677889900aa11bb22cc33dd44ee55ff",
    crop_name: "Sugar Beet",
    category: "Industrial",
    region: "Heilongjiang Farmland",
    status: "Inactive",
    updatedAt: "2025-07-29",
  },
];

const STATUS_CLASS: Record<string, string> = {
  Active: "bg-green-50 text-green-700 dark:bg-green-400/10 dark:text-green-200",
  Draft: "bg-amber-50 text-amber-700 dark:bg-amber-400/10 dark:text-amber-200",
  Inactive: "bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-300",
};

export default function GeneralFormDemoPage() {
  const [search, setSearch] = useState("");
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  useEffect(() => {
    const timer = window.setTimeout(() => setLoading(false), 600);
    return () => window.clearTimeout(timer);
  }, []);

  const filteredRows = useMemo(() => {
    const keyword = search.trim().toLowerCase();
    if (!keyword) return MOCK_ROWS;

    return MOCK_ROWS.filter((row) =>
      [row.crop_name, row.category, row.region, row.status, row.updatedAt].some((value) =>
        value.toLowerCase().includes(keyword)
      )
    );
  }, [search]);

  const totalPages = Math.max(1, Math.ceil(filteredRows.length / pageSize));
  const pagedRows = useMemo(() => {
    const start = (page - 1) * pageSize;
    return filteredRows.slice(start, start + pageSize);
  }, [filteredRows, page, pageSize]);

  useEffect(() => {
    setPage(1);
  }, [search, pageSize]);

  useEffect(() => {
    if (page > totalPages) {
      setPage(totalPages);
    }
  }, [page, totalPages]);

  return (
    <TableQueryPanel
      title="通用表格 TableQueryPanel"
      description="组件演示页，样式对齐 Crop 作物字典页，数据为本地 mock"
      icon={Layers}
      iconBg="bg-gradient-to-br from-violet-500 to-purple-600"
      addLabel="新增作物"
      onAdd={() => window.alert("演示：点击新增")}
      stats={[
        {
          label: "Mock 数据",
          value: MOCK_ROWS.length,
          className:
            "bg-violet-50 text-violet-700 dark:bg-violet-400/10 dark:text-violet-200",
        },
        {
          label: "variant",
          value: "brapi",
          className:
            "bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-300",
        },
      ]}
      variant="brapi"
      hideDefaultActions
      queryForm={
        <div className="relative">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
          <Input
            placeholder="搜索..."
            value={search}
            onChange={(event) => setSearch(event.target.value)}
            className="bg-white pl-9 dark:bg-slate-950"
          />
        </div>
      }
      columns={[
        { key: "crop_name", label: "作物名称" },
        { key: "category", label: "类别" },
        { key: "region", label: "主产区" },
        {
          key: "status",
          label: "状态",
          render: (value) => (
            <span
              className={cn(
                "inline-flex rounded-full px-2.5 py-0.5 text-xs font-medium",
                STATUS_CLASS[String(value)] ?? STATUS_CLASS.Draft
              )}
            >
              {String(value)}
            </span>
          ),
        },
        { key: "updatedAt", label: "更新时间" },
        {
          key: "__actions",
          label: "操作",
          wrap: false,
          headerClassName: "w-24 pr-4 text-right",
          className: "pr-4 text-right",
          render: () => (
            <div className="flex justify-end">
              <Button
                size="icon"
                variant="ghost"
                className="h-7 w-7 text-slate-500 hover:text-slate-700"
                type="button"
              >
                <Pencil className="h-3.5 w-3.5" />
              </Button>
            </div>
          ),
        },
      ]}
      data={pagedRows}
      loading={loading}
      emptyText="暂无数据，请调整搜索条件"
      rowKey="id"
      showIndex
      pagination={{
        page,
        pageSize,
        total: filteredRows.length,
        totalPages,
      }}
      pageSizeOptions={[5, 10, 20]}
      onPageChange={setPage}
      onPageSizeChange={(size) => {
        setPageSize(size);
        setPage(1);
      }}
    />
  );
}
