/**
 * Finance Page - Tài chính & ROI (Financial Modeling)
 * Link truy cập: https://aom.vuphong.com/dev/#/finance
 * 
 * Features:
 * - Financial data visualization with charts
 * - P&L report export (PDF)
 * - Excel export (planned)
 * - Date range filtering
 * - Trend analysis and comparisons
 * - Cost breakdown analysis
 */
import React, { useEffect, useState, useCallback, useMemo } from 'react';
import {
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, 
  LineChart, Line, ComposedChart, PieChart, Pie, Cell, AreaChart, Area
} from 'recharts';
import { dataService } from '../services/dataService';
import { IFinancialData, ICostBreakdown, IReport } from '../types';
import { 
  DollarSign, TrendingUp, TrendingDown, PieChart as PieChartIcon, Loader2, 
  RefreshCw, Download, FileSpreadsheet, Printer, Calendar, AlertCircle 
} from 'lucide-react';
import { useTheme } from '../App';
import { formatCurrency, formatNumber } from '../utils/formatters';
import { useAssetStore } from '../store/useAssetStore';
import { useUIStore } from '../store/useUIStore';

const COLORS = ['#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#64748b'];

// Date range types
type DateRange = 'all' | 'ytd' | '12months' | '6months' | '3months';

// StatCard Component - Extracted for reusability
interface StatCardProps {
  title: string;
  value: string;
  subtext?: string;
  icon: React.ReactNode;
  color: string;
  trend?: string;
  trendValue?: number;
  isLoading?: boolean;
}

const StatCard: React.FC<StatCardProps> = React.memo(({ 
  title, 
  value, 
  subtext, 
  icon, 
  color, 
  trend,
  trendValue,
  isLoading = false 
}) => {
  const trendIcon = trendValue !== undefined 
    ? (trendValue >= 0 ? <TrendingUp size={14} /> : <TrendingDown size={14} />)
    : null;
  
  const trendColor = trendValue !== undefined && trendValue < 0 
    ? 'text-red-600 dark:text-red-400' 
    : 'text-green-600 dark:text-green-400';

  return (
    <div className="bg-white dark:bg-slate-800 p-6 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 hover:shadow-md transition-all">
      <div className="flex items-center justify-between">
        <div className="flex-1">
          <p className="text-sm font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wide">{title}</p>
          <div className="mt-2">
            {isLoading ? (
              <div className="animate-pulse bg-slate-200 dark:bg-slate-700 h-8 w-32 rounded"></div>
            ) : (
              <>
                <span className="text-2xl font-bold text-slate-900 dark:text-white">{value}</span>
                {subtext && <p className="text-xs text-slate-400 dark:text-slate-500 mt-1">{subtext}</p>}
              </>
            )}
          </div>
          {trend && !isLoading && (
            <div className={`flex items-center mt-2 text-xs font-medium ${trendColor}`}>
              {trendIcon}
              <span className="ml-1">{trend}</span>
            </div>
          )}
        </div>
        <div className={`p-3 rounded-full ${color} bg-opacity-10`}>
          {icon}
        </div>
      </div>
    </div>
  );
});

StatCard.displayName = 'StatCard';

