import { useState, useMemo, useEffect } from 'react';
import { Wallet, Users, Info, PieChart, Tag, Calendar, User, FileText, TrendingUp, BarChart3, Download } from 'lucide-react';
import { useTourStore } from '@/store/useTourStore';
import { format } from 'date-fns';
import { jsPDF } from 'jspdf';
import { robotoBase64 } from '../utils/pdfFont';
import autoTable from 'jspdf-autotable';

// Sub-component cho phép chỉnh sửa số lượng thành viên gia đình trực tiếp trên dòng của bảng phân chia chi phí
const FamilySizeEditor = ({
  participant,
  tourId,
  type,
  canManage,
  currentUserId
}: {
  participant: any,
  tourId: string,
  type: 'adult' | 'child',
  canManage: boolean,
  currentUserId: string | null
}) => {
  const [val, setVal] = useState(type === 'adult' ? (participant.adultCount ?? 1) : (participant.childCount ?? 0));
  const [loading, setLoading] = useState(false);
  const updateMemberFamilyCount = useTourStore(state => state.updateMemberFamilyCount);

  useEffect(() => {
    setVal(type === 'adult' ? (participant.adultCount ?? 1) : (participant.childCount ?? 0));
  }, [participant, type]);

  const handleSave = async (newVal: number) => {
    if (newVal === val) return;
    setLoading(true);
    try {
      const nextAdult = type === 'adult' ? newVal : (participant.adultCount ?? 1);
      const nextChild = type === 'child' ? newVal : (participant.childCount ?? 0);
      await updateMemberFamilyCount(tourId, participant.userId || participant.id, nextAdult, nextChild);
    } catch (err) {
      console.error("Lỗi khi lưu quy mô gia đình thành viên:", err);
    } finally {
      setLoading(false);
    }
  };

  const isEditable = canManage || (participant.userId && currentUserId === participant.userId);

  if (!isEditable) {
    return <span className="font-bold text-gray-800">{val}</span>;
  }

  return (
    <div className="flex items-center gap-1 bg-gray-50 p-1 rounded-lg border border-gray-100 shadow-sm">
      <button
        onClick={() => {
          const next = Math.max(type === 'adult' ? 1 : 0, val - 1);
          setVal(next);
          handleSave(next);
        }}
        disabled={loading || (type === 'adult' && val <= 1) || (type === 'child' && val <= 0)}
        className="w-5 h-5 rounded bg-white border border-gray-200 hover:bg-gray-100 flex items-center justify-center font-bold text-[10px] text-gray-600 disabled:opacity-50 transition-all active:scale-90"
      >
        -
      </button>
      <span className="w-5 text-center font-black text-xs text-gray-800">{val}</span>
      <button
        onClick={() => {
          const next = val + 1;
          setVal(next);
          handleSave(next);
        }}
        disabled={loading}
        className="w-5 h-5 rounded bg-white border border-gray-200 hover:bg-gray-100 flex items-center justify-center font-bold text-[10px] text-gray-600 disabled:opacity-50 transition-all active:scale-90"
      >
        +
      </button>
    </div>
  );
};

