import { Button, Form, Tag, Table, Typography, Select } from "antd";
import SearchForm from "@cqsjjb/jjb-react-admin-component/SearchForm";
import ControlWrapper from "@cqsjjb/jjb-react-admin-component/ControlWrapper";
import TableAction from "@cqsjjb/jjb-react-admin-component/TableAction";
import { CHONGQING_DISTRICTS } from "~/enumerate/enterpriseOptions";
import {
  FILING_FORM_MODE,
  getFilingStatusOptions,
  isFiledManageEditable,
  isQualFilingEditable,
  QUAL_FILING_STATUS_COLOR,
} from "~/enumerate/qualFilingOptions";
import { CHANGE_COUNT_STYLE, getChangeCount } from "~/utils/enterpriseForm";
import { goFilingForm } from "./filingPaths";

export default function FilingListTable({
  dataSource,
  total,
  loading,
  searchForm,
  onSearch,
  onPageChange,
  scrollY,
  mode,
  showChangeCount = false,
  onChangeCountClick,
  onCreate,
  createLabel,
  listTitle,
  listDesc,
  PageLayout,
  onDelete,
  extraActions,
}) {
  const statusOptions = getFilingStatusOptions(mode);

  const canEditRow = (record) => {
    if (mode === FILING_FORM_MODE.FILED) {
      return isFiledManageEditable(record.filingStatusCode, mode);
    }
    return isQualFilingEditable(record.filingStatusCode);
  };

  const columns = [
    { title: "备案属地", dataIndex: "filingTerritoryName", width: 120, ellipsis: true },
    { title: "备案单位", dataIndex: "filingUnitName", ellipsis: true },
    { title: "备案编号", dataIndex: "filingNo", width: 200, render: (val, record) => val || record.id || "-" },
    { title: "安全评价业务范围", dataIndex: "businessScope", ellipsis: true },
  ];

  if (showChangeCount) {
    columns.push({
      title: "变更次数",
      dataIndex: "changeCount",
      width: 90,
      render: (_, record) => {
        const count = getChangeCount(record);
        const style = count > 0 ? CHANGE_COUNT_STYLE.active : CHANGE_COUNT_STYLE.zero;
        if (count <= 0) {
          return <span style={style}>{count}</span>;
        }
        return (
          <Typography.Link
            style={style}
            onClick={() => onChangeCountClick?.(record)}
          >
            {count}
          </Typography.Link>
        );
      },
    });
  }

  columns.push({
    title: "备案状态",
    dataIndex: "filingStatusName",
    width: 110,
    render: (_, record) => (
      <Tag color={QUAL_FILING_STATUS_COLOR[record.filingStatusCode] || "default"}>
        {record.filingStatusName || "-"}
      </Tag>
    ),
  });

  columns.push({
    title: "操作",
    width: 180,
    fixed: "right",
    render: (_, record) => (
      <TableAction>
        <Button
          type="link"
          size="small"
          onClick={() => goFilingForm({ mode, id: record.id, readOnly: true })}
        >
          查看
        </Button>
        {extraActions?.(record)}
        {canEditRow(record) && mode !== FILING_FORM_MODE.CHANGE && (
          <Button
            type="link"
            size="small"
            onClick={() => goFilingForm({ mode, id: record.id })}
          >
            修改
          </Button>
        )}
        {mode === FILING_FORM_MODE.APPLICATION && isQualFilingEditable(record.filingStatusCode) && onDelete && (
          <Button type="link" size="small" danger onClick={() => onDelete(record)}>删除</Button>
        )}
      </TableAction>
    ),
  });

  return (
    <PageLayout
      title={
        listDesc ? (
          <div>
            <span>{listTitle}</span>
            <div className="pageLayout-extra">{listDesc}</div>
          </div>
        ) : (
          listTitle
        )
      }
      extra={onCreate && (
        <Button type="primary" onClick={onCreate}>{createLabel}</Button>
      )}
    >
      <SearchForm
        style={{ marginBottom: 24 }}
        form={searchForm}
        loading={loading}
        formLine={[
          <Form.Item key="filingUnitName" name="filingUnitName">
            <ControlWrapper.Input label="备案单位" placeholder="关键字搜索" allowClear />
          </Form.Item>,
          <Form.Item key="filingTerritoryName" name="filingTerritoryName">
            <ControlWrapper.Select
              label="备案属地"
              placeholder="请输入"
              allowClear
              style={{ width: "100%" }}
            >
              {CHONGQING_DISTRICTS.map((d) => (
                <Select.Option key={d.value} value={d.value}>{d.label}</Select.Option>
              ))}
            </ControlWrapper.Select>
          </Form.Item>,
          <Form.Item key="filingNo" name="filingNo">
            <ControlWrapper.Input label="备案编号" placeholder="关键字搜索" allowClear />
          </Form.Item>,
          <Form.Item key="filingStatus" name="filingStatus">
            <ControlWrapper.Select
              label="备案状态"
              placeholder="全部"
              allowClear={false}
              showSearch={false}
              style={{ width: "100%" }}
            >
              {statusOptions.map((opt) => (
                <Select.Option key={opt.value} value={opt.value}>{opt.label}</Select.Option>
              ))}
            </ControlWrapper.Select>
          </Form.Item>,
        ]}
        onFinish={(values) => onSearch(values)}
        onReset={(values) => onSearch(values)}
      />
      <Table
        rowKey="id"
        columns={columns}
        dataSource={dataSource}
        loading={loading}
        scroll={{ y: scrollY }}
        pagination={{
          total,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (t) => `共 ${t} 条`,
        }}
        onChange={(pagination) => {
          if (onPageChange) onPageChange(pagination);
        }}
      />
    </PageLayout>
  );
}
