"use client";

import { useEffect, useMemo, useState } from "react";
import { Plus } from "lucide-react";
import { Button } from "@/components/ui/button";
import { PageHeader } from "@/components/common/PageHeader";
import { cn } from "@/lib/utils";

type DemoEmployeeRow = Record<string, unknown> & {
  id: string;
  name: string;
  department: string;
  role: string;
  email: string;
  status: string;
  joinedAt: string;
};

const MOCK_ROWS: DemoEmployeeRow[] = [
  { id: "1", name: "张伟", department: "育种部", role: "高级育种师", email: "zhangwei@example.com", status: "Active", joinedAt: "2022-03-15" },
  { id: "2", name: "李娜", department: "表型组", role: "数据采集员", email: "lina@example.com", status: "Active", joinedAt: "2023-06-01" },
  { id: "3", name: "王强", department: "基因型实验室", role: "实验主管", email: "wangqiang@example.com", status: "Active", joinedAt: "2021-11-20" },
  { id: "4", name: "赵敏", department: "项目管理", role: "Trial 协调员", email: "zhaomin@example.com", status: "Draft", joinedAt: "2024-01-08" },
  { id: "5", name: "陈晨", department: "育种部", role: "助理育种师", email: "chenchen@example.com", status: "Active", joinedAt: "2024-05-12" },
  { id: "6", name: "刘洋", department: "IT 支持", role: "系统管理员", email: "liuyang@example.com", status: "Inactive", joinedAt: "2020-09-03" },
  { id: "7", name: "孙悦", department: "表型组", role: "图像分析员", email: "sunyue@example.com", status: "Active", joinedAt: "2023-12-18" },
  { id: "8", name: "周杰", department: "基因型实验室", role: "测序技术员", email: "zhoujie@example.com", status: "Active", joinedAt: "2022-08-25" },
  { id: "9", name: "吴婷", department: "项目管理", role: "Program 负责人", email: "wuting@example.com", status: "Active", joinedAt: "2019-04-10" },
  { id: "10", name: "郑磊", department: "育种部", role: "田间管理员", email: "zhenglei@example.com", status: "Draft", joinedAt: "2025-02-01" },
  { id: "11", name: "冯雪", department: "表型组", role: "质控专员", email: "fengxue@example.com", status: "Active", joinedAt: "2023-03-22" },
  { id: "12", name: "蒋波", department: "IT 支持", role: "数据工程师", email: "jiangbo@example.com", status: "Active", joinedAt: "2021-07-14" },
];

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",
};

function filterRows(rows: DemoEmployeeRow[], filters: Record<string, string>) {
  const keyword = filters.keyword?.trim().toLowerCase() ?? "";
  const department = filters.department ?? "";
  const status = filters.status ?? "";

  return rows.filter((row) => {
    if (department && row.department !== department) return false;
    if (status && row.status !== status) return false;
    if (!keyword) return true;

    return [row.name, row.department, row.role, row.email, row.status].some((value) =>
      String(value).toLowerCase().includes(keyword)
    );
  });
}

export default function PageHeaderDemoPage() {
  const [appliedFilters, setAppliedFilters] = useState<Record<string, string>>({});
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);

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

  const filteredRows = useMemo(
    () => filterRows(MOCK_ROWS, appliedFilters),
    [appliedFilters]
  );

  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);
  }, [appliedFilters, pageSize]);

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

  return (
    <PageHeader
      title="PageHeader 页面壳"
      description="集成标题区、配置化查询表单、数据表格与分页的通用页面组件演示，数据为本地 mock。"
      actions={
        <Button className="gap-2">
          <Plus className="h-4 w-4" />
          新增员工
        </Button>
      }
      searchFields={[
        {
          key: "keyword",
          label: "关键词",
          placeholder: "姓名、邮箱、岗位",
        },
        {
          key: "department",
          label: "部门",
          type: "select",
          defaultValue: "all",
          placeholder: "全部部门",
          options: [
            { value: "all", label: "全部部门" },
            { value: "育种部", label: "育种部" },
            { value: "表型组", label: "表型组" },
            { value: "基因型实验室", label: "基因型实验室" },
            { value: "项目管理", label: "项目管理" },
            { value: "IT 支持", label: "IT 支持" },
          ],
        },
        {
          key: "status",
          label: "状态",
          type: "select",
          defaultValue: "all",
          placeholder: "全部状态",
          options: [
            { value: "all", label: "全部状态" },
            { value: "Active", label: "Active" },
            { value: "Draft", label: "Draft" },
            { value: "Inactive", label: "Inactive" },
          ],
        },
      ]}
      columns={[
        { key: "name", label: "姓名", minWidth: "120px" },
        { key: "department", label: "部门", minWidth: "140px" },
        { key: "role", label: "岗位", minWidth: "160px" },
        { key: "email", label: "邮箱", minWidth: "200px" },
        {
          key: "status",
          label: "状态",
          minWidth: "100px",
          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: "joinedAt", label: "入职日期", minWidth: "120px" },
      ]}
      data={pagedRows}
      loading={loading}
      emptyText="暂无匹配数据，请调整查询条件"
      rowKey="id"
      pagination={{
        page,
        size: pageSize,
        total: filteredRows.length,
        totalPages,
      }}
      sizeOptions={[5, 10, 20]}
      onSearch={(filters) => {
        const nextFilters = { ...filters };
        if (nextFilters.department === "all") nextFilters.department = "";
        if (nextFilters.status === "all") nextFilters.status = "";
        setAppliedFilters(nextFilters);
      }}
      onReset={() => setAppliedFilters({})}
      onPageChange={setPage}
      onSizeChange={(size) => {
        setPageSize(size);
        setPage(1);
      }}
    />
  );
}
