import React, { useCallback, useEffect, useState } from 'react';
import dayjs from 'dayjs';
import { Button, Table, Modal, Form, Input } from 'antd';
import type { FormProps } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { Plus, Trash2 } from 'lucide-react';
import { toast } from 'sonner';
import { useTranslation } from 'react-i18next';
import { materialStandardApi, PropertyVO } from '../../../api/material/standard';
import { pickRecords, pickTotal } from '../materialListUtils';
import {
  MaterialPageRoot,
  MaterialToolbarCard,
  MaterialTableCard,
  MaterialPaginationBar,
  MaterialEditButton,
  MaterialDeleteButton,
  materialConfirmDelete,
  getMaterialFormModalProps,
} from '../MaterialPageLayout';
import { setMaterialPvContext, switchMaterialSubMenu } from '../materialPvNav';

/** 物资规格种类新增/编辑弹窗：与业务原型一致（两字段、标签右对齐） */
const standardPropFormLayout: FormProps = {
  layout: 'horizontal',
  colon: false,
  labelAlign: 'right',
  labelCol: { flex: '0 0 132px' },
  wrapperCol: { flex: '1 1 auto' },
};

function formatDateTimeCell(v: unknown): string {
  if (v === undefined || v === null || v === '') return '—';
  const n = typeof v === 'number' ? v : /^\d+$/.test(String(v).trim()) ? Number(String(v).trim()) : NaN;
  const d = Number.isFinite(n) && n > 1e12 ? dayjs(n) : dayjs(v as string);
  return d.isValid() ? d.format('YYYY-MM-DD HH:mm:ss') : '—';
}