export const ExpenseManager = () => {
  const { legs, currentTour } = useTourStore();
  const [splitMode, setSplitMode] = useState<'individual' | 'family'>('family');

  const discount = currentTour?.childDiscount ?? 0;
  const childRateFactor = 1 - (Number(discount) / 100);

  const rawToken = localStorage.getItem('token');
  let currentUserId: string | null = null;
  try {
    const payload = JSON.parse(atob((rawToken || '').split('.')[1]));
    currentUserId = payload.sub;
  } catch {
    currentUserId = null;
  }

  const userRole = useTourStore(state => state.userRole);
  const canManage = userRole === 'OWNER' || userRole === 'MANAGER';

  const stats = useMemo(() => {
    const categoryMap: Record<string, number> = {
      ACCOMMODATION: 0,
      FOOD: 0,
      TRANSPORT: 0,
      TICKET: 0,
      OTHER: 0
    };
    const legMap: Record<string, number> = {};
    const memberMap: Record<string, number> = {};
    const participantPaidMap: Record<string, number> = {};
    let totalAmount = 0;
    let totalCount = 0;

    (legs || []).forEach(leg => {
      let legTotal = 0;
      (leg.expenses || []).forEach((exp: any) => {
        const amt = Number(exp.amount);
        totalAmount += amt;
        legTotal += amt;
        totalCount += 1;

        const memberName = exp.paidBy?.name || 'Chưa rõ';
        memberMap[memberName] = (memberMap[memberName] || 0) + amt;

        if (exp.paidBy?.id) {
          participantPaidMap[exp.paidBy.id] = (participantPaidMap[exp.paidBy.id] || 0) + amt;
        }

        if (categoryMap[exp.category] !== undefined) {
          categoryMap[exp.category] += amt;
        } else {
          categoryMap.OTHER += amt;
        }
      });
      legMap[leg.sequence] = legTotal;
    });

    // Tìm hạng mục tốn nhất
    const maxCat = Object.entries(categoryMap).reduce((a, b) => b[1] > a[1] ? b : a, ['OTHER', 0]);

    // Tìm chặng tốn nhất
    const maxLegEntry = Object.entries(legMap).length > 0
      ? Object.entries(legMap).reduce((a, b) => b[1] > a[1] ? b : a)
      : [null, 0];

    const avgPerLeg = legs.length > 0 ? totalAmount / legs.length : 0;

    // Danh sách phẳng tất cả chi phí để hiển thị bảng
    const flatExpenses: any[] = [];
    [...(legs || [])].sort((a, b) => a.sequence - b.sequence).forEach((leg, legIdx) => {
      const legExpenses = (leg.expenses || []).map((exp: any) => ({
        ...exp,
        legSequence: leg.sequence,
        legDisplayIndex: legIdx + 1, // Số thứ tự chặng liên tục (1, 2, 3...)
        date: exp.location?.plannedStart || leg.startDate || null
      })).sort((a: any, b: any) => {
        if (!a.date || !b.date) return 0;
        return new Date(a.date).getTime() - new Date(b.date).getTime();
      });

      legExpenses.forEach((exp: any, idx: number) => {
        flatExpenses.push({
          ...exp,
          isFirstInLeg: idx === 0
        });
      });
    });

    return {
      total: totalAmount,
      count: totalCount,
      categories: categoryMap,
      list: flatExpenses,
      topCategory: maxCat[0],
      topLeg: maxLegEntry[0],
      avgPerLeg,
      memberStats: Object.entries(memberMap),
      participantPaidMap
    };
  }, [legs]);

  const participants = currentTour?.participants || [];

  const splitResult = useMemo(() => {
    let adultsTotal = 0;
    let childrenTotal = 0;

    if (splitMode === 'individual') {
      adultsTotal = participants.length > 0 ? participants.length : (currentTour?.adultCount ?? 1);
      childrenTotal = 0;
    } else {
      adultsTotal = participants.reduce((sum: number, p: any) => sum + (p.adultCount ?? 1), 0);
      childrenTotal = participants.reduce((sum: number, p: any) => sum + (p.childCount ?? 0), 0);

      // Fallback nếu không có thành viên nào tham gia
      if (participants.length === 0) {
        adultsTotal = currentTour?.adultCount ?? 1;
        childrenTotal = currentTour?.childCount ?? 0;
      }
    }

    const weightedCount = adultsTotal + (childrenTotal * childRateFactor);
    const adultPrice = weightedCount > 0 ? stats.total / weightedCount : 0;
    const childPrice = adultPrice * childRateFactor;

    return {
      adultsTotal,
      childrenTotal,
      adultPrice: Math.round(adultPrice),
      childPrice: Math.round(childPrice),
      weightedCount
    };
  }, [splitMode, participants, discount, stats.total, currentTour, childRateFactor]);

  // Hàm xuất PDF
  const handleExportPDF = () => {
    const doc = new jsPDF();

    // 1. Khai báo chuỗi Base64 của font (Đây là ví dụ, bạn thay bằng chuỗi thực tế từ Bước 1)
    // Roboto-Regular font imported from utils/pdfFont

    // Khai báo chuỗi Base64 của Logo (Thay bằng chuỗi thực tế của bạn)
    const logoBase64 = "data:image/png;base64,[encoded data, 93004 characters]";
    // 2. Thêm font vào Virtual File System của jsPDF
    doc.addFileToVFS("Roboto-Regular.ttf", robotoBase64);

    // 3. Đăng ký font với tên gọi 'Roboto'
    doc.addFont("Roboto-Regular.ttf", "Roboto", "normal");

    // 4. Thiết lập font mặc định cho tài liệu
    doc.setFont("Roboto");

    // 5. Thêm Logo vào PDF (x, y, width, height)
    doc.addImage(logoBase64, 'PNG', 14, 10, 15, 15);

    // Bây giờ bạn có thể viết tiếng Việt có dấu thoải mái
    doc.setFontSize(18);
    doc.setTextColor(37, 99, 235); // Blue-600
    doc.text("BÁO CÁO CHI PHÍ TOUR", 35, 21); // Đẩy tiêu đề sang phải logo

    doc.setFontSize(11);
    doc.setTextColor(100);
    doc.text(`Chuyến đi: ${currentTour?.title || 'Hành trình'}`, 14, 40);
    doc.text(`Ngày xuất: ${format(new Date(), 'dd/MM/yyyy HH:mm')}`, 14, 47);

    doc.setTextColor(0);
    doc.setFontSize(12);
    doc.text(`Tổng chi: ${stats.total.toLocaleString()}đ`, 14, 54);
    doc.text(`Đơn giá người lớn: ${splitResult.adultPrice.toLocaleString()}đ`, 14, 61);
    doc.text(`Đơn giá trẻ em: ${splitResult.childPrice.toLocaleString()}đ (Giảm ${discount}%)`, 14, 68);

    // Cấu hình bảng dữ liệu
    const tableColumn = ["STT", "Ngày giờ", "Chặng", "Dịch vụ", "Số tiền (VNĐ)", "Người chi"];
    const tableRows = stats.list.map((exp: any) => [
      exp.isFirstInLeg ? exp.legSequence : '',
      exp.date ? format(new Date(exp.date), 'd/M - p') : '--/--',
      exp.isFirstInLeg ? `Chặng ${exp.legSequence}` : '',
      exp.description || 'Không có mô tả',
      Number(exp.amount).toLocaleString(),
      exp.paidBy?.name || 'Chưa rõ'
    ]);

    autoTable(doc, {
      head: [tableColumn],
      body: tableRows,
      startY: 75, // Đẩy bảng xuống để không đè lên thông tin phía trên
      theme: 'grid',
      headStyles: { fillColor: [37, 99, 235], textColor: [255, 255, 255], fontStyle: 'normal' }, // Roboto Bold nếu bạn thêm font bold
      styles: { font: "Roboto", fontSize: 8, cellPadding: 3 }, // Quan trọng: Khai báo font ở đây cho autoTable
      columnStyles: {
        4: { halign: 'right' }
      }
    });

    const finalY = (doc as any).lastAutoTable.finalY || 150;

    // Bảng 2: Phân chia chi phí theo thành viên / gia đình
    doc.text("PHÂN CHIA CHI PHÍ CHI TIẾT THEO " + (splitMode === 'family' ? "GIA ĐÌNH" : "CÁ NHÂN"), 14, finalY + 15);

    const memberHeaders = splitMode === 'family'
      ? ["Thành viên", "Vai trò", "Người lớn", "Trẻ em", "Chi phí trách nhiệm", "Đã trả", "Còn lại"]
      : ["Thành viên", "Vai trò", "Chi phí trách nhiệm", "Đã trả", "Còn lại"];

    const memberRows = participants.filter((p: any) => p.user || p.displayName).map((p: any) => {
      const pAdults = splitMode === 'family' ? (p.adultCount ?? 1) : 1;
      const pChildren = splitMode === 'family' ? (p.childCount ?? 0) : 0;
      const responsibilityCost = (splitResult.adultPrice * pAdults) + (splitResult.childPrice * pChildren);
      const amountPaid = stats.participantPaidMap[p.userId || p.id] || 0;
      const remaining = responsibilityCost - amountPaid;

      const remainingText = remaining > 0
        ? `Đóng thêm: ${remaining.toLocaleString()}đ`
        : remaining < 0
          ? `Thối lại: ${Math.abs(remaining).toLocaleString()}đ`
          : 'Hoàn thành';

      const displayName = p.user?.name || p.displayName || 'Thành viên';

      return splitMode === 'family'
        ? [displayName, p.role, pAdults, pChildren, `${responsibilityCost.toLocaleString()}đ`, `${amountPaid.toLocaleString()}đ`, remainingText]
        : [displayName, p.role, `${responsibilityCost.toLocaleString()}đ`, `${amountPaid.toLocaleString()}đ`, remainingText];
    });

    autoTable(doc, {
      head: [memberHeaders],
      body: memberRows,
      startY: finalY + 20,
      theme: 'grid',
      headStyles: { fillColor: [79, 70, 229], textColor: [255, 255, 255], fontStyle: 'normal' },
      styles: { font: "Roboto", fontSize: 8, cellPadding: 3 }
    });

    doc.save(`Chi-phi-tour-${currentTour?.title || 'export'}.pdf`);
  };

  const categoryLabels: Record<string, { label: string, color: string }> = {
    ACCOMMODATION: { label: 'Chỗ ở', color: 'bg-blue-500' },
    FOOD: { label: 'Ăn uống', color: 'bg-orange-500' },
    TRANSPORT: { label: 'Di chuyển', color: 'bg-indigo-500' },
    TICKET: { label: 'Vé tham quan', color: 'bg-green-500' },
    OTHER: { label: 'Khác', color: 'bg-gray-400' }
  };

  return (
    <div className="space-y-6 animate-in fade-in slide-in-from-bottom-4">
      {/* Thẻ hiển thị tổng quan chi phí theo công thức */}
      <div className="bg-blue-600 rounded-3xl p-6 text-white shadow-lg shadow-blue-200">
        <div className="flex justify-between items-start mb-8">
          <div>
            <p className="text-blue-100 text-sm font-medium">Tổng chi phí chuyến đi</p>
            <h2 className="text-3xl font-black mt-1">{stats.total.toLocaleString()} VND</h2>
            <p className="text-blue-200 text-[10px] mt-1.5 font-bold uppercase tracking-wider">{stats.count} hóa đơn đã ghi nhận</p>
          </div>
          <Wallet className="w-8 h-8 opacity-20" />
        </div>

        <div className="grid grid-cols-2 gap-6 border-t border-blue-500/50 pt-6">
          <div>
            <p className="text-blue-100 text-[10px] uppercase tracking-widest font-black">Giá mỗi người lớn (X)</p>
            <p className="text-2xl font-black">{splitResult.adultPrice.toLocaleString()}đ</p>
          </div>
          <div>
            <p className="text-blue-100 text-[10px] uppercase tracking-widest font-black">Giá mỗi trẻ em (-{discount}%)</p>
            <p className="text-2xl font-black">{splitResult.childPrice.toLocaleString()}đ</p>
          </div>
        </div>
      </div>

      {/* Thẻ chỉ số nhanh */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        <div className="bg-white p-4 rounded-2xl border border-gray-100 shadow-sm flex items-center gap-3">
          <div className="w-10 h-10 rounded-xl bg-orange-50 flex items-center justify-center text-orange-500">
            <BarChart3 className="w-5 h-5" />
          </div>
          <div>
            <p className="text-[10px] font-black text-gray-400 uppercase tracking-widest">Hạng mục tốn nhất</p>
            <p className="text-sm font-bold text-gray-800">{categoryLabels[stats.topCategory]?.label || 'Chưa có'}</p>
          </div>
        </div>
        <div className="bg-white p-4 rounded-2xl border border-gray-100 shadow-sm flex items-center gap-3">
          <div className="w-10 h-10 rounded-xl bg-purple-50 flex items-center justify-center text-purple-500">
            <TrendingUp className="w-5 h-5" />
          </div>
          <div>
            <p className="text-[10px] font-black text-gray-400 uppercase tracking-widest">Trung bình / Chặng</p>
            <p className="text-sm font-bold text-gray-800">{Math.round(stats.avgPerLeg).toLocaleString()}đ</p>
          </div>
        </div>
        <div className="bg-white p-4 rounded-2xl border border-gray-100 shadow-sm flex items-center gap-3">
          <div className="w-10 h-10 rounded-xl bg-green-50 flex items-center justify-center text-green-500">
            <Tag className="w-5 h-5" />
          </div>
          <div>
            <p className="text-[10px] font-black text-gray-400 uppercase tracking-widest">Chặng tốn kém nhất</p>
            <p className="text-sm font-bold text-gray-800">{stats.topLeg ? `Chặng ${stats.topLeg}` : 'Chưa có'}</p>
          </div>
        </div>
      </div>

      {/* Bảng phân chia chi phí - Yêu cầu tính toán chi tiết */}
      <div className="bg-white p-6 rounded-3xl border border-gray-100 shadow-sm space-y-6">
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
          <div className="flex items-center gap-2 text-gray-800">
            <Users className="w-5 h-5 text-blue-500" />
            <h3 className="font-black text-gray-900 uppercase tracking-tight">Bảng phân chia chi phí</h3>
          </div>

          <div className="flex items-center bg-gray-100 p-1 rounded-xl self-start sm:self-auto border border-gray-200/50">
            <button
              onClick={() => setSplitMode('individual')}
              className={`px-4 py-2 text-xs font-black uppercase tracking-wider rounded-lg transition-all ${splitMode === 'individual' ? 'bg-white text-blue-600 shadow-sm' : 'text-gray-500 hover:text-gray-800'
                }`}
            >
              Cá nhân
            </button>
            <button
              onClick={() => setSplitMode('family')}
              className={`px-4 py-2 text-xs font-black uppercase tracking-wider rounded-lg transition-all ${splitMode === 'family' ? 'bg-white text-blue-600 shadow-sm' : 'text-gray-500 hover:text-gray-800'
                }`}
            >
              Gia đình
            </button>
          </div>
        </div>

        {/* Thông tin công thức áp dụng */}
        <div className="bg-blue-50/50 border border-blue-100/50 rounded-2xl p-4 space-y-3">
          <div className="flex items-start gap-2.5 text-blue-700">
            <Info className="w-4 h-4 mt-0.5 flex-shrink-0" />
            <div className="text-xs space-y-1">
              <p className="font-black uppercase tracking-wide">Công thức tính phân bổ chi phí:</p>
              <p className="font-semibold text-gray-600 leading-relaxed">
                <span className="font-bold text-blue-700">Tổng chi phí</span> =
                (Số người lớn × Đơn giá lớn) + (Số trẻ em × Đơn giá lớn × {100 - discount}%)
              </p>
              <p className="text-[11px] text-gray-400 italic">
                * Trẻ em được giảm {discount}% (Phần trăm thanh toán: {100 - discount}%)
              </p>
            </div>
          </div>

          <div className="grid grid-cols-2 sm:grid-cols-4 gap-4 pt-2 border-t border-blue-100/30">
            <div className="bg-white p-3 rounded-xl border border-blue-100/40">
              <p className="text-[9px] font-black text-gray-400 uppercase tracking-widest">Tổng chi phí</p>
              <p className="text-sm font-black text-blue-600">{stats.total.toLocaleString()}đ</p>
            </div>
            <div className="bg-white p-3 rounded-xl border border-blue-100/40">
              <p className="text-[9px] font-black text-gray-400 uppercase tracking-widest">Quy mô tính</p>
              <p className="text-sm font-black text-gray-800">
                {splitResult.adultsTotal} Lớn {splitResult.childrenTotal > 0 && `• ${splitResult.childrenTotal} Trẻ`}
              </p>
            </div>
            <div className="bg-white p-3 rounded-xl border border-blue-100/40">
              <p className="text-[9px] font-black text-gray-400 uppercase tracking-widest">Đơn giá người lớn (X)</p>
              <p className="text-sm font-black text-gray-800">{splitResult.adultPrice.toLocaleString()}đ</p>
            </div>
            <div className="bg-white p-3 rounded-xl border border-blue-100/40">
              <p className="text-[9px] font-black text-gray-400 uppercase tracking-widest">Đơn giá trẻ em</p>
              <p className="text-sm font-black text-gray-800">{splitResult.childPrice.toLocaleString()}đ</p>
            </div>
          </div>
        </div>

        {/* Bảng phân chia thực tế */}
        <div className="overflow-x-auto border border-gray-100 rounded-2xl">
          <table className="w-full text-left border-collapse min-w-[650px]">
            <thead>
              <tr className="bg-gray-50/50 text-[10px] font-black text-gray-400 uppercase tracking-widest border-b border-gray-100">
                <th className="px-4 py-4 min-w-[150px]">Thành viên</th>
                <th className="px-4 py-4 text-center">Vai trò</th>
                {splitMode === 'family' && (
                  <>
                    <th className="px-4 py-4 text-center">Người lớn</th>
                    <th className="px-4 py-4 text-center">Trẻ em</th>
                  </>
                )}
                <th className="px-4 py-4 text-right">Chi phí chịu</th>
                <th className="px-4 py-4 text-right">Đã chi trả</th>
                <th className="px-4 py-4 text-right min-w-[150px]">Còn lại</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-50">
              {participants.filter((p: any) => p.user || p.displayName).length > 0 ? (
                participants.filter((p: any) => p.user || p.displayName).map((p: any) => {
                  const pAdults = splitMode === 'family' ? (p.adultCount ?? 1) : 1;
                  const pChildren = splitMode === 'family' ? (p.childCount ?? 0) : 0;

                  const responsibilityCost = (splitResult.adultPrice * pAdults) + (splitResult.childPrice * pChildren);
                  const amountPaid = stats.participantPaidMap[p.userId || p.id] || 0;
                  const remaining = responsibilityCost - amountPaid;

                  const displayName = p.user?.name || p.displayName || 'Thành viên';
                  const email = p.user?.email || 'Thành viên ngoài hệ thống';

                  return (
                    <tr key={p.id} className="hover:bg-gray-50/50 transition-colors text-sm">
                      <td className="px-4 py-4">
                        <div className="flex items-center gap-2.5">
                          <div className="w-8 h-8 rounded-full bg-blue-100 border border-blue-200 flex items-center justify-center text-blue-700 font-bold text-xs">
                            {displayName.charAt(0)}
                          </div>
                          <div className="flex flex-col">
                            <span className="font-bold text-gray-900">{displayName}</span>
                            <span className="text-[10px] text-gray-400 font-semibold">{email}</span>
                          </div>
                        </div>
                      </td>

                      <td className="px-4 py-4 text-center">
                        <span className={`px-2 py-0.5 rounded-full text-[9px] font-black border ${p.role === 'OWNER' ? 'bg-red-50 text-red-600 border-red-100' :
                          p.role === 'MANAGER' ? 'bg-purple-50 text-purple-600 border-purple-100' :
                            'bg-gray-50 text-gray-500 border-gray-100'
                          }`}>
                          {p.role}
                        </span>
                      </td>

                      {splitMode === 'family' && (
                        <>
                          <td className="px-4 py-4">
                            <div className="flex justify-center">
                              <FamilySizeEditor
                                participant={p}
                                tourId={currentTour.id}
                                type="adult"
                                canManage={canManage}
                                currentUserId={currentUserId}
                              />
                            </div>
                          </td>
                          <td className="px-4 py-4">
                            <div className="flex justify-center">
                              <FamilySizeEditor
                                participant={p}
                                tourId={currentTour.id}
                                type="child"
                                canManage={canManage}
                                currentUserId={currentUserId}
                              />
                            </div>
                          </td>
                        </>
                      )}

                      <td className="px-4 py-4 text-right font-black text-gray-900">
                        {responsibilityCost.toLocaleString()}đ
                      </td>

                      <td className="px-4 py-4 text-right font-semibold text-gray-600">
                        {amountPaid.toLocaleString()}đ
                      </td>

                      <td className="px-4 py-4 text-right">
                        {remaining > 0 ? (
                          <span className="inline-block px-2.5 py-1 bg-red-50 text-red-600 border border-red-100 rounded-lg font-black text-xs">
                            Đóng thêm: {remaining.toLocaleString()}đ
                          </span>
                        ) : remaining < 0 ? (
                          <span className="inline-block px-2.5 py-1 bg-emerald-50 text-emerald-600 border border-emerald-100 rounded-lg font-black text-xs">
                            Thối lại: {Math.abs(remaining).toLocaleString()}đ
                          </span>
                        ) : (
                          <span className="inline-block px-2.5 py-1 bg-gray-50 text-gray-500 border border-gray-100 rounded-lg font-black text-xs">
                            Hoàn thành
                          </span>
                        )}
                      </td>
                    </tr>
                  );
                })
              ) : (
                <tr>
                  <td colSpan={splitMode === 'family' ? 7 : 5} className="py-8 text-center text-gray-400 text-sm italic">
                    Không có thành viên tham gia tour.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Thống kê theo người chi trả gốc */}
      <div className="bg-white p-6 rounded-2xl border border-gray-100 shadow-sm">
        <div className="flex items-center gap-2 mb-6 text-gray-800">
          <Users className="w-5 h-5 text-blue-500" />
          <h3 className="font-bold">Thống kê theo tổng chi trả thực tế</h3>
        </div>
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          {stats.memberStats.length > 0 ? stats.memberStats.map(([name, amount]) => {
            const percentage = stats.total > 0 ? (amount / stats.total) * 100 : 0;
            return (
              <div key={name} className="flex items-center justify-between p-4 bg-gray-50 rounded-2xl border border-gray-100">
                <div className="flex items-center gap-3">
                  <div className="w-8 h-8 rounded-full bg-blue-100 flex items-center justify-center text-blue-600 font-bold text-xs">
                    {name.charAt(0)}
                  </div>
                  <span className="text-sm font-bold text-gray-700">{name}</span>
                </div>
                <div className="text-right">
                  <div className="text-sm font-black text-gray-900">{amount.toLocaleString()}đ</div>
                  <div className="text-[10px] text-gray-400 font-bold uppercase">{percentage.toFixed(1)}% tổng chi</div>
                </div>
              </div>
            );
          }) : (
            <div className="col-span-full py-8 text-center text-gray-400 text-sm italic">
              Chưa có thông tin chi trả của thành viên.
            </div>
          )}
        </div>
      </div>

      {/* Thống kê theo hạng mục */}
      <div className="bg-white p-6 rounded-2xl border border-gray-100 shadow-sm">
        <div className="flex items-center gap-2 mb-6 text-gray-800">
          <PieChart className="w-5 h-5 text-indigo-500" />
          <h3 className="font-bold">Phân tích chi tiêu</h3>
        </div>
        <div className="space-y-4">
          {stats.total > 0 ? Object.entries(stats.categories).map(([key, value]) => {
            const percentage = stats.total > 0 ? (value / stats.total) * 100 : 0;
            if (value === 0) return null;
            return (
              <div key={key}>
                <div className="flex justify-between text-xs mb-1.5 font-bold">
                  <span className="text-gray-600 flex items-center gap-1.5">
                    <div className={`w-2 h-2 rounded-full ${categoryLabels[key].color}`} />
                    {categoryLabels[key].label}
                  </span>
                  <span className="text-gray-900">{value.toLocaleString()}đ ({percentage.toFixed(1)}%)</span>
                </div>
                <div className="w-full h-2 bg-gray-50 rounded-full overflow-hidden border border-gray-100">
                  <div className={`h-full ${categoryLabels[key].color} transition-all duration-500`} style={{ width: `${percentage}%` }} />
                </div>
              </div>
            );
          }) : (
            <div className="py-8 text-center text-gray-400 text-sm italic">
              Chưa có dữ liệu phân tích theo hạng mục.
            </div>
          )}
        </div>
      </div>

      {/* Bảng thống kê chi tiết chi phí */}
      <div className="bg-white rounded-3xl border border-gray-100 shadow-sm overflow-hidden">
        <div className="p-6 border-b border-gray-100 bg-gray-50/30 flex items-center justify-between">
          <div className="flex items-center gap-2">
            <FileText className="w-5 h-5 text-blue-600" />
            <h3 className="font-black text-gray-900 uppercase tracking-tight">Bảng kê chi tiết các khoản chi</h3>
          </div>
          <button
            onClick={handleExportPDF}
            className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-xl text-[11px] font-black uppercase tracking-wider transition-all shadow-lg shadow-blue-200 active:scale-95"
          >
            <Download className="w-3.5 h-3.5" /> Xuất PDF
          </button>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full text-left border-collapse">
            <thead>
              <tr className="bg-gray-50/50 text-[10px] font-black text-gray-400 uppercase tracking-widest border-b border-gray-100">
                <th className="px-4 py-4 text-center">STT</th>
                <th className="px-4 py-4 min-w-[100px]">Ngày giờ</th>
                <th className="px-4 py-4 min-w-[80px]">Chặng</th>
                <th className="px-4 py-4">Dịch vụ sử dụng</th>
                <th className="px-4 py-4 text-right">Số tiền</th>
                <th className="px-4 py-4 min-w-[120px]">Người đã trả</th>
                <th className="px-4 py-4">Ghi chú</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-50">
              {stats.list.length > 0 ? (
                stats.list.map((exp: any) => (
                  <tr key={exp.id} className={`hover:bg-blue-50/20 transition-colors text-sm ${!exp.isFirstInLeg ? 'bg-gray-50/10' : ''}`}>
                    <td className="px-4 py-4 text-center font-black text-gray-400">
                      {exp.isFirstInLeg ? exp.legDisplayIndex : ''}
                    </td>
                    <td className="px-4 py-4">
                      <div className="flex items-center gap-1.5 text-gray-600 font-medium">
                        <Calendar className="w-3.5 h-3.5 opacity-40" />
                        {exp.date ? format(new Date(exp.date), 'd/M - p') : '--/--'}
                      </div>
                    </td>
                    <td className="px-4 py-4 whitespace-nowrap">
                      {exp.isFirstInLeg ? (
                        <span className="px-2 py-1 bg-blue-50 text-blue-600 rounded-lg font-bold text-[10px]">
                          Chặng {exp.legSequence}
                        </span>
                      ) : (
                        <div className="ml-6 border-l-2 border-blue-100/50 h-4" />
                      )}
                    </td>
                    <td className="px-4 py-4 font-semibold text-gray-800">
                      {exp.location?.name ? (
                        <div className="flex flex-col">
                          <span className="text-gray-900">{exp.description || 'Chi phí dịch vụ'}</span>
                          <span className="text-[10px] text-blue-500 font-bold uppercase tracking-tighter">@{exp.location.name}</span>
                        </div>
                      ) : (
                        exp.description || 'Không có mô tả'
                      )}
                    </td>
                    <td className="px-4 py-4 text-right font-black text-blue-600">
                      {Number(exp.amount).toLocaleString()}đ
                    </td>
                    <td className="px-4 py-4">
                      <div className="flex items-center gap-1.5 text-gray-600">
                        <User className="w-3.5 h-3.5 opacity-40" />
                        {exp.paidBy?.name || 'Chưa rõ'}
                      </div>
                    </td>
                    <td className="px-4 py-4 text-xs text-gray-400 italic">
                      {exp.note || '-'}
                    </td>
                  </tr>
                ))
              ) : (
                [1, 2, 3].map((i) => (
                  <tr key={`sample-${i}`} className="opacity-30 grayscale pointer-events-none select-none text-sm">
                    <td className="px-4 py-4 text-center font-bold text-gray-300">{i}</td>
                    <td className="px-4 py-4 text-gray-300">--/-- --:--</td>
                    <td className="px-4 py-4 text-gray-300">Chặng -</td>
                    <td className="px-4 py-4 text-gray-300 italic">Chưa có dữ liệu...</td>
                    <td className="px-4 py-4 text-right text-gray-300">0đ</td>
                    <td className="px-4 py-4 text-gray-300">Chưa rõ</td>
                    <td className="px-4 py-4 text-gray-200">-</td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>
      <div className="flex items-center gap-2 text-gray-400 text-xs px-2">
        <Info className="w-4 h-4" />
        <p>Chi phí được tự động tính toán dựa trên hóa đơn của các chặng.</p>
      </div>
    </div>
  );
};