import React, { useEffect, useState, useMemo, useCallback } from 'react';
import {
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as RechartsTooltip, Legend, ResponsiveContainer, LineChart, Line, AreaChart, Area, ComposedChart
} from 'recharts';
import {
  Activity, Zap, Sun, AlertTriangle, Cloud, Wind, DollarSign, Leaf, ArrowUpRight, Calendar, MapPin, CheckCircle, RefreshCw, TrendingUp, TrendingDown, X, Check
} from 'lucide-react';
import { dataService } from '../services/dataService';
import { IKPI, ITicket, IFinancialData, TicketStatus, IProject } from '../types';
import { useTheme } from '../App';
import { useAssetStore } from '../store/useAssetStore';

// Types
type DateRange = '7days' | '30days' | 'year' | 'custom';
interface StatCardProps {
  title: string;
  value: string | number;
  unit?: string;
  icon: React.ReactNode;
  color: string;
  trend?: string;
  trendValue?: number;
  isLoading?: boolean;
}

interface ChartColors {
  text: string;
  grid: string;
  tooltipBg: string;
  tooltipText: string;
}

// Extract StatCard component for reusability
const StatCard: React.FC<StatCardProps> = React.memo(({
  title,
  value,
  unit,
  icon,
  color,
  trend,
  trendValue,
  isLoading = false
}) => {
  const trendIcon = trendValue !== undefined
    ? (trendValue >= 0 ? <TrendingUp size={14} /> : <TrendingDown size={14} />)
    : <ArrowUpRight size={14} />;

  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-4 sm:p-5 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 hover:shadow-md transition-all">
      <div className="flex items-start justify-between">
        <div className="flex-1">
          <p className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wide">{title}</p>
          <div className="mt-2 flex items-baseline gap-2">
            {isLoading ? (
              <div className="animate-pulse bg-slate-200 dark:bg-slate-700 h-8 w-24 rounded"></div>
            ) : (
              <>
                <span className="text-2xl font-bold text-slate-800 dark:text-white">{value}</span>
                {unit && <span className="text-xs text-slate-500 dark:text-slate-400 font-medium">{unit}</span>}
              </>
            )}
          </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-2 sm:p-3 rounded-lg ${color} bg-opacity-10`}>
          {icon}
        </div>
      </div>
    </div>
  );
});

StatCard.displayName = 'StatCard';

const DashboardProject: React.FC = () => {
  const { isDarkMode } = useTheme();
  const { selectedProjectId } = useAssetStore();
  const [kpiData, setKpiData] = useState<IKPI[]>([]);
  const [tickets, setTickets] = useState<ITicket[]>([]);
  const [financials, setFinancialData] = useState<IFinancialData[]>([]);
  const [vcomAlarms, setVcomAlarms] = useState<any[]>([]);
  const [showAllAlarmsModal, setShowAllAlarmsModal] = useState(false);
  const [viewedAlerts, setViewedAlerts] = useState<Set<string>>(() => {
    // Load từ localStorage khi component mount
    if (typeof window !== 'undefined') {
      const saved = localStorage.getItem('viewedAlerts');
      if (saved) {
        try {
          return new Set(JSON.parse(saved));
        } catch (e) {
          return new Set();
        }
      }
    }
    return new Set();
  });
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [selectedProject, setSelectedProject] = useState<IProject | null>(null);
  const [dateRange, setDateRange] = useState<DateRange>('30days');
  const [lastUpdated, setLastUpdated] = useState<Date>(new Date());
  const [weatherData, setWeatherData] = useState<{
    temp: number;
    humidity: number;
    windSpeed: number;
    condition: string;
    irradiance: number;
    loading: boolean;
  }>({
    temp: 0,
    humidity: 0,
    windSpeed: 0,
    condition: 'N/A',
    irradiance: 0,
    loading: true,
  });

  // Fetch weather data from Open-Meteo API
  const fetchWeatherData = useCallback(async (project: IProject | null) => {
    if (!project?.location?.coordinates) {
      setWeatherData({
        temp: 0,
        humidity: 0,
        windSpeed: 0,
        condition: 'N/A',
        irradiance: 0,
        loading: false,
      });
      return;
    }

    try {
      const { lat, lng } = project.location.coordinates;
      
      // Open-Meteo API (free, no API key required)
      // Get current weather and solar radiation
      const weatherUrl = `https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lng}&current=temperature_2m,relative_humidity_2m,wind_speed_10m,weather_code&hourly=direct_radiation&timezone=Asia%2FHo_Chi_Minh`;
      
      const response = await fetch(weatherUrl);
      if (!response.ok) throw new Error('Failed to fetch weather data');
      
      const data = await response.json();
      
      if (data.current) {
        const current = data.current;
        const hourly = data.hourly;
        
        // Get current temperature (convert from Celsius if needed)
        const temp = Math.round(current.temperature_2m || 0);
        
        // Get humidity
        const humidity = Math.round(current.relative_humidity_2m || 0);
        
        // Get wind speed (convert from m/s to km/h)
        const windSpeedMs = current.wind_speed_10m || 0;
        const windSpeed = Math.round(windSpeedMs * 3.6); // m/s to km/h
        
        // Get current solar radiation (W/m²) - use current hour or latest available
        let irradiance = 0;
        if (hourly && hourly.direct_radiation && hourly.direct_radiation.length > 0) {
          // Get the latest available radiation value
          const now = new Date();
          const currentHour = now.getHours();
          const radiationIndex = Math.min(currentHour, hourly.direct_radiation.length - 1);
          irradiance = Math.round(hourly.direct_radiation[radiationIndex] || 0);
        }
        
        // Map weather code to condition (simplified)
        const weatherCode = current.weather_code || 0;
        let condition = 'N/A';
        if (weatherCode === 0) condition = 'Trời quang';
        else if (weatherCode <= 3) condition = 'Ít mây';
        else if (weatherCode <= 48) condition = 'Có mây';
        else if (weatherCode <= 67) condition = 'Có mưa';
        else if (weatherCode <= 77) condition = 'Có tuyết';
        else if (weatherCode <= 82) condition = 'Mưa rào';
        else if (weatherCode <= 86) condition = 'Tuyết rơi';
        else condition = 'Sương mù';
        
        setWeatherData({
          temp,
          humidity,
          windSpeed,
          condition,
          irradiance,
          loading: false,
        });
      } else {
        throw new Error('Invalid weather data format');
      }
    } catch (error) {
      console.warn('Failed to fetch weather data:', error);
      // Fallback to default values
      setWeatherData({
        temp: 0,
        humidity: 0,
        windSpeed: 0,
        condition: 'N/A',
        irradiance: 0,
        loading: false,
      });
    }
  }, []);

  // Fetch data function
  const fetchData = useCallback(async (isRefresh = false) => {
    if (!selectedProjectId) return;

    try {
      if (isRefresh) {
        setRefreshing(true);
      } else {
        setLoading(true);
      }
      setError(null);

      // Find the selected project object for display name/code
      const projects = await dataService.getProjects();
      const project = projects.find(p => p._id === selectedProjectId) || projects[0];
      setSelectedProject(project);
      
      // Fetch weather data if project has coordinates
      if (project?.location?.coordinates) {
        fetchWeatherData(project);
      }

      // Fetch all data in parallel
      // Use live KPI API (direct from V2 API, no MongoDB)
      // getKPIs() now uses live API by default
      const [kpis, tix, fin, alarms] = await Promise.all([
        dataService.getKPIs(selectedProjectId).catch(err => {
          console.warn('Failed to fetch KPIs from V2 API:', err);
          // Fallback to MongoDB if live API fails
          return dataService.getKPIsFromMongoDB(selectedProjectId).catch(() => []);
        }),
        dataService.getTickets(selectedProjectId).catch(err => {
          console.warn('Failed to fetch tickets:', err);
          return [];
        }),
        dataService.getFinancialData(selectedProjectId).catch(err => {
          console.warn('Failed to fetch financial data:', err);
          return { yearly: [], breakdown: [] };
        }),
        // Fetch VCOM alarms live (high and critical severity only)
        dataService.getVCOMAlarmsLive(selectedProjectId, 'open', 'high,critical').catch(err => {
          console.warn('Failed to fetch VCOM alarms:', err);
          return [];
        })
      ]);


      setKpiData(kpis || []);
      setTickets(tix || []);
      setVcomAlarms(alarms || []);
      
      // Weather data is fetched separately above
      
      setFinancialData(fin?.yearly || []);
      setLastUpdated(new Date());
    } catch (err: unknown) {
      const errorMessage = err instanceof Error ? err.message : 'Không thể tải dữ liệu dashboard. Vui lòng thử lại.';
      console.error('Failed to fetch dashboard data:', err);
      setError(errorMessage);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  }, [selectedProjectId, fetchWeatherData]);

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

  // Filter KPI data based on date range
  const filteredKpiData = useMemo(() => {
    if (!kpiData.length) {
      return [];
    }

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

    switch (dateRange) {
      case '7days':
        cutoffDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
        break;
      case '30days':
        cutoffDate = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
        break;
      case 'year':
        cutoffDate = new Date(now.getFullYear(), 0, 1);
        break;
      default:
        return kpiData;
    }

    const filtered = kpiData.filter(kpi => {
      // Normalize date from API/model (can be Date, string, timestamp, or missing).
      const rawDate = (kpi as any).date;
      if (rawDate === null || rawDate === undefined) return false;
      const kpiDate = new Date(rawDate);
      if (Number.isNaN(kpiDate.getTime())) return false;
      return kpiDate >= cutoffDate;
    });
    
    
    return filtered;
  }, [kpiData, dateRange]);

  // Memoized calculations for better performance
  const dashboardMetrics = useMemo(() => {
    if (!filteredKpiData.length) {
      return {
        currentPR: '0',
        currentAvail: '0',
        totalProduction: '0',
        co2Avoided: '0',
        prChange: 0,
        productionChange: 0,
      };
    }

    // Find the most recent record with valid availability data
    // Priority: availability > 0 > any record with production/PR > 0 > last record
    let current = filteredKpiData[filteredKpiData.length - 1];
    let bestAvailabilityRecord = null;
    
    // First pass: find the most recent record with availability > 0
    for (let i = filteredKpiData.length - 1; i >= 0; i--) {
      const record = filteredKpiData[i];
      const availability = typeof record.availability === 'number' ? record.availability : 0;
      
      if (availability > 0) {
        bestAvailabilityRecord = record;
        break; // Found the most recent record with availability > 0
      }
    }
    
    // Use the record with availability > 0 if found, otherwise use the last record
    if (bestAvailabilityRecord) {
      current = bestAvailabilityRecord;
    } else {
      // Fallback: find any record with production or PR > 0
      for (let i = filteredKpiData.length - 1; i >= 0; i--) {
        const record = filteredKpiData[i];
        const hasProduction = typeof record.production === 'number' && record.production > 0;
        const hasPR = typeof record.pr === 'number' && record.pr > 0;
        
        if (hasProduction || hasPR) {
          current = record;
          break;
        }
      }
    }
    
    // Find previous record for comparison (also with valid availability if possible)
    const currentIndex = filteredKpiData.indexOf(current);
    let previous = null;
    if (currentIndex > 0) {
      // Try to find previous record with availability > 0
      for (let i = currentIndex - 1; i >= 0; i--) {
        const record = filteredKpiData[i];
        const availability = typeof record.availability === 'number' ? record.availability : 0;
        
        if (availability > 0) {
          previous = record;
          break;
        }
      }
      
      // If no previous record with availability found, use the immediate previous record
      if (!previous && currentIndex > 0) {
        previous = filteredKpiData[currentIndex - 1];
      }
    }

    // Ensure all values are numbers (handle null/undefined)
    const currentPRValue = typeof current.pr === 'number' ? current.pr : 0;
    const currentAvailValue = typeof current.availability === 'number' ? current.availability : 0;
    const currentProductionValue = typeof current.production === 'number' ? current.production : 0;
    
    const currentPR = currentPRValue.toFixed(1);
    const currentAvail = currentAvailValue.toFixed(1);
    const totalProductionValue = filteredKpiData.reduce((acc, curr) => {
      const prod = typeof curr.production === 'number' ? curr.production : 0;
      return acc + prod;
    }, 0);
    const totalProduction = totalProductionValue.toFixed(0);
    const co2AvoidedValue = totalProductionValue * 0.8;
    const co2Avoided = co2AvoidedValue.toFixed(1);
    

    // Calculate trends
    const prChange = previous ? current.pr - previous.pr : 0;
    const productionChange = previous
      ? ((current.production - previous.production) / previous.production) * 100
      : 0;

    return {
      currentPR,
      currentAvail,
      totalProduction,
      co2Avoided,
      prChange,
      productionChange,
    };
  }, [filteredKpiData]);

  const financialMetrics = useMemo(() => {
    // Default electricity price (VND per kWh) - can be configured per project later
    const DEFAULT_ELECTRICITY_PRICE = 1800; // VND/kWh
    
    // If financial data is available, use it
    if (financials.length > 0) {
      const current = financials[financials.length - 1];
      const previous = financials.length > 1 ? financials[financials.length - 2] : null;
      const revenueChange = previous
        ? ((current.revenue - previous.revenue) / previous.revenue) * 100
        : 0;

      return {
        currentRevenue: current.revenue,
        revenueChange,
      };
    }

    // Fallback: Calculate revenue from production data
    if (filteredKpiData.length > 0) {
      // Calculate total production for current period (based on dateRange)
      const totalProduction = filteredKpiData.reduce((acc, curr) => {
        const prod = typeof curr.production === 'number' ? curr.production : 0;
        return acc + prod;
      }, 0);

      // Calculate revenue = total production (kWh) * price (VND/kWh)
      const calculatedRevenue = totalProduction * DEFAULT_ELECTRICITY_PRICE;

      // Calculate revenue change from previous period
      let revenueChange = 0;
      if (filteredKpiData.length > 1) {
        // Compare current period with previous period of same length
        const periodLength = Math.min(filteredKpiData.length, 30); // Use last 30 days or available data
        const currentPeriod = filteredKpiData.slice(-periodLength);
        const previousPeriod = filteredKpiData.slice(-periodLength * 2, -periodLength);
        
        if (previousPeriod.length > 0) {
          const currentPeriodRevenue = currentPeriod.reduce((acc, curr) => {
            const prod = typeof curr.production === 'number' ? curr.production : 0;
            return acc + prod;
          }, 0) * DEFAULT_ELECTRICITY_PRICE;
          
          const previousPeriodRevenue = previousPeriod.reduce((acc, curr) => {
            const prod = typeof curr.production === 'number' ? curr.production : 0;
            return acc + prod;
          }, 0) * DEFAULT_ELECTRICITY_PRICE;
          
          if (previousPeriodRevenue > 0) {
            revenueChange = ((currentPeriodRevenue - previousPeriodRevenue) / previousPeriodRevenue) * 100;
          }
        }
      }

      return {
        currentRevenue: calculatedRevenue,
        revenueChange,
      };
    }

    console.warn('[Dashboard] No financial data and no production data available for revenue calculation');
    return {
      currentRevenue: 0,
      revenueChange: 0,
    };
  }, [financials, filteredKpiData]);

  const criticalTickets = useMemo(() =>
    tickets.filter(t =>
      (t.priority === 'High' || t.priority === 'Critical') &&
      t.status !== TicketStatus.CLOSED
    ),
    [tickets]
  );

  // Combine critical tickets and VCOM alarms
  const allAlerts = useMemo(() => {
    const alerts: any[] = [];
    
    // Add critical tickets
    criticalTickets.forEach(ticket => {
      alerts.push({
        id: ticket._id,
        type: 'ticket',
        message: ticket.title,
        description: ticket.description,
        severity: ticket.priority === 'Critical' ? 'Critical' : ticket.priority === 'High' ? 'Warning' : 'Info',
        createdAt: new Date(ticket.createdAt),
        link: `/tickets/${ticket._id}`,
        source: 'ticket',
      });
    });
    
    // Add VCOM alarms
    vcomAlarms.forEach(alarm => {
      alerts.push({
        id: alarm._id || `vcom-${alarm.vcomAlarmId}`,
        type: 'vcom',
        message: alarm.message,
        description: alarm.componentName ? `Thiết bị: ${alarm.componentName}` : undefined,
        severity: alarm.severity,
        createdAt: alarm.createdAt ? new Date(alarm.createdAt) : new Date(),
        startedAt: alarm.startedAt ? new Date(alarm.startedAt) : undefined,
        duration: alarm.duration,
        affectedPower: alarm.affectedPower,
        losses: alarm.losses,
        link: alarm.link,
        source: 'vcom',
        alarmType: alarm.alarmType,
        componentType: alarm.componentType,
      });
    });
    
    // Sort by severity (Critical > Warning > Info) and then by date
    const severityOrder = { Critical: 3, Warning: 2, Info: 1 };
    return alerts.sort((a, b) => {
      const severityDiff = (severityOrder[b.severity as keyof typeof severityOrder] || 0) - 
                          (severityOrder[a.severity as keyof typeof severityOrder] || 0);
      if (severityDiff !== 0) return severityDiff;
      return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
    });
  }, [criticalTickets, vcomAlarms]);

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

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

  // Format number with thousand separators (Vietnamese format: 1.234.567)
  const formatNumber = useCallback((value: number | string, decimals: number = 0): string => {
    const numValue = typeof value === 'string' ? parseFloat(value) : value;
    if (isNaN(numValue)) return '0';
    
    return numValue.toLocaleString('vi-VN', {
      minimumFractionDigits: decimals,
      maximumFractionDigits: decimals,
    });
  }, []);

  // Format date for tooltip (only date, no time)
  const formatTooltipDate = useCallback((label: string | number | Date): string => {
    if (!label) return '';
    
    let date: Date;
    if (label instanceof Date) {
      date = label;
    } else if (typeof label === 'string') {
      date = new Date(label);
    } else if (typeof label === 'number') {
      date = new Date(label);
    } else {
      return String(label);
    }
    
    // Check if date is valid
    if (isNaN(date.getTime())) {
      return String(label);
    }
    
    // Format as DD/MM/YYYY
    const day = date.getDate().toString().padStart(2, '0');
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const year = date.getFullYear();
    
    return `${day}/${month}/${year}`;
  }, []);

  // Handle refresh
  const handleRefresh = useCallback(() => {
    fetchData(true);
  }, [fetchData]);

  // Handle date range change
  const handleDateRangeChange = useCallback((e: React.ChangeEvent<HTMLSelectElement>) => {
    setDateRange(e.target.value as DateRange);
  }, []);

  if (loading) {
    return (
      <div className="flex h-full items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
          <span className="ml-3 text-slate-500 dark:text-slate-400 mt-3 block">Đang tải dữ liệu tổng quan...</span>
        </div>
      </div>
    );
  }

  if (error) {
    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">
          <AlertTriangle 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>
    );
  }

  return (
    <div className="space-y-6 pb-10">
      {/* 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ổng quan dự án</h1>
          <p className="text-slate-500 dark:text-slate-400 text-sm mt-1">
            {selectedProject ? (
              <>Dự án: <span className="font-medium text-slate-700 dark:text-slate-300">{selectedProject.name}</span> ({selectedProject.code})</>
            ) : (
              <>Cập nhật lần cuối: {lastUpdated.toLocaleString('vi-VN')}</>
            )}
          </p>
        </div>
        <div className="flex items-center gap-3">
          {/* Refresh Button */}
          <button
            onClick={handleRefresh}
            disabled={refreshing}
            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 ${refreshing ? 'animate-spin' : ''}`}
            />
          </button>

          {/* Weather Widget */}
          <div className="flex items-center gap-3 bg-white dark:bg-slate-800 p-2 rounded-lg border border-slate-200 dark:border-slate-700 shadow-sm">
            <div className="flex items-center gap-2 px-3 border-r border-slate-200 dark:border-slate-700">
              <Cloud size={18} className="text-blue-400" />
              <div>
                <p className="text-xs text-slate-500 dark:text-slate-400">Thời tiết</p>
                <p className="text-sm font-bold text-slate-700 dark:text-slate-200">
                  {weatherData.loading ? '...' : weatherData.temp > 0 ? `${weatherData.temp}°C` : 'N/A'}
                </p>
              </div>
            </div>
            <div className="flex items-center gap-2 px-3 border-r border-slate-200 dark:border-slate-700">
              <Sun size={18} className="text-orange-400" />
              <div>
                <p className="text-xs text-slate-500 dark:text-slate-400">Bức xạ</p>
                <p className="text-sm font-bold text-slate-700 dark:text-slate-200">
                  {weatherData.loading ? '...' : weatherData.irradiance > 0 ? `${weatherData.irradiance} W/m²` : 'N/A'}
                </p>
              </div>
            </div>
            <div className="flex items-center gap-2 px-3">
              <Wind size={18} className="text-teal-400" />
              <div>
                <p className="text-xs text-slate-500 dark:text-slate-400">Gió</p>
                <p className="text-sm font-bold text-slate-700 dark:text-slate-200">
                  {weatherData.loading ? '...' : weatherData.windSpeed > 0 ? `${weatherData.windSpeed} km/h` : 'N/A'}
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Primary KPI Cards */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4 md:gap-6">
        <StatCard
          title="Hiệu suất (PR)"
          value={`${dashboardMetrics.currentPR}%`}
          icon={<Activity size={24} className="text-blue-600 dark:text-blue-400" />}
          color="bg-blue-500"
          trend={dashboardMetrics.prChange !== 0 ? `${formatTrend(dashboardMetrics.prChange)} so với kỳ trước` : undefined}
          trendValue={dashboardMetrics.prChange}
          isLoading={loading}
        />
        <StatCard
          title="Sản lượng"
          value={formatNumber(parseFloat(dashboardMetrics.totalProduction), 0)}
          unit="MWh"
          icon={<Zap size={24} className="text-orange-600 dark:text-orange-400" />}
          color="bg-orange-500"
          trend={dashboardMetrics.productionChange !== 0 ? `${formatTrend(dashboardMetrics.productionChange)} so với kỳ trước` : 'Dữ liệu hiện tại'}
          trendValue={dashboardMetrics.productionChange}
          isLoading={loading}
        />
        <StatCard
          title="Doanh thu tạm tính"
          value={formatNumber(financialMetrics.currentRevenue / 1000000000, 2)}
          unit="Tỷ VNĐ"
          icon={<DollarSign size={24} className="text-green-600 dark:text-green-400" />}
          color="bg-green-500"
          trend={financialMetrics.revenueChange !== 0 ? `${formatTrend(financialMetrics.revenueChange)} so với kỳ trước` : 'Dữ liệu hiện tại'}
          trendValue={financialMetrics.revenueChange}
          isLoading={loading}
        />
        <StatCard
          title="Giảm phát thải CO2"
          value={formatNumber(parseFloat(dashboardMetrics.co2Avoided), 1)}
          unit="Tấn"
          icon={<Leaf size={24} className="text-emerald-600 dark:text-emerald-400" />}
          color="bg-emerald-500"
          trend="Tương đương 400 cây xanh"
          isLoading={loading}
        />
      </div>

      {/* Main Content Grid */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Left Column: Charts */}
        <div className="lg:col-span-2 space-y-6">
          {/* Production Chart */}
          <div className="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-6">
              <div>
                <h3 className="text-lg font-bold text-slate-800 dark:text-white">Biểu đồ Sản lượng & Hiệu suất</h3>
                <p className="text-xs text-slate-500 dark:text-slate-400">
                  {dateRange === '7days' ? 'Dữ liệu 7 ngày gần nhất' :
                    dateRange === '30days' ? 'Dữ liệu 30 ngày gần nhất' :
                      dateRange === 'year' ? 'Dữ liệu năm hiện tại' :
                        'Dữ liệu tùy chọn'}
                </p>
              </div>
              <select
                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"
                value={dateRange}
                onChange={handleDateRangeChange}
                aria-label="Chọn khoảng thời gian"
              >
                <option value="7days">7 ngày qua</option>
                <option value="30days">30 ngày qua</option>
                <option value="year">Năm nay</option>
              </select>
            </div>
            <div className="h-80">
              {filteredKpiData.length > 0 ? (
                <ResponsiveContainer width="100%" height="100%" minWidth={0} debounce={100}>
                  <ComposedChart data={filteredKpiData} margin={{ top: 10, right: 10, left: 0, bottom: 0 }}>
                    <defs>
                      <linearGradient id="colorProd" x1="0" y1="0" x2="0" y2="1">
                        <stop offset="5%" stopColor="#3b82f6" stopOpacity={0.8} />
                        <stop offset="95%" stopColor="#3b82f6" stopOpacity={0} />
                      </linearGradient>
                    </defs>
                    <CartesianGrid strokeDasharray="3 3" vertical={false} stroke={chartColors.grid} />
                    <XAxis
                      dataKey="date"
                      tickFormatter={(str) => {
                        const date = new Date(str);
                        return `${date.getDate()}/${date.getMonth() + 1}`;
                      }}
                      tick={{ fontSize: 11, fill: chartColors.text }}
                      axisLine={false}
                      tickLine={false}
                      dy={10}
                    />
                    <YAxis
                      yAxisId="left"
                      orientation="left"
                      stroke={chartColors.text}
                      tick={{ fontSize: 11, fill: chartColors.text }}
                      axisLine={false}
                      tickLine={false}
                      label={{ value: 'MWh', angle: -90, position: 'insideLeft', style: { textAnchor: 'middle', fill: chartColors.text, fontSize: 11 } }}
                    />
                    <YAxis
                      yAxisId="right"
                      orientation="right"
                      stroke={chartColors.text}
                      tick={{ fontSize: 11, fill: chartColors.text }}
                      domain={[60, 100]}
                      axisLine={false}
                      tickLine={false}
                      label={{ value: 'PR %', angle: 90, position: 'insideRight', style: { textAnchor: 'middle', fill: chartColors.text, fontSize: 11 } }}
                    />
                    <RechartsTooltip
                      contentStyle={{
                        borderRadius: '8px',
                        border: 'none',
                        boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.1)',
                        backgroundColor: chartColors.tooltipBg,
                        color: chartColors.tooltipText
                      }}
                      labelStyle={{ color: chartColors.text, fontSize: '12px', marginBottom: '4px' }}
                      labelFormatter={formatTooltipDate}
                      formatter={(value: number, name: string) => [
                        typeof value === 'number' ? formatNumber(value, 2) : value,
                        name
                      ]}
                    />
                    <Legend wrapperStyle={{ paddingTop: '20px' }} />
                    <Bar yAxisId="left" dataKey="production" name="Sản lượng (MWh)" fill="url(#colorProd)" radius={[4, 4, 0, 0]} barSize={24} />
                    <Line yAxisId="right" type="monotone" dataKey="pr" name="PR (%)" stroke="#f97316" strokeWidth={3} dot={false} activeDot={{ r: 6 }} />
                  </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>

          {/* Specific Yield & Irradiation */}
          <div className="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-6">
              <h3 className="text-lg font-bold text-slate-800 dark:text-white">Tương quan Bức xạ & Năng suất</h3>
            </div>
            <div className="h-64">
              {filteredKpiData.length > 0 ? (
                <ResponsiveContainer width="100%" height="100%" minWidth={0} debounce={100}>
                  <AreaChart data={filteredKpiData} margin={{ top: 10, right: 10, left: 0, bottom: 0 }}>
                    <defs>
                      <linearGradient id="colorIrr" x1="0" y1="0" x2="0" y2="1">
                        <stop offset="5%" stopColor="#eab308" stopOpacity={0.3} />
                        <stop offset="95%" stopColor="#eab308" stopOpacity={0} />
                      </linearGradient>
                    </defs>
                    <XAxis
                      dataKey="date"
                      tickFormatter={(str) => {
                        const date = new Date(str);
                        return `${date.getDate()}/${date.getMonth() + 1}`;
                      }}
                      tick={{ fontSize: 11, fill: chartColors.text }}
                      axisLine={false}
                      tickLine={false}
                    />
                    <YAxis tick={{ fontSize: 11, fill: chartColors.text }} axisLine={false} tickLine={false} />
                    <CartesianGrid strokeDasharray="3 3" vertical={false} stroke={chartColors.grid} />
                    <RechartsTooltip
                      contentStyle={{
                        borderRadius: '8px',
                        backgroundColor: chartColors.tooltipBg,
                        color: chartColors.tooltipText,
                        border: `1px solid ${chartColors.grid}`
                      }}
                      labelStyle={{ color: chartColors.text, fontSize: '12px', marginBottom: '4px' }}
                      labelFormatter={formatTooltipDate}
                      formatter={(value: number, name: string) => [
                        typeof value === 'number' ? formatNumber(value, 2) : value,
                        name
                      ]}
                    />
                    <Legend />
                    <Area type="monotone" dataKey="irradiation" name="Bức xạ (kWh/m²)" stroke="#eab308" fill="url(#colorIrr)" strokeWidth={2} />
                    <Line type="monotone" dataKey="specificYield" name="Năng suất (kWh/kWp)" stroke="#10b981" strokeWidth={2} dot={false} />
                  </AreaChart>
                </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>
        </div>

        {/* Right Column: Alerts & Operational Status */}
        <div className="space-y-6">
          {/* Alert Widget */}
          <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-4 border-b border-slate-100 dark:border-slate-700 bg-red-50 dark:bg-red-900/20 flex justify-between items-center">
              <h3 className="font-bold text-red-800 dark:text-red-400 flex items-center gap-2">
                <AlertTriangle size={18} /> Cảnh báo quan trọng
              </h3>
              <span className="bg-red-200 dark:bg-red-800 text-red-800 dark:text-red-100 text-xs font-bold px-2 py-1 rounded-full">
                {allAlerts.length}
              </span>
            </div>
            <div className="divide-y divide-slate-100 dark:divide-slate-700 max-h-[300px] overflow-y-auto">
              {allAlerts.length > 0 ? (
                allAlerts.slice(0, 2).map(alert => (
                  <div 
                    key={alert.id} 
                    className="p-4 hover:bg-slate-50 dark:hover:bg-slate-700/50 transition-colors cursor-pointer"
                    onClick={() => {
                      if (alert.link) {
                        window.location.href = alert.link;
                      }
                    }}
                  >
                    <div className="flex justify-between items-start">
                      <span className={`text-xs font-bold px-2 py-0.5 rounded ${
                        alert.severity === 'Critical' 
                          ? 'text-red-700 bg-red-100 dark:bg-red-900/50 dark:text-red-300'
                          : alert.severity === 'Warning'
                          ? 'text-orange-700 bg-orange-100 dark:bg-orange-900/50 dark:text-orange-300'
                          : 'text-blue-700 bg-blue-100 dark:bg-blue-900/50 dark:text-blue-300'
                      }`}>
                        {alert.severity === 'Critical' ? 'Nghiêm trọng' : 
                         alert.severity === 'Warning' ? 'Cảnh báo' : 'Thông tin'}
                        {alert.source === 'vcom' && ' (VCOM)'}
                      </span>
                      <span className="text-xs text-slate-400">
                        {alert.createdAt.toLocaleDateString('vi-VN')}
                      </span>
                    </div>
                    <p className="text-sm font-semibold text-slate-800 dark:text-slate-200 mt-1 line-clamp-1">
                      {alert.message}
                    </p>
                    {alert.description && (
                      <p className="text-xs text-slate-500 dark:text-slate-400 mt-1 line-clamp-2">
                        {alert.description}
                      </p>
                    )}
                    {alert.source === 'vcom' && alert.affectedPower && (
                      <p className="text-xs text-slate-500 dark:text-slate-400 mt-1">
                        Ảnh hưởng: {alert.affectedPower.toFixed(1)}% công suất
                        {alert.losses && ` • Ước tính mất: ${alert.losses.toFixed(2)} kWh`}
                      </p>
                    )}
                  </div>
                ))
              ) : (
                <div className="p-8 text-center text-slate-500 dark:text-slate-400">
                  <CheckCircle size={32} className="mx-auto text-green-500 mb-2 opacity-50" />
                  <p>Hệ thống vận hành ổn định</p>
                </div>
              )}
            </div>
            {allAlerts.length > 0 && (
              <div className="p-3 bg-slate-50 dark:bg-slate-800 text-center border-t border-slate-100 dark:border-slate-700">
                <button 
                  onClick={() => setShowAllAlarmsModal(true)}
                  className="text-sm text-blue-600 dark:text-blue-400 font-medium hover:underline"
                >
                  Xem tất cả {allAlerts.length} cảnh báo
                </button>
              </div>
            )}
          </div>

          {/* Plant Info Widget */}
          <div className="bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 p-5">
            <h3 className="font-bold text-slate-800 dark:text-white mb-4">Thông tin nhà máy</h3>
            <div className="space-y-3">
              <div className="flex justify-between items-center py-2 border-b border-slate-50 dark:border-slate-700">
                <span className="text-sm text-slate-500 dark:text-slate-400 flex items-center gap-2">
                  <MapPin size={14} /> Địa điểm
                </span>
                <span className="text-sm font-medium text-slate-800 dark:text-slate-200 text-right max-w-[60%]">
                  {selectedProject?.location?.address || 'N/A'}
                </span>
              </div>
              <div className="flex justify-between items-center py-2 border-b border-slate-50 dark:border-slate-700">
                <span className="text-sm text-slate-500 dark:text-slate-400 flex items-center gap-2">
                  <Zap size={14} /> Công suất
                </span>
                <span className="text-sm font-medium text-slate-800 dark:text-slate-200">
                  {selectedProject?.capacityMWp || 0} MWp
                </span>
              </div>
              <div className="flex justify-between items-center py-2 border-b border-slate-50 dark:border-slate-700">
                <span className="text-sm text-slate-500 dark:text-slate-400 flex items-center gap-2">
                  <Calendar size={14} /> Ngày COD
                </span>
                <span className="text-sm font-medium text-slate-800 dark:text-slate-200">
                  {selectedProject?.commissioningDate
                    ? new Date(selectedProject.commissioningDate).toLocaleDateString('vi-VN')
                    : 'N/A'}
                </span>
              </div>
              <div className="flex justify-between items-center py-2">
                <span className="text-sm text-slate-500 dark:text-slate-400 flex items-center gap-2">
                  <Activity size={14} /> Trạng thái
                </span>
                <span className={`text-xs font-bold px-2 py-1 rounded-full ${selectedProject?.status === 'operational'
                    ? 'bg-green-100 dark:bg-green-900 text-green-700 dark:text-green-300'
                    : selectedProject?.status === 'construction'
                      ? 'bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300'
                      : 'bg-slate-100 dark:bg-slate-700 text-slate-700 dark:text-slate-300'
                  }`}>
                  {selectedProject?.status === 'operational' ? 'Đang vận hành' :
                    selectedProject?.status === 'construction' ? 'Đang xây dựng' :
                      selectedProject?.status === 'planning' ? 'Đang lập kế hoạch' : 'Ngừng hoạt động'}
                </span>
              </div>
            </div>
          </div>

          {/* Availability Gauge */}
          <div className="bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 p-5">
            <h3 className="font-bold text-slate-800 dark:text-white mb-2">Độ sẵn sàng (Availability)</h3>
            <div className="flex items-end gap-2 mb-1">
              <span className="text-3xl font-bold text-blue-600 dark:text-blue-400">
                {dashboardMetrics.currentAvail}%
              </span>
              <span className="text-sm text-slate-400 mb-1">Target: 99.5%</span>
            </div>
            <div className="w-full bg-slate-100 dark:bg-slate-700 rounded-full h-3 overflow-hidden">
              <div
                className="bg-blue-600 dark:bg-blue-500 h-3 rounded-full transition-all duration-300"
                style={{ width: `${Math.min(parseFloat(dashboardMetrics.currentAvail), 100)}%` }}
                role="progressbar"
                aria-valuenow={parseFloat(dashboardMetrics.currentAvail)}
                aria-valuemin={0}
                aria-valuemax={100}
              />
            </div>
            {parseFloat(dashboardMetrics.currentAvail) < 99.5 && (
              <p className="text-xs text-orange-600 dark:text-orange-400 mt-2">
                Dưới mục tiêu {(99.5 - parseFloat(dashboardMetrics.currentAvail)).toFixed(1)}%
              </p>
            )}
          </div>
        </div>
      </div>

      {/* Modal: Xem tất cả cảnh báo */}
      {showAllAlarmsModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className="bg-white dark:bg-slate-800 rounded-xl shadow-xl max-w-4xl w-full max-h-[90vh] flex flex-col">
            {/* Modal Header */}
            <div className="p-6 border-b border-slate-200 dark:border-slate-700 flex justify-between items-center">
              <h2 className="text-xl font-bold text-slate-800 dark:text-white flex items-center gap-2">
                <AlertTriangle size={24} className="text-red-600 dark:text-red-400" />
                Tất cả cảnh báo ({allAlerts.length})
              </h2>
              <button
                onClick={() => setShowAllAlarmsModal(false)}
                className="p-2 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg transition-colors"
              >
                <X size={24} className="text-slate-600 dark:text-slate-400" />
              </button>
            </div>

            {/* Modal Content */}
            <div className="flex-1 overflow-y-auto p-6">
              <div className="space-y-4">
                {allAlerts.length > 0 ? (
                  allAlerts.map((alert, index) => (
                    <div
                      key={alert.id}
                      className={`p-4 rounded-lg border ${
                        alert.severity === 'Critical'
                          ? 'bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800'
                          : alert.severity === 'Warning'
                          ? 'bg-orange-50 dark:bg-orange-900/20 border-orange-200 dark:border-orange-800'
                          : 'bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800'
                      }`}
                    >
                      <div className="flex justify-between items-start mb-2">
                        <div className="flex items-center gap-2">
                          <span className={`text-xs font-bold px-2 py-1 rounded ${
                            alert.severity === 'Critical'
                              ? 'text-red-700 bg-red-100 dark:bg-red-900/50 dark:text-red-300'
                              : alert.severity === 'Warning'
                              ? 'text-orange-700 bg-orange-100 dark:bg-orange-900/50 dark:text-orange-300'
                              : 'text-blue-700 bg-blue-100 dark:bg-blue-900/50 dark:text-blue-300'
                          }`}>
                            {alert.severity === 'Critical' ? 'Nghiêm trọng' :
                             alert.severity === 'Warning' ? 'Cảnh báo' : 'Thông tin'}
                          </span>
                          {alert.source === 'vcom' && (
                            <span className="text-xs text-slate-500 dark:text-slate-400 bg-slate-100 dark:bg-slate-700 px-2 py-1 rounded">
                              VCOM
                            </span>
                          )}
                          {alert.source === 'ticket' && (
                            <span className="text-xs text-slate-500 dark:text-slate-400 bg-slate-100 dark:bg-slate-700 px-2 py-1 rounded">
                              Phiếu yêu cầu
                            </span>
                          )}
                        </div>
                        <span className="text-xs text-slate-500 dark:text-slate-400">
                          {alert.createdAt.toLocaleDateString('vi-VN', {
                            day: '2-digit',
                            month: '2-digit',
                            year: 'numeric',
                            hour: '2-digit',
                            minute: '2-digit',
                          })}
                        </span>
                      </div>
                      
                      <p className="text-sm font-semibold text-slate-800 dark:text-slate-200 mb-1">
                        {alert.message}
                      </p>
                      
                      {alert.description && (
                        <p className="text-xs text-slate-600 dark:text-slate-400 mb-2">
                          {alert.description}
                        </p>
                      )}
                      
                      {alert.source === 'vcom' && (
                        <div className="mt-2 space-y-1">
                          {alert.componentType && (
                            <p className="text-xs text-slate-500 dark:text-slate-400">
                              Loại thiết bị: {alert.componentType}
                            </p>
                          )}
                          {alert.alarmType && (
                            <p className="text-xs text-slate-500 dark:text-slate-400">
                              Loại cảnh báo: {alert.alarmType}
                            </p>
                          )}
                          {alert.startedAt && (
                            <p className="text-xs text-slate-500 dark:text-slate-400">
                              Bắt đầu: {alert.startedAt.toLocaleDateString('vi-VN', {
                                day: '2-digit',
                                month: '2-digit',
                                year: 'numeric',
                                hour: '2-digit',
                                minute: '2-digit',
                              })}
                            </p>
                          )}
                          {alert.duration && (
                            <p className="text-xs text-slate-500 dark:text-slate-400">
                              Thời lượng: {alert.duration}
                            </p>
                          )}
                          {alert.affectedPower !== undefined && alert.affectedPower > 0 && (
                            <p className="text-xs text-slate-500 dark:text-slate-400">
                              Ảnh hưởng: {alert.affectedPower.toFixed(1)}% công suất
                            </p>
                          )}
                          {alert.losses !== undefined && alert.losses > 0 && (
                            <p className="text-xs text-slate-500 dark:text-slate-400">
                              Ước tính mất: {formatNumber(alert.losses, 2)} kWh
                            </p>
                          )}
                        </div>
                      )}
                      
                      <div className="mt-3 flex items-center justify-between gap-2">
                        {alert.link && (
                          <a
                            href={alert.link}
                            className="text-xs text-blue-600 dark:text-blue-400 hover:underline"
                            onClick={(e) => {
                              e.preventDefault();
                              window.location.href = alert.link;
                            }}
                          >
                            Xem chi tiết →
                          </a>
                        )}
                        <button
                          onClick={() => {
                            setViewedAlerts(prev => {
                              const newSet = new Set(prev);
                              newSet.add(alert.id);
                              // Lưu vào localStorage
                              if (typeof window !== 'undefined') {
                                localStorage.setItem('viewedAlerts', JSON.stringify(Array.from(newSet)));
                              }
                              return newSet;
                            });
                          }}
                          disabled={viewedAlerts.has(alert.id)}
                          className={`ml-auto flex items-center gap-1 px-3 py-1.5 text-xs font-medium rounded-lg transition-colors ${
                            viewedAlerts.has(alert.id)
                              ? 'bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400 cursor-not-allowed'
                              : 'bg-slate-100 dark:bg-slate-700 text-slate-700 dark:text-slate-300 hover:bg-slate-200 dark:hover:bg-slate-600'
                          }`}
                        >
                          {viewedAlerts.has(alert.id) ? (
                            <>
                              <Check size={14} />
                              Đã xem
                            </>
                          ) : (
                            'Đánh dấu đã xem'
                          )}
                        </button>
                      </div>
                    </div>
                  ))
                ) : (
                  <div className="p-8 text-center text-slate-500 dark:text-slate-400">
                    <CheckCircle size={48} className="mx-auto text-green-500 mb-4 opacity-50" />
                    <p className="text-lg font-medium">Không có cảnh báo nào</p>
                    <p className="text-sm mt-2">Hệ thống đang vận hành ổn định</p>
                  </div>
                )}
              </div>
            </div>

            {/* Modal Footer */}
            <div className="p-4 border-t border-slate-200 dark:border-slate-700 flex justify-end">
              <button
                onClick={() => setShowAllAlarmsModal(false)}
                className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
              >
                Đóng
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default DashboardProject;
