import React, { useCallback, useEffect, useState } from 'react';
import dayjs from 'dayjs';
import { Button, Input, Space, Table, Modal, Form } from 'antd';
import type { FormProps } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { Plus, Trash2, ArrowLeft, Search, RefreshCw } from 'lucide-react';
import { toast } from 'sonner';
import { useTranslation } from 'react-i18next';
import { materialPropertyValueApi, PropertyValueVO } from '../../../api/material/propertyValue';
import { pickRecords, pickTotal } from '../materialListUtils';
import {
  MaterialPageRoot,
  MaterialToolbarCard,
  MaterialTableCard,
  MaterialPaginationBar,
  materialConfirmDelete,
  getMaterialFormModalProps,
} from '../MaterialPageLayout';
import { readMaterialPvContext, switchMaterialSubMenu } from '../materialPvNav';

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') : '—';
}

/** 与老系统「新增/修改」弹窗一致：标签右对齐、无冒号 */
const valModalFormLayout: FormProps = {
  layout: 'horizontal',
  colon: false,
  labelAlign: 'right',
  labelCol: { flex: '0 0 160px' },
  wrapperCol: { flex: '1 1 auto' },
};

export default function MaterialStandardPropertyValuesPage() {
  const { t } = useTranslation();
  const [ctx] = useState(() => readMaterialPvContext());
  const [loading, setLoading] = useState(false);
  const [list, setList] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [pageNo, setPageNo] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [draftSpec, setDraftSpec] = useState('');
  const [appliedSpec, setAppliedSpec] = useState('');
  const [refreshTick, setRefreshTick] = useState(0);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  const [valModalOpen, setValModalOpen] = useState(false);
  const [valEditing, setValEditing] = useState<any | null>(null);
  const [valForm] = Form.useForm();
  const [valSaveLoading, setValSaveLoading] = useState(false);

  const fetchList = useCallback(async () => {
    const c = readMaterialPvContext();
    if (!c) {
      setList([]);
      setTotal(0);
      return;
    }
    setLoading(true);
    try {
      const res = await materialPropertyValueApi.PropertyValuePage({
        pageNo,
        pageSize,
        propertyId: c.propertyId,
        propertyName: c.propertyName ?? '',
        valueName: appliedSpec.trim(),
      });
      setList(pickRecords(res));
      setTotal(pickTotal(res));
    } catch (e: any) {
      toast.error(e?.message || t('common.operationFailed'));
      setList([]);
      setTotal(0);
    } finally {
      setLoading(false);
    }
  }, [pageNo, pageSize, appliedSpec, t, refreshTick]);

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

  const handleSearch = () => {
    setAppliedSpec(draftSpec);
    setPageNo(1);
    setSelectedRowKeys([]);
    setRefreshTick((n) => n + 1);
  };

  const handleReset = () => {
    setDraftSpec('');
    setAppliedSpec('');
    setPageNo(1);
    setSelectedRowKeys([]);
    setRefreshTick((n) => n + 1);
  };

  const goBackToStandard = () => {
    switchMaterialSubMenu('materialManagement', 'materialStandard');
  };

  const openValModalAdd = () => {
    const c = readMaterialPvContext();
    if (!c) {
      toast.error('缺少规格种类信息，请从物资规格种类进入');
      return;
    }
    setValEditing(null);
    valForm.resetFields();
    valForm.setFieldsValue({ valueName: '', remark: '' });
    setValModalOpen(true);
  };

  const openValModalEdit = (row: any) => {
    const c = readMaterialPvContext();
    if (!c) {
      toast.error('缺少规格种类信息，请从物资规格种类进入');
      return;
    }
    setValEditing(row);
    valForm.resetFields();
    valForm.setFieldsValue({
      valueName: row.valueName ?? row.propertyValue ?? '',
      remark: row.remark ?? '',
    });
    setValModalOpen(true);
  };

  const closeValModal = () => {
    setValModalOpen(false);
    setValEditing(null);
    valForm.resetFields();
  };

  const submitValModal = async () => {
    const c = readMaterialPvContext();
    if (!c) {
      toast.error('缺少规格种类信息');
      return Promise.reject();
    }
    let v: { valueName?: string; remark?: string };
    try {
      v = await valForm.validateFields();
    } catch (e) {
      return Promise.reject(e);
    }
    const spec = String(v.valueName ?? '').trim();
    if (!spec) {
      toast.error('请输入物资规格');
      return Promise.reject();
    }
    setValSaveLoading(true);
    try {
      if (valEditing) {
        await materialPropertyValueApi.updatePropertyValue({
          ...valEditing,
          propertyValue: spec,
          valueName: spec,
          remark: v.remark,
          propertyId: c.propertyId,
          propertyName: c.propertyName,
        } as PropertyValueVO);
        toast.success(t('common.updateSuccess'));
      } else {
        await materialPropertyValueApi.addPropertyValue({
          propertyId: c.propertyId,
          propertyName: c.propertyName,
          propertyValue: spec,
          valueName: spec,
          status: 0,
          remark: v.remark,
        } as PropertyValueVO);
        toast.success(t('common.addSuccess'));
      }
      closeValModal();
      setRefreshTick((n) => n + 1);
    } catch (e: any) {
      toast.error(e?.message || t('common.operationFailed'));
      return Promise.reject(e);
    } finally {
      setValSaveLoading(false);
    }
  };

  const deleteOne = (row: any) => {
    const id = row.recordId ?? row.id;
    materialConfirmDelete(t, {
      count: 1,
      onOk: async () => {
        await materialPropertyValueApi.deletePropertyValue(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 () => {
        for (const id of ids) {
          await materialPropertyValueApi.deletePropertyValue(id);
        }
        toast.success(t('common.deleteSuccess'));
        setSelectedRowKeys([]);
        fetchList();
      },
    });
  };

  const displaySpec = (row: any) => row.valueName ?? row.propertyValue ?? '—';

  const columns: ColumnsType<any> = [
    { title: '编号', dataIndex: 'recordId', width: 90, align: 'center', render: (_v, row) => row.recordId ?? row.id },
    {
      title: '物资规格',
      dataIndex: 'valueName',
      align: 'center',
      render: (_v, row) => displaySpec(row),
    },
    { title: '备注', dataIndex: 'remark', ellipsis: true, align: 'center' },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 170,
      align: 'center',
      render: (v) => formatDateTimeCell(v),
    },
    {
      title: t('table.operation'),
      width: 140,
      align: 'center',
      fixed: 'right',
      render: (_, row) => (
        <div className="flex items-center justify-center gap-3">
          <button type="button" className="text-sm text-blue-600 hover:underline" onClick={() => openValModalEdit(row)}>
            {t('common.edit')}
          </button>
          <button type="button" className="text-sm text-red-600 hover:underline" onClick={() => deleteOne(row)}>
            {t('common.delete')}
          </button>
        </div>
      ),
    },
  ];

  if (!ctx) {
    return (
      <MaterialPageRoot>
        <MaterialTableCard>
          <div className="flex flex-col items-center justify-center gap-4 py-16 text-gray-600">
            <p>未找到规格种类上下文，请从「物资规格种类」点击「规格设置」进入。</p>
            <Button type="primary" className="!bg-orange-500 hover:!bg-orange-600" icon={<ArrowLeft className="h-4 w-4" />} onClick={goBackToStandard}>
              返回
            </Button>
          </div>
        </MaterialTableCard>
      </MaterialPageRoot>
    );
  }

  return (
    <MaterialPageRoot>
      <MaterialToolbarCard
        hideSearchButtons
        filterRow={
          <div className="flex flex-wrap items-center gap-2">
            <label className="text-sm font-medium text-gray-700 whitespace-nowrap">物资规格种类：</label>
            <Input
              disabled
              value={ctx.propertyName}
              className="w-[180px] !cursor-not-allowed !bg-gray-100 !text-gray-600 !opacity-100"
              title={ctx.propertyName}
            />
            <label className="text-sm font-medium text-gray-700 whitespace-nowrap">物资规格：</label>
            <Input
              allowClear
              placeholder="请输入物资规格"
              className="w-[180px]"
              value={draftSpec}
              onChange={(e) => setDraftSpec(e.target.value)}
              onPressEnter={handleSearch}
            />
            <Space className="flex-shrink-0" size="small">
              <Button type="primary" icon={<Search className="h-4 w-4" />} onClick={handleSearch}>
                {t('common.search')}
              </Button>
              <Button icon={<RefreshCw className="h-4 w-4" />} onClick={handleReset}>
                {t('common.reset')}
              </Button>
            </Space>
          </div>
        }
        toolbarRight={
          <Space wrap>
            <Button type="primary" icon={<Plus className="h-4 w-4" />} onClick={openValModalAdd}>
              {t('common.addNew')}
            </Button>
            <Button
              danger
              icon={<Trash2 className="h-4 w-4" />}
              disabled={selectedRowKeys.length === 0}
              onClick={batchDelete}
            >
              {t('common.batchDelete')}
            </Button>
            <Button
              type="default"
              className="!border-orange-500 !bg-orange-500 !text-white hover:!bg-orange-600 hover:!border-orange-600"
              icon={<ArrowLeft className="h-4 w-4" />}
              onClick={goBackToStandard}
            >
              返回
            </Button>
          </Space>
        }
      />
      <MaterialTableCard>
        <Table
          rowKey={(r) => r.recordId ?? r.id}
          loading={loading}
          columns={columns}
          dataSource={list}
          pagination={false}
          scroll={{ x: 'max-content' }}
          rowSelection={{
            selectedRowKeys,
            onChange: setSelectedRowKeys,
            preserveSelectedRowKeys: true,
            getCheckboxProps: (record) => ({ name: String(displaySpec(record)) }),
          }}
          rowClassName={(_, index) => (index !== undefined && index % 2 === 1 ? 'isolation-work-list-row-alt' : '')}
        />
      </MaterialTableCard>
      <MaterialPaginationBar
        total={total}
        current={pageNo}
        pageSize={pageSize}
        onPageChange={setPageNo}
        onPageSizeChange={(size) => {
          setPageSize(size);
          setPageNo(1);
        }}
        loading={loading}
        listLength={list.length}
        showQuickJumper
      />

      <Modal
        title={valEditing ? '修改' : '新增'}
        open={valModalOpen}
        onOk={submitValModal}
        onCancel={closeValModal}
        confirmLoading={valSaveLoading}
        {...getMaterialFormModalProps(t, 520)}
        styles={{ body: { paddingTop: 8 } }}
      >
        <Form form={valForm} {...valModalFormLayout}>
          <Form.Item label="物资规格种类编号">
            <Input
              disabled
              readOnly
              value={String(ctx.propertyId)}
              className="!cursor-not-allowed !bg-gray-100 !text-gray-600 !opacity-100"
            />
          </Form.Item>
          <Form.Item
            name="valueName"
            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>
  );
}
