import React, { useEffect, useState } from 'react';
import { Button, Radio } from 'antd';
import { Download } from 'lucide-react';
import { toast } from 'sonner';
import { useTranslation } from 'react-i18next';
import { materialStatisticsApi } from '../../../api/material/statistics';
import { downloadBlob } from '../materialListUtils';
import { MaterialPageRoot, MaterialToolbarCard, MaterialTableCard } from '../MaterialPageLayout';

type TabDef = { dictValue?: string; dictLabel?: string; sum?: number; label?: string; value?: string };

export default function MaterialInventoryPage() {
  const { t } = useTranslation();
  const [tab, setTab] = useState('0');
  const [tabs, setTabs] = useState<TabDef[]>([]);
  const [matrix, setMatrix] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);

  const loadTabsAndData = async (tkey: string) => {
    setLoading(true);
    try {
      const sumData: any = await materialStatisticsApi.getInventorySum();
      const tabList = Array.isArray(sumData) ? sumData : sumData?.list || sumData?.tabs || [];
      setTabs(tabList.length ? tabList : [{ dictValue: '0', dictLabel: '正常', sum: 0 }]);
      const data = await materialStatisticsApi.getMaterialInventory(tkey);
      setMatrix(Array.isArray(data) ? data : []);
    } catch (e: any) {
      toast.error(e?.message || '加载盘点数据失败');
      setMatrix([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadTabsAndData(tab);
  }, [tab]);

  const exportExcel = async () => {
    try {
      const blob = await materialStatisticsApi.exportMaterialInventory();
      downloadBlob(blob as Blob, '物资盘点.xls');
      toast.success('已开始下载');
    } catch (e: any) {
      toast.error(e?.message || t('common.operationFailed'));
    }
  };

  const tabKey = (x: TabDef, i: number) => String(x.dictValue ?? x.value ?? i);
  const tabLabel = (x: TabDef) => `${x.dictLabel ?? x.label ?? ''}${x.sum != null ? ` (${x.sum})` : ''}`;

  const cabinets = matrix;
  const materialTypes =
    cabinets.length > 0 ? cabinets[0]?.materialsTypeVOList || cabinets[0]?.materialsTypeList || [] : [];

  const getCell = (typeId: string | number, cabinetId: string | number) => {
    const cab = cabinets.find((c: any) => String(c.cabinetId) === String(cabinetId));
    if (!cab) return '';
    const list = cab.materialsTypeVOList || cab.materialsTypeList || [];
    const mt = list.find((m: any) => String(m.materialsTypeId) === String(typeId));
    if (!mt) return '';
    const n = mt.number;
    return n == null || n === 0 ? '' : String(n);
  };

  return (
    <MaterialPageRoot>
      <MaterialToolbarCard
        hideSearchButtons
        filterRow={
          <div className="flex flex-wrap items-center justify-between gap-3 w-full min-w-0">
            <Radio.Group value={tab} onChange={(e) => setTab(e.target.value)} optionType="button" buttonStyle="solid">
              {(tabs.length ? tabs : [{ dictValue: '0', dictLabel: '正常' }]).map((x, i) => (
                <Radio.Button key={tabKey(x, i)} value={tabKey(x, i)}>
                  {tabLabel(x) || `分类 ${i}`}
                </Radio.Button>
              ))}
            </Radio.Group>
            <Button type="primary" icon={<Download className="w-4 h-4" />} onClick={exportExcel}>
              导出
            </Button>
          </div>
        }
      />

      <MaterialTableCard>
        <div className="overflow-x-auto p-1">
          <table className="min-w-full border-collapse text-sm">
            <thead>
              <tr className="bg-gray-50">
                <th className="border border-gray-200 p-2 text-left w-40 text-gray-700 font-medium">物资类型</th>
                {cabinets.map((c: any) => (
                  <th key={c.cabinetId} className="border border-gray-200 p-2 text-center whitespace-nowrap text-gray-700 font-medium">
                    {c.cabinetName}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr>
                  <td colSpan={Math.max(cabinets.length + 1, 2)} className="border border-gray-200 p-6 text-center text-gray-500">
                    加载中…
                  </td>
                </tr>
              ) : materialTypes.length === 0 ? (
                <tr>
                  <td colSpan={Math.max(cabinets.length + 1, 2)} className="border border-gray-200 p-6 text-center text-gray-500">
                    暂无数据
                  </td>
                </tr>
              ) : (
                materialTypes.map((mt: any, idx: number) => (
                  <tr
                    key={mt.materialsTypeId}
                    className={idx % 2 === 1 ? 'bg-[#f0f0f0] hover:bg-[#e8e8e8]' : 'bg-white hover:bg-gray-50'}
                  >
                    <td className="border border-gray-200 p-2">
                      <div className="flex items-center gap-2">
                        {mt.materialsTypeIcon ? (
                          <img src={mt.materialsTypeIcon} alt="" className="h-10 w-10 rounded object-cover" />
                        ) : null}
                        <span>{mt.materialsTypeName}</span>
                      </div>
                    </td>
                    {cabinets.map((c: any) => (
                      <td key={c.cabinetId} className="border border-gray-200 p-2 text-center text-lg">
                        {getCell(mt.materialsTypeId, c.cabinetId)}
                      </td>
                    ))}
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </MaterialTableCard>
    </MaterialPageRoot>
  );
}