export default function MaterialStandardPage() {
  const { t } = useTranslation();
  const [loading, setLoading] = useState(false);
  const [list, setList] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [pageNo, setPageNo] = useState(1);
  const [pageSize] = useState(10);
  const [draftName, setDraftName] = useState('');
  const [appliedName, setAppliedName] = useState('');
  const [modalOpen, setModalOpen] = useState(false);
  const [form] = Form.useForm();
  const [editing, setEditing] = useState<any | null>(null);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  const fetchList = useCallback(async () => {
    setLoading(true);
    try {
      const res = await materialStandardApi.PropertyPage({
        pageNo,
        pageSize,
        ...(appliedName.trim() ? { propertyName: appliedName.trim() } : {}),
      });
      setList(pickRecords(res));
      setTotal(pickTotal(res));
    } catch (e: any) {
      toast.error(e?.message || t('common.operationFailed'));
    } finally {
      setLoading(false);
    }
  }, [pageNo, pageSize, appliedName, t]);

  useEffect(() => {
    fetchList();
  }, [fetchList]);

  const openPropForm = (row?: any) => {
    setEditing(row || null);
    form.resetFields();
    if (row) {
      form.setFieldsValue({
        propertyName: row.propertyName,
        remark: row.remark,
      });
    }
    setModalOpen(true);
  };

  const submitProp = async () => {
    const v = await form.validateFields();
    setLoading(true);
    try {
      if (editing) {
        await materialStandardApi.updateProperty({
          ...editing,
          ...v,
          propertyId: editing.propertyId ?? editing.id,
        } as PropertyVO);
        toast.success(t('common.updateSuccess'));
      } else {
        await materialStandardApi.addProperty({
          propertyName: v.propertyName,
          propertyCode: v.propertyName,
          propertyType: 'text',
          propertyUnit: undefined,
          status: 0,
          remark: v.remark,
        } as PropertyVO);
        toast.success(t('common.addSuccess'));
      }
      setModalOpen(false);
      fetchList();
    } catch (e: any) {
      if (!e?.errorFields) toast.error(e?.message || t('common.operationFailed'));
    } finally {
      setLoading(false);
    }
  };

  const deleteProp = (row: any) => {
    const id = row.propertyId ?? row.id;
    materialConfirmDelete(t, {
      count: 1,
      onOk: async () => {
        await materialStandardApi.deleteProperty(id);
        toast.success(t('common.deleteSuccess'));
        setSelectedRowKeys((prev) => prev.filter((k) => String(k) !== String(id)));
        fetchList();
      },
    });
  };

  const batchDelete = () => {
    if (selectedRowKeys.length === 0) {
      toast.error(t('common.pleaseSelectDataToDelete'));
      return;
    }
    const ids = selectedRowKeys
      .map((k) => Number(k))
      .filter((n) => Number.isFinite(n) && !Number.isNaN(n));
    if (ids.length === 0) {
      toast.error(t('common.pleaseSelectDataToDelete'));
      return;
    }
    materialConfirmDelete(t, {
      count: ids.length,
      onOk: async () => {
        await materialStandardApi.deleteProperty(ids.join(','));
        toast.success(t('common.deleteSuccess'));
        setSelectedRowKeys([]);
        fetchList();
      },
    });
  };

  const goPropertyValuesPage = (row: any) => {
    const pid = Number(row.propertyId ?? row.id);
    if (!Number.isFinite(pid)) {
      toast.error('无效的种类编号');
      return;
    }
    setMaterialPvContext({
      propertyId: pid,
      propertyName: String(row.propertyName ?? ''),
    });
    switchMaterialSubMenu('materialManagement', 'materialStandardPropertyValues');
  };

  const columns: ColumnsType<any> = [
    { title: '编号', dataIndex: 'id', width: 90, align: 'center' },
    { title: '物资规格种类', dataIndex: 'propertyName', align: 'center' },
    { title: '备注', dataIndex: 'remark', ellipsis: true, align: 'center' },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 170,
      align: 'center',
      render: (v) => formatDateTimeCell(v),
    },
    {
      title: t('table.operation'),
      width: 260,
      align: 'center',
      fixed: 'right',
      render: (_, row) => (
        <div className="flex items-center gap-2 justify-center flex-wrap">
          <MaterialEditButton label={t('common.edit')} onClick={() => openPropForm(row)} />
          <MaterialEditButton label="规格设置" onClick={() => goPropertyValuesPage(row)} />
          <MaterialDeleteButton label={t('common.delete')} onClick={() => deleteProp(row)} />
        </div>
      ),
    },
  ];

  return (
    <MaterialPageRoot>
      <MaterialToolbarCard
        filterRow={
          <div className="flex items-center gap-2">
            <label className="text-sm font-medium text-gray-700 whitespace-nowrap">物资规格种类：</label>
            <Input
              allowClear
              placeholder="请输入物资规格种类"
              className="w-[180px]"
              value={draftName}
              onChange={(e) => setDraftName(e.target.value)}
              onPressEnter={() => setAppliedName(draftName)}
            />
          </div>
        }
        onSearch={() => {
          setAppliedName(draftName);
          setPageNo(1);
          setSelectedRowKeys([]);
        }}
        onReset={() => {
          setDraftName('');
          setAppliedName('');
          setPageNo(1);
          setSelectedRowKeys([]);
        }}
        toolbarRight={
          <>
            <Button type="primary" icon={<Plus />} onClick={() => openPropForm()}>
              {t('common.addNew')}
            </Button>
            <Button
              danger
              icon={<Trash2 className="h-4 w-4" />}
              disabled={selectedRowKeys.length === 0}
              onClick={batchDelete}
            >
              {t('common.batchDelete')}
            </Button>
          </>
        }
      />
      <MaterialTableCard>
        <Table
          rowKey={(r) => r.propertyId ?? r.id}
          loading={loading}
          columns={columns}
          dataSource={list}
          pagination={false}
          scroll={{ x: 'max-content' }}
          rowSelection={{
            selectedRowKeys,
            onChange: setSelectedRowKeys,
            preserveSelectedRowKeys: true,
            getCheckboxProps: (record) => ({ name: record.propertyName }),
          }}
          rowClassName={(_, index) => (index !== undefined && index % 2 === 1 ? 'isolation-work-list-row-alt' : '')}
        />
      </MaterialTableCard>
      <MaterialPaginationBar
        total={total}
        current={pageNo}
        pageSize={pageSize}
        onPageChange={setPageNo}
        loading={loading}
        listLength={list.length}
      />

      <Modal
        title={editing ? '修改' : '新增'}
        open={modalOpen}
        onOk={submitProp}
        onCancel={() => setModalOpen(false)}
        confirmLoading={loading}
        {...getMaterialFormModalProps(t, 520)}
        styles={{ body: { paddingTop: 8 } }}
      >
        <Form form={form} {...standardPropFormLayout}>
          <Form.Item
            name="propertyName"
            label="物资规格种类"
            rules={[{ required: true, message: '请输入物资规格种类' }]}
          >
            <Input allowClear placeholder="请输入物资规格种类" />
          </Form.Item>
          <Form.Item name="remark" label="备注">
            <Input.TextArea allowClear rows={4} placeholder="请输入内容" />
          </Form.Item>
        </Form>
      </Modal>
    </MaterialPageRoot>
  );
}
