import React, { useCallback, useEffect, useState } from 'react';
import { Input, Table, Image } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { toast } from 'sonner';
import { handleTree } from '../../../utils/tree';
import { materialTypeApi } from '../../../api/material/type';
import { materialStandardApi } from '../../../api/material/standard';
import { pickRecords, fetchAllMaterialTypes } from '../materialListUtils';
import { MaterialPageRoot, MaterialToolbarCard, MaterialTableCard } from '../MaterialPageLayout';

export default function MaterialTypePage() {
  const [loading, setLoading] = useState(false);
  const [tree, setTree] = useState<any[]>([]);
  const [draftName, setDraftName] = useState('');
  const [appliedName, setAppliedName] = useState('');
  const [propertyMap, setPropertyMap] = useState<Record<string, string>>({});

  const loadPropertyMap = async () => {
    try {
      const res = await materialStandardApi.PropertyPage({ pageNo: 1, pageSize: -1 });
      const records = pickRecords(res);
      const map: Record<string, string> = {};
      records.forEach((item: any) => {
        const id = String(item.propertyId ?? item.id ?? '');
        const nm = item.propertyName ?? item.name ?? id;
        if (id) {
          map[id] = nm;
        }
      });
      setPropertyMap(map);
    } catch {
      setPropertyMap({});
    }
  };

  const fetchList = useCallback(async () => {
    setLoading(true);
    try {
      const flat = await fetchAllMaterialTypes(materialTypeApi.listType, {
        materialsTypeName: appliedName || undefined,
      });
      setTree(handleTree(flat as any, 'id', 'parentId', 'children'));
    } catch (e: any) {
      toast.error(e?.message || '加载失败');
      setTree([]);
    } finally {
      setLoading(false);
    }
  }, [appliedName]);

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

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

  const displayProps = (ids: string | undefined) => {
    if (!ids) return '—';
    const parts = String(ids)
      .split(',')
      .map((x) => x.trim())
      .filter(Boolean);
    return parts.map((id) => propertyMap[id] || id).join(', ') || '—';
  };

  const imgCell = (url: string | undefined) =>
    url ? (
      <Image
        src={url}
        width={48}
        height={48}
        className="rounded-md border border-gray-200"
        style={{ objectFit: 'cover' }}
        preview={{ mask: '预览' }}
      />
    ) : (
      <span className="text-gray-400">—</span>
    );

  const columns: ColumnsType<any> = [
    {
      title: '物资类型名称',
      dataIndex: 'materialsTypeName',
      key: 'materialsTypeName',
      width: 240,
      ellipsis: { showTitle: true },
      align: 'left',
    },
    {
      title: '物资规格',
      dataIndex: 'propertyIds',
      key: 'propertyIds',
      width: 260,
      ellipsis: { showTitle: true },
      align: 'left',
      render: (v: string) => displayProps(v),
    },
    {
      title: '物资类型图标',
      dataIndex: 'materialsTypeIcon',
      key: 'materialsTypeIcon',
      width: 108,
      align: 'center',
      className: '!align-middle',
      render: (u: string) => imgCell(u),
    },
    {
      title: '物资类型缩略图',
      dataIndex: 'materialsTypePicture',
      key: 'materialsTypePicture',
      width: 108,
      align: 'center',
      className: '!align-middle',
      render: (u: string) => imgCell(u),
    },
  ];

  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)}
        onReset={() => {
          setDraftName('');
          setAppliedName('');
        }}
      />
      <MaterialTableCard>
        <div className="material-type-tree-table">
          <Table
            rowKey={(r) => r.id}
            loading={loading}
            columns={columns}
            dataSource={tree}
            pagination={false}
            tableLayout="fixed"
            scroll={{ x: 748 }}
            expandable={{
              defaultExpandAllRows: true,
              indentSize: 22,
            }}
            rowClassName={(_, index) => (index !== undefined && index % 2 === 1 ? 'isolation-work-list-row-alt' : '')}
          />
        </div>
      </MaterialTableCard>
    </MaterialPageRoot>
  );
}