const Finance: React.FC = () => {
  const { isDarkMode } = useTheme();
  const { selectedProjectId } = useAssetStore();
  const { addNotification } = useUIStore();
  const [financialData, setFinancialData] = useState<IFinancialData[]>([]);
  const [costBreakdown, setCostBreakdown] = useState<ICostBreakdown[]>([]);
  const [loading, setLoading] = useState(true);
  const [isExporting, setIsExporting] = useState(false);
  const [generatedReportId, setGeneratedReportId] = useState<string | null>(null);
  const [dateRange, setDateRange] = useState<DateRange>('all');
  const [error, setError] = useState<string | null>(null);
  const [lastUpdated, setLastUpdated] = useState<Date>(new Date());

  // Fetch financial data
  const fetchFinancialData = useCallback(async () => {
    if (!selectedProjectId) {
      setLoading(false);
      return;
    }

    try {
      setLoading(true);
      setError(null);
      const data = await dataService.getFinancialData(selectedProjectId);
      setFinancialData(data.yearly);
      setCostBreakdown(data.breakdown);
      setLastUpdated(new Date());
    } catch (err: any) {
      const errorMessage = err instanceof Error ? err.message : 'Không thể tải dữ liệu tài chính';
      setError(errorMessage);
      addNotification('error', errorMessage);
      console.error('Failed to fetch financial data:', err);
    } finally {
      setLoading(false);
    }
  }, [selectedProjectId, addNotification]);

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

  // Filter financial data based on date range
  const filteredFinancialData = useMemo(() => {
    if (!financialData.length || dateRange === 'all') return financialData;

    const now = new Date();
    let cutoffDate: Date;

    switch (dateRange) {
      case 'ytd':
        cutoffDate = new Date(now.getFullYear(), 0, 1);
        break;
      case '12months':
        cutoffDate = new Date(now.getFullYear(), now.getMonth() - 12, now.getDate());
        break;
      case '6months':
        cutoffDate = new Date(now.getFullYear(), now.getMonth() - 6, now.getDate());
        break;
      case '3months':
        cutoffDate = new Date(now.getFullYear(), now.getMonth() - 3, now.getDate());
        break;
      default:
        return financialData;
    }

    return financialData.filter(item => {
      const itemDate = new Date(item.month + '-01');
      return itemDate >= cutoffDate;
    });
  }, [financialData, dateRange]);

  // Memoized calculations for better performance - MUST be defined before handlers that use it
  const financialMetrics = useMemo(() => {
    if (!filteredFinancialData.length) {
      return {
        totalRevenue: 0,
        totalOpex: 0,
        totalProfit: 0,
        currentROI: 0,
        profitMargin: 0,
        revenueChange: 0,
        opexChange: 0,
        profitChange: 0,
      };
    }

    const totalRevenue = filteredFinancialData.reduce((acc, curr) => acc + curr.revenue, 0);
    const totalOpex = filteredFinancialData.reduce((acc, curr) => acc + curr.opex, 0);
    const totalProfit = totalRevenue - totalOpex;
    const currentROI = filteredFinancialData[filteredFinancialData.length - 1].cumulativeROI;
    const profitMargin = totalRevenue > 0 ? (totalProfit / totalRevenue) * 100 : 0;

    // Calculate trends (compare with previous period)
    const currentPeriod = filteredFinancialData.slice(-3); // Last 3 months
    const previousPeriod = filteredFinancialData.slice(-6, -3); // Previous 3 months

    const currentPeriodRevenue = currentPeriod.reduce((acc, curr) => acc + curr.revenue, 0);
    const previousPeriodRevenue = previousPeriod.length > 0 
      ? previousPeriod.reduce((acc, curr) => acc + curr.revenue, 0) 
      : currentPeriodRevenue;

    const currentPeriodOpex = currentPeriod.reduce((acc, curr) => acc + curr.opex, 0);
    const previousPeriodOpex = previousPeriod.length > 0 
      ? previousPeriod.reduce((acc, curr) => acc + curr.opex, 0) 
      : currentPeriodOpex;

    const currentPeriodProfit = currentPeriodRevenue - currentPeriodOpex;
    const previousPeriodProfit = previousPeriodRevenue - previousPeriodOpex;

    const revenueChange = previousPeriodRevenue > 0 
      ? ((currentPeriodRevenue - previousPeriodRevenue) / previousPeriodRevenue) * 100 
      : 0;
    const opexChange = previousPeriodOpex > 0 
      ? ((currentPeriodOpex - previousPeriodOpex) / previousPeriodOpex) * 100 
      : 0;
    const profitChange = previousPeriodProfit !== 0 
      ? ((currentPeriodProfit - previousPeriodProfit) / Math.abs(previousPeriodProfit)) * 100 
      : 0;

    return {
      totalRevenue,
      totalOpex,
      totalProfit,
      currentROI,
      profitMargin,
      revenueChange,
      opexChange,
      profitChange,
    };
  }, [filteredFinancialData]);

  // Utility functions
  const sanitizeFilename = useCallback((filename: string, extension: string): string => {
    let sanitized = filename
      .replace(/[<>:"/\\|?*]/g, '_')
      .replace(/\s+/g, ' ')
      .trim();

    if (!sanitized || sanitized.length < 1) {
      sanitized = `BaoCao_PL_${Date.now()}`;
    }

    if (sanitized.length > 200) {
      sanitized = sanitized.substring(0, 200);
    }

    return `${sanitized}.${extension}`;
  }, []);

  const downloadFromBlob = useCallback((blob: Blob, filename: string): void => {
    if (!blob || blob.size === 0) {
      throw new Error('Blob is empty or invalid');
    }

    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = filename;
    link.style.display = 'none';
    document.body.appendChild(link);
    
    setTimeout(() => {
      try {
        link.click();
        setTimeout(() => {
          document.body.removeChild(link);
          URL.revokeObjectURL(url);
        }, 100);
      } catch (clickError: any) {
        document.body.removeChild(link);
        URL.revokeObjectURL(url);
        throw new Error(`Failed to trigger download: ${clickError.message}`);
      }
    }, 10);
  }, []);

  const formatTrend = useCallback((value: number): string => {
    const sign = value >= 0 ? '+' : '';
    return `${sign}${value.toFixed(1)}%`;
  }, []);

  const handleDownloadReport = useCallback(async (report: IReport): Promise<void> => {
    try {
      const extension = report.format.toLowerCase();
      const filename = sanitizeFilename(report.title, extension);
      
      const blob = await dataService.downloadReport(report._id);
      downloadFromBlob(blob, filename);
      addNotification('success', 'Tải xuống báo cáo thành công');
    } catch (error: any) {
      console.error('Download error:', error);
      const errorMessage = error.message || 'Vui lòng thử lại sau.';
      addNotification('error', `Lỗi khi tải xuống báo cáo: ${errorMessage}`);
    }
  }, [sanitizeFilename, downloadFromBlob, addNotification]);

  // Poll for report status
  useEffect(() => {
    if (!generatedReportId || !selectedProjectId) return;

    const checkReportStatus = async () => {
      try {
        const reports = await dataService.getReports(selectedProjectId);
        const report = reports.find(r => r._id === generatedReportId);
        
        if (report && report.status === 'Ready') {
          setIsExporting(false);
          setGeneratedReportId(null);
          await handleDownloadReport(report);
        } else if (report && report.status === 'Failed') {
          setIsExporting(false);
          setGeneratedReportId(null);
          addNotification('error', 'Tạo báo cáo thất bại. Vui lòng thử lại.');
        }
      } catch (error) {
        console.error('Error checking report status:', error);
      }
    };

    const interval = setInterval(checkReportStatus, 3000);
    return () => clearInterval(interval);
  }, [generatedReportId, selectedProjectId, handleDownloadReport, addNotification]);

  const handleExportPL = useCallback(async () => {
    if (!selectedProjectId) {
      addNotification('warning', 'Vui lòng chọn dự án trước khi xuất báo cáo.');
      return;
    }

    if (isExporting) return;

    setIsExporting(true);
    try {
      const financialDataForPDF = {
        financialData: filteredFinancialData,
        costBreakdown,
        totals: {
          totalRevenue: financialMetrics.totalRevenue,
          totalOpex: financialMetrics.totalOpex,
          totalProfit: financialMetrics.totalProfit,
          currentROI: financialMetrics.currentROI,
          profitMargin: Math.round(financialMetrics.profitMargin * 100) / 100
        }
      };

      const title = `Báo cáo P&L - ${new Date().toLocaleDateString('vi-VN')}`;
      await dataService.generateReport('Financial', title, selectedProjectId, null, financialDataForPDF);
      addNotification('info', 'Đang tạo báo cáo PDF...');
      
      setTimeout(async () => {
        try {
          const reports = await dataService.getReports(selectedProjectId);
          const newReport = reports
            .filter(r => r.type === 'Financial')
            .sort((a, b) => new Date(b.generatedDate).getTime() - new Date(a.generatedDate).getTime())[0];
          
          if (newReport) {
            if (newReport.status === 'Ready') {
              setIsExporting(false);
              await handleDownloadReport(newReport);
            } else {
              setGeneratedReportId(newReport._id);
            }
          } else {
            setIsExporting(false);
            addNotification('warning', 'Không tìm thấy báo cáo đã tạo. Vui lòng kiểm tra trong Trung tâm Báo cáo.');
          }
        } catch (error) {
          setIsExporting(false);
          console.error('Error checking for new report:', error);
          addNotification('error', 'Lỗi khi kiểm tra trạng thái báo cáo');
        }
      }, 2000);
    } catch (error: any) {
      setIsExporting(false);
      console.error('Export error:', error);
      addNotification('error', `Lỗi khi tạo báo cáo: ${error.message || 'Vui lòng thử lại sau.'}`);
    }
  }, [selectedProjectId, isExporting, filteredFinancialData, costBreakdown, financialMetrics, handleDownloadReport, addNotification]);

  const handleExportExcel = useCallback(() => {
    // TODO: Implement Excel export
    addNotification('info', 'Tính năng xuất Excel đang được phát triển');
  }, [addNotification]);

  const handlePrint = useCallback(() => {
    window.print();
  }, []);

  const handleRefresh = useCallback(() => {
    fetchFinancialData();
  }, [fetchFinancialData]);

  // Chart Colors based on theme - memoized
  const chartColors = useMemo(() => ({
    text: isDarkMode ? '#94a3b8' : '#64748b',
    grid: isDarkMode ? '#334155' : '#e2e8f0',
    tooltipBg: isDarkMode ? '#1e293b' : '#ffffff',
    tooltipText: isDarkMode ? '#f8fafc' : '#1e293b',
  }), [isDarkMode]);

  // Loading state
  if (loading) {
    return (
      <div className="flex h-full items-center justify-center">
        <div className="text-center">
          <Loader2 className="animate-spin h-8 w-8 text-blue-600 mx-auto mb-4" />
          <span className="text-slate-500 dark:text-slate-400">Đang tải dữ liệu tài chính...</span>
        </div>
      </div>
    );
  }

  // Error state
  if (error && !financialData.length) {
    return (
      <div className="flex h-full items-center justify-center">
        <div className="text-center max-w-md p-6 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-xl">
          <AlertCircle size={48} className="mx-auto text-red-600 dark:text-red-400 mb-4" />
          <h3 className="text-lg font-bold text-red-800 dark:text-red-300 mb-2">Lỗi tải dữ liệu</h3>
          <p className="text-sm text-red-600 dark:text-red-400 mb-4">{error}</p>
          <button
            onClick={handleRefresh}
            className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors"
          >
            Thử lại
          </button>
        </div>
      </div>
    );
  }

  // Empty state
  if (!selectedProjectId) {
    return (
      <div className="flex h-full items-center justify-center">
        <div className="text-center max-w-md p-6">
          <AlertCircle size={48} className="mx-auto text-slate-400 mb-4" />
          <h3 className="text-lg font-bold text-slate-800 dark:text-white mb-2">Chưa chọn dự án</h3>
          <p className="text-sm text-slate-500 dark:text-slate-400">Vui lòng chọn dự án để xem dữ liệu tài chính</p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header Section */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
        <div>
          <h1 className="text-2xl font-bold text-slate-800 dark:text-white">Tài chính & ROI (Financial Modeling)</h1>
          <p className="text-slate-500 dark:text-slate-400 text-sm mt-1">
            Cập nhật lần cuối: {lastUpdated.toLocaleString('vi-VN')}
          </p>
        </div>
        <div className="flex items-center gap-3 flex-wrap">
          {/* Date Range Filter */}
          <select
            value={dateRange}
            onChange={(e) => setDateRange(e.target.value as DateRange)}
            className="text-sm border-slate-300 dark:border-slate-600 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 p-2 bg-white dark:bg-slate-700 text-slate-700 dark:text-white"
            aria-label="Chọn khoảng thời gian"
          >
            <option value="all">Tất cả</option>
            <option value="ytd">Năm nay (YTD)</option>
            <option value="12months">12 tháng qua</option>
            <option value="6months">6 tháng qua</option>
            <option value="3months">3 tháng qua</option>
          </select>

          {/* Refresh Button */}
          <button
            onClick={handleRefresh}
            disabled={loading}
            className="p-2 rounded-lg border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 hover:bg-slate-50 dark:hover:bg-slate-700 transition-colors disabled:opacity-50"
            title="Làm mới dữ liệu"
            aria-label="Làm mới dữ liệu"
          >
            <RefreshCw 
              size={18} 
              className={`text-slate-600 dark:text-slate-400 ${loading ? 'animate-spin' : ''}`} 
            />
          </button>

          {/* Print Button */}
          <button
            onClick={handlePrint}
            className="p-2 rounded-lg border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 hover:bg-slate-50 dark:hover:bg-slate-700 transition-colors"
            title="In trang"
            aria-label="In trang"
          >
            <Printer size={18} className="text-slate-600 dark:text-slate-400" />
          </button>

          {/* Export Buttons */}
          <div className="flex gap-2">
            <button
              onClick={handleExportExcel}
              disabled={!selectedProjectId}
              className="px-3 py-2 rounded-lg text-sm font-medium flex items-center gap-2 transition-colors border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 hover:bg-slate-50 dark:hover:bg-slate-700 text-slate-700 dark:text-slate-300 disabled:opacity-50 disabled:cursor-not-allowed"
              title="Xuất Excel"
            >
              <FileSpreadsheet size={16} /> Excel
            </button>
            <button 
              onClick={handleExportPL}
              disabled={isExporting || !selectedProjectId}
              className={`px-4 py-2 rounded-lg text-sm font-medium flex items-center gap-2 transition-colors ${
                isExporting || !selectedProjectId
                  ? 'bg-slate-200 dark:bg-slate-700 text-slate-400 dark:text-slate-500 cursor-not-allowed'
                  : 'bg-blue-600 text-white hover:bg-blue-700'
              }`}
              title={!selectedProjectId ? 'Vui lòng chọn dự án' : isExporting ? 'Đang tạo báo cáo...' : 'Xuất báo cáo P&L PDF'}
            >
              {isExporting ? (
                <>
                  <Loader2 size={16} className="animate-spin" /> Đang tạo...
                </>
              ) : (
                <>
                  <Download size={16} /> PDF
                </>
              )}
            </button>
          </div>
        </div>
      </div>

      {/* KPI Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <StatCard
          title="Tổng doanh thu"
          value={`${formatNumber(financialMetrics.totalRevenue, 1)} Tỷ VNĐ`}
          subtext={dateRange === 'all' ? 'Tổng doanh thu bán điện' : `Doanh thu ${dateRange === 'ytd' ? 'năm nay' : dateRange === '12months' ? '12 tháng' : dateRange === '6months' ? '6 tháng' : '3 tháng'}`}
          icon={<DollarSign size={24} className="text-blue-600 dark:text-blue-400" />}
          color="bg-blue-500"
          trend={financialMetrics.revenueChange !== 0 ? `${formatTrend(financialMetrics.revenueChange)} so với kỳ trước` : undefined}
          trendValue={financialMetrics.revenueChange}
          isLoading={loading}
        />
        <StatCard
          title="Chi phí vận hành (OPEX)"
          value={`${formatNumber(financialMetrics.totalOpex, 1)} Tỷ VNĐ`}
          subtext="Bao gồm bảo trì, nhân sự, bảo hiểm"
          icon={<TrendingDown size={24} className="text-red-600 dark:text-red-400" />}
          color="bg-red-500"
          trend={financialMetrics.opexChange !== 0 ? `${formatTrend(financialMetrics.opexChange)} so với kỳ trước` : undefined}
          trendValue={-financialMetrics.opexChange}
          isLoading={loading}
        />
        <StatCard
          title="Lợi nhuận ròng (Net)"
          value={`${formatNumber(financialMetrics.totalProfit, 1)} Tỷ VNĐ`}
          subtext={`Biên lợi nhuận: ${financialMetrics.profitMargin.toFixed(1)}%`}
          icon={<TrendingUp size={24} className="text-green-600 dark:text-green-400" />}
          color="bg-green-500"
          trend={financialMetrics.profitChange !== 0 ? `${formatTrend(financialMetrics.profitChange)} so với kỳ trước` : undefined}
          trendValue={financialMetrics.profitChange}
          isLoading={loading}
        />
        <StatCard
          title="ROI Lũy kế"
          value={`${financialMetrics.currentROI.toFixed(1)}%`}
          subtext="Tỷ suất hoàn vốn đầu tư"
          icon={<PieChartIcon size={24} className="text-purple-600 dark:text-purple-400" />}
          color="bg-purple-500"
          isLoading={loading}
        />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Main Chart: Revenue vs Opex */}
        <div className="lg:col-span-2 bg-white dark:bg-slate-800 p-6 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700">
          <div className="flex justify-between items-center mb-4">
            <h3 className="text-lg font-bold text-slate-800 dark:text-white">Doanh thu & Chi phí (Theo tháng)</h3>
            {filteredFinancialData.length !== financialData.length && (
              <span className="text-xs text-slate-500 dark:text-slate-400">
                Đang hiển thị {filteredFinancialData.length} / {financialData.length} tháng
              </span>
            )}
          </div>
          <div className="h-80">
            {filteredFinancialData.length > 0 ? (
              <ResponsiveContainer width="100%" height="100%" minWidth={0}>
                <ComposedChart data={filteredFinancialData}>
                  <CartesianGrid strokeDasharray="3 3" vertical={false} stroke={chartColors.grid} />
                  <XAxis 
                    dataKey="month" 
                    tick={{ fontSize: 12, fill: chartColors.text }} 
                    axisLine={false} 
                    tickLine={false}
                    tickFormatter={(value) => {
                      const date = new Date(value + '-01');
                      return `${date.getMonth() + 1}/${date.getFullYear().toString().slice(-2)}`;
                    }}
                  />
                  <YAxis 
                    yAxisId="left" 
                    orientation="left" 
                    stroke={chartColors.text} 
                    tick={{ fontSize: 12, fill: chartColors.text }} 
                    label={{ value: 'Tỷ VNĐ', angle: -90, position: 'insideLeft', fill: chartColors.text }} 
                    axisLine={false} 
                    tickLine={false} 
                  />
                  <YAxis 
                    yAxisId="right" 
                    orientation="right" 
                    stroke={chartColors.text} 
                    tick={{ fontSize: 12, fill: chartColors.text }} 
                    unit="%" 
                    domain={[0, 30]} 
                    axisLine={false} 
                    tickLine={false} 
                  />
                  <Tooltip
                    contentStyle={{ 
                      borderRadius: '8px', 
                      border: 'none', 
                      boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.1)', 
                      backgroundColor: chartColors.tooltipBg, 
                      color: chartColors.tooltipText 
                    }}
                    itemStyle={{ color: chartColors.tooltipText }}
                    formatter={(value: number, name: string) => [
                      typeof value === 'number' ? formatNumber(value, 2) : value,
                      name
                    ]}
                  />
                  <Legend />
                  <Bar yAxisId="left" dataKey="revenue" name="Doanh thu" fill="#3b82f6" barSize={20} radius={[4, 4, 0, 0]} />
                  <Bar yAxisId="left" dataKey="opex" name="OPEX" fill="#ef4444" barSize={20} radius={[4, 4, 0, 0]} />
                  <Line yAxisId="right" type="monotone" dataKey="cumulativeROI" name="ROI Lũy kế (%)" stroke="#10b981" strokeWidth={2} dot={{ r: 4 }} />
                </ComposedChart>
              </ResponsiveContainer>
            ) : (
              <div className="h-full flex items-center justify-center text-slate-500 dark:text-slate-400">
                Không có dữ liệu cho khoảng thời gian đã chọn
              </div>
            )}
          </div>
        </div>

        {/* Pie Chart: Cost Structure */}
        <div className="bg-white dark:bg-slate-800 p-6 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700">
          <h3 className="text-lg font-bold text-slate-800 dark:text-white mb-4">Cơ cấu chi phí (Cost Breakdown)</h3>
          <div className="h-80 flex flex-col justify-center">
            {costBreakdown.length > 0 ? (
              <ResponsiveContainer width="100%" height="100%" minWidth={0}>
                <PieChart>
                  <Pie
                    data={costBreakdown as any[]}
                    cx="50%"
                    cy="50%"
                    innerRadius={60}
                    outerRadius={80}
                    fill="#8884d8"
                    paddingAngle={5}
                    dataKey="value"
                    label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                  >
                    {costBreakdown.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                    ))}
                  </Pie>
                  <Tooltip
                    contentStyle={{ 
                      borderRadius: '8px', 
                      border: 'none', 
                      boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.1)', 
                      backgroundColor: chartColors.tooltipBg, 
                      color: chartColors.tooltipText 
                    }}
                    itemStyle={{ color: chartColors.tooltipText }}
                    formatter={(value: number) => `${formatNumber(value, 1)}%`}
                  />
                </PieChart>
              </ResponsiveContainer>
            ) : (
              <div className="h-full flex items-center justify-center text-slate-500 dark:text-slate-400">
                Không có dữ liệu
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Financial Table */}
      <div className="bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden">
        <div className="p-6 border-b border-slate-200 dark:border-slate-700 flex justify-between items-center">
          <h3 className="text-lg font-bold text-slate-800 dark:text-white">Chi tiết dòng tiền (Cashflow)</h3>
          {filteredFinancialData.length !== financialData.length && (
            <span className="text-xs text-slate-500 dark:text-slate-400">
              Hiển thị {filteredFinancialData.length} / {financialData.length} bản ghi
            </span>
          )}
        </div>
        <div className="overflow-x-auto">
          {filteredFinancialData.length > 0 ? (
            <table className="min-w-full divide-y divide-slate-200 dark:divide-slate-700">
              <thead className="bg-slate-50 dark:bg-slate-700/50">
                <tr>
                  <th className="px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider whitespace-nowrap">Tháng</th>
                  <th className="px-6 py-3 text-right text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider whitespace-nowrap">Doanh thu (Tỷ)</th>
                  <th className="px-6 py-3 text-right text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider whitespace-nowrap">OPEX (Tỷ)</th>
                  <th className="px-6 py-3 text-right text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider whitespace-nowrap">Lợi nhuận ròng (Tỷ)</th>
                  <th className="px-6 py-3 text-right text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider whitespace-nowrap">ROI Lũy kế (%)</th>
                </tr>
              </thead>
              <tbody className="bg-white dark:bg-slate-800 divide-y divide-slate-200 dark:divide-slate-700">
                {filteredFinancialData.map((row, idx) => (
                  <tr key={idx} className="hover:bg-slate-50 dark:hover:bg-slate-700/50 transition-colors">
                    <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-slate-900 dark:text-white">
                      {new Date(row.month + '-01').toLocaleDateString('vi-VN', { month: 'short', year: 'numeric' })}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-right text-blue-600 dark:text-blue-400 font-medium">{formatNumber(row.revenue)}</td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-right text-red-600 dark:text-red-400">{formatNumber(row.opex)}</td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-right text-green-600 dark:text-green-400 font-bold">{formatNumber(row.netProfit)}</td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-right text-slate-700 dark:text-slate-300">{row.cumulativeROI.toFixed(1)}%</td>
                  </tr>
                ))}
              </tbody>
              <tfoot className="bg-slate-50 dark:bg-slate-700/50 font-bold">
                <tr>
                  <td className="px-6 py-3 text-sm text-slate-900 dark:text-white">Tổng cộng</td>
                  <td className="px-6 py-3 text-sm text-right text-blue-700 dark:text-blue-300">{formatNumber(financialMetrics.totalRevenue)}</td>
                  <td className="px-6 py-3 text-sm text-right text-red-700 dark:text-red-300">{formatNumber(financialMetrics.totalOpex)}</td>
                  <td className="px-6 py-3 text-sm text-right text-green-700 dark:text-green-300">{formatNumber(financialMetrics.totalProfit)}</td>
                  <td className="px-6 py-3 text-sm text-right text-slate-700 dark:text-slate-300">-</td>
                </tr>
              </tfoot>
            </table>
          ) : (
            <div className="p-8 text-center text-slate-500 dark:text-slate-400">
              Không có dữ liệu cho khoảng thời gian đã chọn
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default Finance;
