import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { ArrowLeft } from 'lucide-react';
import { materialLockerApi } from '../../../api/material/lockers';
import { toast } from 'sonner';
import MaterialInformationPage from './MaterialInformationPage';
import MaterialLoanPage from './MaterialLoanPage';
import MaterialInspectionPlanPage from './MaterialInspectionPlanPage';
import MaterialInspectionRecordPage from './MaterialInspectionRecordPage';
import MaterialReplacementRecordPage from './MaterialReplacementRecordPage';

export interface MaterialLockerDetailPageProps {
  cabinetId: number;
  cabinetName?: string;
  onBack: () => void;
}

type DetailTabKey = 'inventory' | 'loan' | 'plan' | 'record' | 'replace';

const TAB_LABELS: Record<DetailTabKey, string> = {
  inventory: '物资清单',
  loan: '领取记录',
  plan: '检查计划',
  record: '检查记录',
  replace: '更换记录',
};

/** 显式顺序，避免 Object.keys 与 activeKey 不一致导致面板一直处于 hidden */
const TAB_KEYS: DetailTabKey[] = ['inventory', 'loan', 'plan', 'record', 'replace'];

/** 与 Dashboard 二级菜单 Tab 一致：选中蓝渐变胶囊，未选中灰字 + hover 浅蓝底 */
function subMenuPillClass(active: boolean) {
  return [
    'inline-flex shrink-0 select-none items-center justify-center gap-1.5 whitespace-nowrap rounded-xl px-3 py-2 text-xs font-medium transition-all duration-200 sm:px-4 sm:py-2.5 sm:text-sm',
    active
      ? 'bg-gradient-to-r from-blue-500 to-blue-600 text-white shadow-lg shadow-blue-400/40'
      : 'text-gray-700 hover:bg-blue-50 hover:text-blue-600',
  ].join(' ');
}

/**
 * 物资柜详情：顶栏 Tab 与 Dashboard 二级菜单同款胶囊条；右侧物资柜名 + 返回同风格；下方独立挂载各面板
 */
export default function MaterialLockerDetailPage({ cabinetId, cabinetName, onBack }: MaterialLockerDetailPageProps) {
  const [titleName, setTitleName] = useState(cabinetName?.trim() || '');
  const [activeKey, setActiveKey] = useState<DetailTabKey>('inventory');

  const loadTitle = useCallback(async () => {
    if (cabinetName?.trim()) {
      setTitleName(cabinetName.trim());
      return;
    }
    try {
      const res: any = await materialLockerApi.getMaterialsCabinetInfo(cabinetId);
      const data = res?.data ?? res;
      const n = data?.cabinetName ?? data?.name;
      if (n) setTitleName(String(n));
    } catch {
      toast.error('加载物资柜信息失败');
    }
  }, [cabinetId, cabinetName]);

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

  const displayTitle = titleName.trim() || '物资柜详情';

  const embeddedTabBar = useMemo(
    () => (
      <div className="flex w-full min-w-0 flex-nowrap items-center gap-2 sm:gap-3">
        <div className="flex min-h-[40px] min-w-0 flex-1 flex-nowrap items-center gap-2 overflow-x-auto pb-0.5 [-webkit-overflow-scrolling:touch] sm:min-h-0">
          {TAB_KEYS.map((key) => {
            const active = activeKey === key;
            return (
              <button
                key={key}
                type="button"
                onClick={() => setActiveKey(key)}
                className={subMenuPillClass(active)}
              >
                <span className={active ? 'text-white' : ''}>{TAB_LABELS[key]}</span>
              </button>
            );
          })}
        </div>
        <div className="flex shrink-0 items-center gap-2 border-l border-gray-200/80 pl-2 sm:pl-3">
          <span
            className={`${subMenuPillClass(false)} max-w-[36vw] cursor-default sm:max-w-[220px]`}
            title={displayTitle}
          >
            <span className="truncate">{displayTitle}</span>
          </span>
          <button type="button" className={subMenuPillClass(false)} onClick={onBack}>
            <ArrowLeft className="h-4 w-4 shrink-0 opacity-90" aria-hidden />
            <span>返回</span>
          </button>
        </div>
      </div>
    ),
    [activeKey, displayTitle, onBack],
  );

  return (
    <div className="space-y-4">
      {/* 同时挂载各面板、仅显示当前 Tab，切换不丢表单状态；Tab 与筛选同卡由各子页渲染 */}
      <div className="min-h-[200px] w-full">
        <div className={activeKey === 'inventory' ? 'block' : 'hidden'} aria-hidden={activeKey !== 'inventory'}>
          <MaterialInformationPage
            embedded
            embeddedTabBar={embeddedTabBar}
            fixedCabinetId={cabinetId}
            fixedCabinetName={titleName || undefined}
          />
        </div>
        <div className={activeKey === 'loan' ? 'block' : 'hidden'} aria-hidden={activeKey !== 'loan'}>
          <MaterialLoanPage embedded embeddedTabBar={embeddedTabBar} fixedCabinetId={cabinetId} />
        </div>
        <div className={activeKey === 'plan' ? 'block' : 'hidden'} aria-hidden={activeKey !== 'plan'}>
          <MaterialInspectionPlanPage embedded embeddedTabBar={embeddedTabBar} fixedCabinetId={cabinetId} />
        </div>
        <div className={activeKey === 'record' ? 'block' : 'hidden'} aria-hidden={activeKey !== 'record'}>
          <MaterialInspectionRecordPage embedded embeddedTabBar={embeddedTabBar} fixedCabinetId={cabinetId} />
        </div>
        <div className={activeKey === 'replace' ? 'block' : 'hidden'} aria-hidden={activeKey !== 'replace'}>
          <MaterialReplacementRecordPage embedded embeddedTabBar={embeddedTabBar} fixedCabinetId={cabinetId} />
        </div>
      </div>
    </div>
  );
}
