import React, { useState, useMemo } from 'react';
import { motion } from 'framer-motion';
import { 
  BarChart3, 
  TrendingUp, 
  TrendingDown,
  Users, 
  Briefcase, 
  Download, 
  Calendar, 
  Filter, 
  Search, 
  ArrowUpRight, 
  ArrowDownRight, 
  PieChart as PieChartIcon,
  FileText,
  MoreHorizontal,
  RefreshCcw,
  ChevronRight,
  Plus,
  DollarSign,
  Clock,
  CheckSquare
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';
import { 
  BarChart, 
  Bar, 
  XAxis, 
  YAxis, 
  CartesianGrid, 
  Tooltip, 
  ResponsiveContainer, 
  LineChart, 
  Line, 
  PieChart, 
  Pie, 
  Cell,
  Legend
} from 'recharts';
import { useApp, Project, Task, Expense, Engineer, Candidate, JobOpening, Client } from '@/context/AppContext';

const DEPARTMENT_COLORS: Record<string, string> = {
  'Engineering': 'hsl(var(--primary))',
  'Sales': '#3b82f6',
  'Marketing': '#ec4899',
  'HR': '#f59e0b',
  'Finance': '#10b981',
  'Operations': '#8b5cf6',
  'Support': '#06b6d4',
};

const CATEGORY_COLORS: Record<string, string> = {
  'Travel': '#3b82f6',
  'Materials': '#f59e0b',
  'Equipment': '#ef4444',
  'Software': '#8b5cf6',
  'Office': '#10b981',
  'Marketing': '#ec4899',
  'Other': '#94a3b8',
};

const STATUS_COLORS: Record<string, string> = {
  'Applied': '#94a3b8',
  'Screening': '#3b82f6',
  'Interview': '#8b5cf6',
  'Offer': '#10b981',
  'Hired': 'hsl(var(--primary))',
  'Rejected': '#ef4444',
};

const RECENT_REPORTS = [
  { id: 'REP-001', name: 'Monthly Financial Summary', type: 'Financial', date: '2026-03-31', status: 'Generated' },
  { id: 'REP-002', name: 'Employee Performance Review', type: 'HR', date: '2026-03-30', status: 'Generated' },
  { id: 'REP-003', name: 'Project Milestone Analysis', type: 'Operations', date: '2026-03-28', status: 'Draft' },
  { id: 'REP-004', name: 'Sales Pipeline Forecast', type: 'Sales', date: '2026-03-25', status: 'Generated' },
];

export function Reports() {
  const { projects, tasks, engineers, expenses, candidates, jobs, clients } = useApp();
  const [dateRange, setDateRange] = useState('Last 6 Months');
  const [searchQuery, setSearchQuery] = useState('');
  const [reports, setReports] = useState(RECENT_REPORTS);

  const filteredProjects = useMemo(() => {
    const now = new Date();
    let cutoff = new Date();
    
    if (dateRange === 'Last 30 Days') cutoff.setDate(now.getDate() - 30);
    else if (dateRange === 'Last 3 Months') cutoff.setMonth(now.getMonth() - 3);
    else if (dateRange === 'Last 6 Months') cutoff.setMonth(now.getMonth() - 6);
    else if (dateRange === 'Last Year') cutoff.setFullYear(now.getFullYear() - 1);
    else return projects;

    return projects.filter(p => {
      const date = p.issueDate ? new Date(p.issueDate) : new Date();
      return date >= cutoff;
    });
  }, [projects, dateRange]);

  const recruitmentStats = useMemo(() => {
    const statusCounts = {
      'Applied': 0,
      'Screening': 0,
      'Interview': 0,
      'Offer': 0,
      'Hired': 0,
      'Rejected': 0
    };

    candidates.forEach(c => {
      if (statusCounts[c.status as keyof typeof statusCounts] !== undefined) {
        statusCounts[c.status as keyof typeof statusCounts]++;
      }
    });

    return Object.entries(statusCounts).map(([name, value]) => ({
      name,
      value,
      color: STATUS_COLORS[name as keyof typeof STATUS_COLORS]
    }));
  }, [candidates]);

  const clientRevenueData = useMemo(() => {
    const clientMap = new Map<string, number>();
    
    projects.forEach(p => {
      const revenue = p.clientTotalAmount || 0;
      clientMap.set(p.client, (clientMap.get(p.client) || 0) + revenue);
    });

    return Array.from(clientMap.entries())
      .map(([name, value]) => ({ name, value }))
      .sort((a, b) => b.value - a.value)
      .slice(0, 5);
  }, [projects]);

  const engineerUtilization = useMemo(() => {
    const total = engineers.length;
    if (total === 0) return 0;
    
    const assigned = engineers.filter(eng => 
      projects.some(p => p.assignedTo === eng.name && p.status !== 'Completed' && p.status !== 'Cancelled')
    ).length;

    return Math.round((assigned / total) * 100);
  }, [engineers, projects]);

  const departmentalStats = useMemo(() => {
    const deptMap = new Map<string, { count: number, completed: number, totalTasks: number, completedTasks: number }>();
    
    engineers.forEach(eng => {
      if (!deptMap.has(eng.department)) {
        deptMap.set(eng.department, { count: 0, completed: 0, totalTasks: 0, completedTasks: 0 });
      }
      const dept = deptMap.get(eng.department)!;
      dept.count++;
      
      // Count completed projects for this engineer
      const engProjects = projects.filter(p => p.assignedTo === eng.name);
      const completed = engProjects.filter(p => p.status === 'Completed').length;
      dept.completed += completed;

      // Count tasks for this engineer
      const engTasks = tasks.filter(t => t.assignee === eng.name);
      dept.totalTasks += engTasks.length;
      dept.completedTasks += engTasks.filter(t => t.status === 'Completed').length;
    });

    return Array.from(deptMap.entries()).map(([name, data]) => ({
      name,
      efficiency: data.totalTasks > 0 ? Math.round((data.completedTasks / data.totalTasks) * 100) : 0,
      quality: data.count > 0 ? Math.min(100, 80 + Math.round((data.completed / data.count) * 20)) : 85,
      color: DEPARTMENT_COLORS[name] || '#94a3b8'
    })).sort((a, b) => b.efficiency - a.efficiency);
  }, [engineers, projects, tasks]);

  const expenseBreakdown = useMemo(() => {
    const catMap = new Map<string, number>();
    expenses.filter(e => e.status === 'Approved').forEach(e => {
      catMap.set(e.category, (catMap.get(e.category) || 0) + e.amount);
    });

    return Array.from(catMap.entries()).map(([name, value]) => ({
      name,
      value,
      color: CATEGORY_COLORS[name] || '#94a3b8'
    })).sort((a, b) => b.value - a.value);
  }, [expenses]);

  const taskTrends = useMemo(() => {
    const now = new Date();
    const trends = [];
    for (let i = 5; i >= 0; i--) {
      const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
      const mStr = d.toLocaleString('default', { month: 'short' });
      const mFull = `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}`;
      
      const monthTasks = tasks.filter(t => t.dueDate.startsWith(mFull) || (t.completedDate && t.completedDate.startsWith(mFull)));
      const completed = monthTasks.filter(t => t.status === 'Completed').length;
      const total = monthTasks.length;

      trends.push({
        month: mStr,
        completed,
        total,
        rate: total > 0 ? Math.round((completed / total) * 100) : 0
      });
    }
    return trends;
  }, [tasks]);

  const parseTotalTime = (timeStr?: string) => {
    if (!timeStr) return 0;
    const hoursMatch = timeStr.match(/(\d+)h/);
    const minsMatch = timeStr.match(/(\d+)m/);
    const hours = hoursMatch ? parseInt(hoursMatch[1]) : 0;
    const mins = minsMatch ? parseInt(minsMatch[1]) : 0;
    return hours + mins / 60;
  };

  const stats = useMemo(() => {
    let totalRevenue = 0;
    let totalExpenses = 0;
    let pendingAmount = 0;
    let pendingCount = 0;
    
    const now = new Date();
    const currentMonthStr = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}`;
    let currentMonthInflow = 0;
    let currentMonthOutflow = 0;

    // Monthly data for chart (last 6 months)
    const monthlyMap = new Map<string, { revenue: number, expenses: number }>();
    for (let i = 5; i >= 0; i--) {
      const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
      const mStr = `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}`;
      monthlyMap.set(mStr, { revenue: 0, expenses: 0 });
    }

    filteredProjects.forEach(p => {
      const hours = parseTotalTime(p.totalTime);
      
      // Internal/Engineer rates (Expenses)
      const hourlyTotal = (p.hourlyRate || 0) * hours;
      const internalAmount = p.totalAmount && p.totalAmount > 0 ? p.totalAmount : 
        (hourlyTotal + (p.travelCost || 0) + (p.materialCost || 0) + (p.halfDayRate || 0) + (p.fullDayRate || 0) + (p.monthlyRate || 0));
      
      // Client rates (Revenue)
      const clientHourlyTotal = (p.clientHourlyRate || 0) * hours;
      const clientAmount = p.clientTotalAmount && p.clientTotalAmount > 0 ? p.clientTotalAmount : 
        (clientHourlyTotal + (p.clientTravelCost || 0) + (p.clientMaterialCost || 0) + (p.clientHalfDayRate || 0) + (p.clientFullDayRate || 0) + (p.clientMonthlyRate || 0));

      totalRevenue += clientAmount;
      totalExpenses += internalAmount;

      const pMonth = p.issuedMonth || (p.issueDate ? p.issueDate.substring(0, 7) : '');
      
      if (pMonth === currentMonthStr) {
        if (p.clientStatus === 'Completed') currentMonthInflow += clientAmount;
        if (p.status === 'Completed') currentMonthOutflow += internalAmount;
      }

      if (monthlyMap.has(pMonth)) {
        const mData = monthlyMap.get(pMonth)!;
        mData.revenue += clientAmount;
        mData.expenses += internalAmount;
      }

      if (p.clientStatus !== 'Completed' && p.clientStatus !== 'Cancelled') {
        pendingAmount += clientAmount;
        pendingCount++;
      }
    });

    // Add company expenses to total expenses
    expenses.filter(e => {
      if (e.status !== 'Approved') return false;
      const now = new Date();
      let cutoff = new Date();
      if (dateRange === 'Last 30 Days') cutoff.setDate(now.getDate() - 30);
      else if (dateRange === 'Last 3 Months') cutoff.setMonth(now.getMonth() - 3);
      else if (dateRange === 'Last 6 Months') cutoff.setMonth(now.getMonth() - 6);
      else if (dateRange === 'Last Year') cutoff.setFullYear(now.getFullYear() - 1);
      else return true;
      return new Date(e.date) >= cutoff;
    }).forEach(e => {
      totalExpenses += e.amount;
      const eMonth = (e.date || '').substring(0, 7);
      if (eMonth === currentMonthStr) {
        currentMonthOutflow += e.amount;
      }
      if (monthlyMap.has(eMonth)) {
        const mData = monthlyMap.get(eMonth)!;
        mData.expenses += e.amount;
      }
    });

    const netProfit = totalRevenue - totalExpenses;
    const margin = totalRevenue > 0 ? (netProfit / totalRevenue) * 100 : 0;

    const chartData = Array.from(monthlyMap.entries()).map(([month, data]) => {
      const parts = (month || '').split('-');
      if (parts.length < 2) return { month: month, revenue: data.revenue, expenses: data.expenses };
      const [year, m] = parts;
      const date = new Date(parseInt(year), parseInt(m) - 1);
      return {
        month: date.toLocaleString('default', { month: 'short' }),
        revenue: data.revenue,
        expenses: data.expenses
      };
    });

    // Project Status Data
    const statusCounts = {
      'On Track': 0,
      'At Risk': 0,
      'Delayed': 0,
      'Completed': 0
    };

    filteredProjects.forEach(p => {
      if (p.status === 'Completed') statusCounts['Completed']++;
      else if (p.status === 'In Progress') statusCounts['On Track']++;
      else if (p.status === 'Pending') statusCounts['At Risk']++;
      else if (p.status === 'Cancelled') statusCounts['Delayed']++;
      else statusCounts['On Track']++;
    });

    const projectStatusData = [
      { name: 'On Track', value: statusCounts['On Track'], color: 'hsl(var(--primary))' },
      { name: 'At Risk', value: statusCounts['At Risk'], color: '#f59e0b' },
      { name: 'Delayed', value: statusCounts['Delayed'], color: '#ef4444' },
      { name: 'Completed', value: statusCounts['Completed'], color: '#10b981' },
    ];

    return {
      totalRevenue,
      totalExpenses,
      netProfit,
      margin,
      pendingAmount,
      pendingCount,
      chartData,
      currentMonthInflow,
      currentMonthOutflow,
      projectStatusData
    };
  }, [filteredProjects, expenses, dateRange]);

  const projectProfitability = useMemo(() => {
    return filteredProjects.map(p => {
      const hours = parseTotalTime(p.totalTime);
      const hourlyTotal = (p.hourlyRate || 0) * hours;
      const internalAmount = p.totalAmount && p.totalAmount > 0 ? p.totalAmount : 
        (hourlyTotal + (p.travelCost || 0) + (p.materialCost || 0) + (p.halfDayRate || 0) + (p.fullDayRate || 0) + (p.monthlyRate || 0));
      
      const clientHourlyTotal = (p.clientHourlyRate || 0) * hours;
      const clientAmount = p.clientTotalAmount && p.clientTotalAmount > 0 ? p.clientTotalAmount : 
        (clientHourlyTotal + (p.clientTravelCost || 0) + (p.clientMaterialCost || 0) + (p.clientHalfDayRate || 0) + (p.clientFullDayRate || 0) + (p.clientMonthlyRate || 0));

      const profit = clientAmount - internalAmount;
      return {
        name: p.name,
        profit,
        revenue: clientAmount,
        cost: internalAmount
      };
    }).sort((a, b) => b.profit - a.profit).slice(0, 5);
  }, [filteredProjects]);

  const handleExport = () => {
    const headers = ['Metric', 'Value'];
    const data = [
      ['Total Revenue', stats.totalRevenue.toFixed(2)],
      ['Total Expenses', stats.totalExpenses.toFixed(2)],
      ['Net Profit', stats.netProfit.toFixed(2)],
      ['Profit Margin', `${stats.margin.toFixed(2)}%`],
      ['Engineer Utilization', `${engineerUtilization}%`],
      ['Pending Amount', stats.pendingAmount.toFixed(2)],
      ['Pending Count', stats.pendingCount.toString()],
    ];

    // Add departmental stats
    data.push(['', '']);
    data.push(['Department', 'Efficiency (%)', 'Quality (%)']);
    departmentalStats.forEach(dept => {
      data.push([dept.name, dept.efficiency.toString(), dept.quality.toString()]);
    });

    const csvContent = [
      headers.join(','),
      ...data.map(row => row.map(cell => `"${cell}"`).join(','))
    ].join('\n');

    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = window.document.createElement('a');
    link.setAttribute('href', url);
    link.setAttribute('download', `analytics_export_${new Date().toISOString().split('T')[0]}.csv`);
    window.document.body.appendChild(link);
    link.click();
    window.document.body.removeChild(link);
    URL.revokeObjectURL(url);
    
    toast.success('Analytics data exported as CSV');
  };

  const handleRefresh = () => {
    toast.info('Refreshing analytics data...');
  };

  const handleGenerateReport = () => {
    const reportId = `REP-${Math.floor(Math.random() * 1000).toString().padStart(3, '0')}`;
    const newReport = {
      id: reportId,
      name: `Performance Analysis - ${new Date().toLocaleDateString()}`,
      type: 'Automated',
      date: new Date().toISOString().split('T')[0],
      status: 'Generated'
    };

    setReports([newReport, ...reports]);

    // Generate CSV content for the report
    const headers = ['Metric', 'Value'];
    const data = [
      ['Report ID', reportId],
      ['Report Name', newReport.name],
      ['Generated On', new Date().toLocaleString()],
      ['Range', dateRange],
      ['', ''],
      ['FINANCIAL SUMMARY', ''],
      ['Total Revenue', stats.totalRevenue.toFixed(2)],
      ['Total Expenses', stats.totalExpenses.toFixed(2)],
      ['Net Profit', stats.netProfit.toFixed(2)],
      ['Profit Margin', `${stats.margin.toFixed(2)}%`],
      ['', ''],
      ['OPERATIONAL METRICS', ''],
      ['Engineer Utilization', `${engineerUtilization}%`],
      ['Pending Projects', stats.pendingCount.toString()],
      ['Pending Revenue', stats.pendingAmount.toFixed(2)],
    ];

    const csvContent = [
      headers.join(','),
      ...data.map(row => row.map(cell => `"${cell}"`).join(','))
    ].join('\n');

    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = window.document.createElement('a');
    a.href = url;
    a.download = `report_${reportId}.csv`;
    window.document.body.appendChild(a);
    a.click();
    window.document.body.removeChild(a);
    URL.revokeObjectURL(url);

    toast.success('New report generated and downloaded as CSV');
  };

  const handleDownloadReport = (report: any) => {
    // Generate a generic CSV for existing reports
    const headers = ['Report ID', 'Name', 'Type', 'Date', 'Status'];
    const row = [report.id, report.name, report.type, report.date, report.status];
    
    const csvContent = [
      headers.join(','),
      row.map(cell => `"${cell}"`).join(',')
    ].join('\n');

    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = window.document.createElement('a');
    a.href = url;
    a.download = `${report.id}_${report.name.replace(/\s+/g, '_')}.csv`;
    window.document.body.appendChild(a);
    a.click();
    window.document.body.removeChild(a);
    URL.revokeObjectURL(url);
    
    toast.success(`Downloading ${report.name} as CSV`);
  };

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Reports & Analytics</h1>
          <p className="text-muted-foreground">Comprehensive insights into business performance and departmental metrics.</p>
        </div>
        <div className="flex items-center gap-2">
          <button 
            onClick={handleRefresh}
            className="p-2 rounded-lg border border-border bg-card hover:bg-accent transition-colors"
            title="Refresh Data"
          >
            <RefreshCcw size={18} className="text-muted-foreground" />
          </button>
          <div className="relative">
            <Calendar className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" size={16} />
            <select 
              value={dateRange}
              onChange={(e) => setDateRange(e.target.value)}
              className="h-10 rounded-lg border border-border bg-card pl-10 pr-4 text-sm font-medium focus:outline-none focus:ring-2 focus:ring-primary/20 appearance-none cursor-pointer"
            >
              <option>Last 30 Days</option>
              <option>Last 3 Months</option>
              <option>Last 6 Months</option>
              <option>Last Year</option>
            </select>
          </div>
          <button 
            onClick={handleExport}
            className="flex items-center gap-2 rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium hover:bg-accent transition-colors"
          >
            <Download size={18} />
            Export
          </button>
          <button 
            onClick={handleGenerateReport}
            className="flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors"
          >
            <Plus size={18} />
            Generate Report
          </button>
        </div>
      </div>

      {/* KPI Overview */}
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <ReportStatCard 
          title="Total Revenue" 
          value={`$${stats.totalRevenue.toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: 0 })}`} 
          icon={TrendingUp} 
          trend={`${stats.margin.toFixed(1)}%`} 
          trendType="up"
          description="Gross profit margin"
        />
        <ReportStatCard 
          title="Total Expenses" 
          value={`$${stats.totalExpenses.toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: 0 })}`} 
          icon={TrendingDown} 
          trend="Stable" 
          trendType="neutral"
          description="Engineer payouts & costs"
        />
        <ReportStatCard 
          title="Net Profit" 
          value={`$${stats.netProfit.toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: 0 })}`} 
          icon={DollarSign} 
          trend="+5.2%" 
          trendType="up"
          description="Earnings after expenses"
        />
        <ReportStatCard 
          title="Engineer Utilization" 
          value={`${engineerUtilization}%`} 
          icon={Users} 
          trend={engineers.length.toString()} 
          trendType="neutral"
          description="Active project assignments"
        />
      </div>

      <div className="grid gap-6 lg:grid-cols-2">
        {/* Revenue Growth Chart */}
        <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
          <div className="flex items-center justify-between mb-6">
            <div>
              <h3 className="font-bold text-lg">Financial Performance</h3>
              <p className="text-xs text-muted-foreground">Revenue vs. Expenses (Last 6 Months)</p>
            </div>
            <div className="flex items-center gap-4 text-[10px] font-bold uppercase tracking-wider">
              <div className="flex items-center gap-1.5">
                <div className="h-2 w-2 rounded-full bg-primary" />
                <span className="text-muted-foreground">Revenue</span>
              </div>
              <div className="flex items-center gap-1.5">
                <div className="h-2 w-2 rounded-full bg-muted" />
                <span className="text-muted-foreground">Expenses</span>
              </div>
            </div>
          </div>
          <div className="h-[300px] w-full">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart data={stats.chartData} margin={{ top: 10, right: 10, left: -20, bottom: 0 }}>
                <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="hsl(var(--border))" />
                <XAxis 
                  dataKey="month" 
                  axisLine={false} 
                  tickLine={false} 
                  tick={{ fontSize: 10, fontWeight: 600, fill: 'hsl(var(--muted-foreground))' }} 
                />
                <YAxis 
                  axisLine={false} 
                  tickLine={false} 
                  tick={{ fontSize: 10, fontWeight: 600, fill: 'hsl(var(--muted-foreground))' }}
                  tickFormatter={(value) => `$${value/1000}k`}
                />
                <Tooltip 
                  cursor={{ fill: 'hsl(var(--muted)/0.1)' }}
                  contentStyle={{ backgroundColor: 'hsl(var(--card))', borderColor: 'hsl(var(--border))', borderRadius: '12px', boxShadow: '0 10px 15px -3px rgb(0 0 0 / 0.1)' }}
                  itemStyle={{ fontSize: '11px', fontWeight: 600 }}
                  labelStyle={{ fontSize: '12px', fontWeight: 700, marginBottom: '4px' }}
                />
                <Bar dataKey="revenue" fill="hsl(var(--primary))" radius={[4, 4, 0, 0]} barSize={24} />
                <Bar dataKey="expenses" fill="hsl(var(--muted))" radius={[4, 4, 0, 0]} barSize={24} />
              </BarChart>
            </ResponsiveContainer>
          </div>
        </div>

        {/* Recruitment Funnel */}
        <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
          <div className="flex items-center justify-between mb-6">
            <div>
              <h3 className="font-bold text-lg">Recruitment Funnel</h3>
              <p className="text-xs text-muted-foreground">Candidate status distribution</p>
            </div>
            <div className="p-2 rounded-lg bg-primary/10 text-primary">
              <Users size={18} />
            </div>
          </div>
          <div className="h-[300px] w-full">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart data={recruitmentStats} layout="vertical" margin={{ top: 0, right: 30, left: 40, bottom: 0 }}>
                <CartesianGrid strokeDasharray="3 3" horizontal={false} stroke="hsl(var(--border))" />
                <XAxis type="number" hide />
                <YAxis 
                  dataKey="name" 
                  type="category" 
                  axisLine={false} 
                  tickLine={false} 
                  tick={{ fontSize: 10, fontWeight: 700, fill: 'hsl(var(--foreground))' }}
                  width={100}
                />
                <Tooltip 
                  cursor={{ fill: 'hsl(var(--muted)/0.1)' }}
                  contentStyle={{ backgroundColor: 'hsl(var(--card))', borderColor: 'hsl(var(--border))', borderRadius: '12px' }}
                />
                <Bar dataKey="value" radius={[0, 4, 4, 0]} barSize={20}>
                  {recruitmentStats.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={entry.color} />
                  ))}
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          </div>
        </div>
      </div>

      <div className="grid gap-6 lg:grid-cols-3">
        {/* Top Clients by Revenue */}
        <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
          <h3 className="font-bold text-lg mb-1">Top Clients</h3>
          <p className="text-xs text-muted-foreground mb-6">Revenue contribution by client</p>
          <div className="space-y-4">
            {clientRevenueData.map((client, index) => (
              <div key={client.name} className="space-y-2">
                <div className="flex items-center justify-between text-xs">
                  <span className="font-bold">{client.name}</span>
                  <span className="font-mono text-primary font-bold">${client.value.toLocaleString()}</span>
                </div>
                <div className="h-2 w-full bg-muted rounded-full overflow-hidden">
                  <motion.div 
                    initial={{ width: 0 }}
                    animate={{ width: `${(client.value / clientRevenueData[0].value) * 100}%` }}
                    className="h-full bg-primary"
                  />
                </div>
              </div>
            ))}
            {clientRevenueData.length === 0 && (
              <p className="text-center text-muted-foreground text-sm py-8">No client data available</p>
            )}
          </div>
        </div>

        {/* Departmental Efficiency */}
        <div className="rounded-xl border border-border bg-card p-6 shadow-sm lg:col-span-2">
          <div className="flex items-center justify-between mb-6">
            <div>
              <h3 className="font-bold text-lg">Departmental Efficiency</h3>
              <p className="text-xs text-muted-foreground">Task completion vs. Quality score</p>
            </div>
            <div className="flex items-center gap-4 text-[10px] font-bold uppercase tracking-wider">
              <div className="flex items-center gap-1.5">
                <div className="h-2 w-2 rounded-full bg-primary" />
                <span className="text-muted-foreground">Efficiency</span>
              </div>
              <div className="flex items-center gap-1.5">
                <div className="h-2 w-2 rounded-full bg-muted" />
                <span className="text-muted-foreground">Quality</span>
              </div>
            </div>
          </div>
          <div className="h-[300px] w-full">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart 
                data={departmentalStats} 
                layout="vertical"
                margin={{ top: 0, right: 30, left: 40, bottom: 0 }}
              >
                <CartesianGrid strokeDasharray="3 3" horizontal={false} stroke="hsl(var(--border))" />
                <XAxis 
                  type="number"
                  axisLine={false} 
                  tickLine={false} 
                  tick={{ fontSize: 10, fontWeight: 600, fill: 'hsl(var(--muted-foreground))' }} 
                  domain={[0, 100]}
                />
                <YAxis 
                  dataKey="name" 
                  type="category"
                  axisLine={false} 
                  tickLine={false} 
                  tick={{ fontSize: 10, fontWeight: 700, fill: 'hsl(var(--foreground))' }}
                  width={100}
                />
                <Tooltip 
                  cursor={{ fill: 'hsl(var(--muted)/0.1)' }}
                  contentStyle={{ backgroundColor: 'hsl(var(--card))', borderColor: 'hsl(var(--border))', borderRadius: '12px' }}
                />
                <Bar dataKey="efficiency" fill="hsl(var(--primary))" radius={[0, 4, 4, 0]} barSize={12} />
                <Bar dataKey="quality" fill="hsl(var(--muted))" radius={[0, 4, 4, 0]} barSize={12} />
              </BarChart>
            </ResponsiveContainer>
          </div>
        </div>
      </div>

      <div className="grid gap-6 lg:grid-cols-3">
        {/* Expense Breakdown */}
        <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
          <h3 className="font-bold text-lg mb-1">Expense Allocation</h3>
          <p className="text-xs text-muted-foreground mb-6">Distribution by category</p>
          <div className="h-[250px] w-full">
            <ResponsiveContainer width="100%" height="100%">
              <PieChart>
                <Pie
                  data={expenseBreakdown.length > 0 ? expenseBreakdown : [{ name: 'No Data', value: 1, color: '#94a3b8' }]}
                  cx="50%"
                  cy="50%"
                  innerRadius={60}
                  outerRadius={80}
                  paddingAngle={5}
                  dataKey="value"
                >
                  {(expenseBreakdown.length > 0 ? expenseBreakdown : [{ name: 'No Data', value: 1, color: '#94a3b8' }]).map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={entry.color} />
                  ))}
                </Pie>
                <Tooltip 
                  formatter={(value: number) => `$${value.toLocaleString()}`}
                  contentStyle={{ backgroundColor: 'hsl(var(--card))', borderColor: 'hsl(var(--border))', borderRadius: '12px' }}
                />
              </PieChart>
            </ResponsiveContainer>
          </div>
          <div className="mt-4 space-y-2">
            {expenseBreakdown.slice(0, 4).map((item) => (
              <div key={item.name} className="flex items-center justify-between text-xs">
                <div className="flex items-center gap-2">
                  <div className="h-2 w-2 rounded-full" style={{ backgroundColor: item.color }} />
                  <span className="font-medium">{item.name}</span>
                </div>
                <span className="text-muted-foreground font-mono">${item.value.toLocaleString()}</span>
              </div>
            ))}
          </div>
        </div>

        {/* Task Completion Trends */}
        <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
          <div className="flex items-center justify-between mb-6">
            <div>
              <h3 className="font-bold text-lg">Task Execution Trends</h3>
              <p className="text-xs text-muted-foreground">Monthly completion rates and volume</p>
            </div>
            <div className="p-2 rounded-lg bg-primary/10 text-primary">
              <CheckSquare size={18} />
            </div>
          </div>
          <div className="h-[250px] w-full">
            <ResponsiveContainer width="100%" height="100%">
              <LineChart data={taskTrends} margin={{ top: 10, right: 10, left: -20, bottom: 0 }}>
                <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="hsl(var(--border))" />
                <XAxis 
                  dataKey="month" 
                  axisLine={false} 
                  tickLine={false} 
                  tick={{ fontSize: 10, fontWeight: 600, fill: 'hsl(var(--muted-foreground))' }} 
                />
                <YAxis 
                  axisLine={false} 
                  tickLine={false} 
                  tick={{ fontSize: 10, fontWeight: 600, fill: 'hsl(var(--muted-foreground))' }}
                />
                <Tooltip 
                  contentStyle={{ backgroundColor: 'hsl(var(--card))', borderColor: 'hsl(var(--border))', borderRadius: '12px' }}
                  itemStyle={{ fontSize: '11px', fontWeight: 600 }}
                />
                <Line 
                  type="monotone" 
                  dataKey="rate" 
                  stroke="hsl(var(--primary))" 
                  strokeWidth={3} 
                  dot={{ r: 4, fill: 'hsl(var(--primary))', strokeWidth: 2, stroke: 'hsl(var(--card))' }}
                  activeDot={{ r: 6, strokeWidth: 0 }}
                  name="Completion %"
                />
              </LineChart>
            </ResponsiveContainer>
          </div>
        </div>

        {/* Portfolio Health */}
        <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
          <h3 className="font-bold text-lg mb-1">Portfolio Health</h3>
          <p className="text-xs text-muted-foreground mb-6">Project status distribution</p>
          <div className="h-[250px] w-full">
            <ResponsiveContainer width="100%" height="100%">
              <PieChart>
                <Pie
                  data={stats.projectStatusData}
                  cx="50%"
                  cy="50%"
                  innerRadius={60}
                  outerRadius={80}
                  paddingAngle={5}
                  dataKey="value"
                >
                  {stats.projectStatusData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={entry.color} />
                  ))}
                </Pie>
                <Tooltip 
                  contentStyle={{ backgroundColor: 'hsl(var(--card))', borderColor: 'hsl(var(--border))', borderRadius: '12px' }}
                />
                <Legend 
                  verticalAlign="bottom" 
                  height={36}
                  iconType="circle"
                  formatter={(value) => <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">{value}</span>}
                />
              </PieChart>
            </ResponsiveContainer>
          </div>
        </div>

        {/* Recent Reports List */}
        <div className="rounded-xl border border-border bg-card p-6 shadow-sm lg:col-span-2">
          <div className="flex items-center justify-between mb-6">
            <h3 className="font-semibold">Recently Generated Reports</h3>
            <div className="relative max-w-xs">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" size={16} />
              <input
                type="text"
                placeholder="Search reports..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="h-9 w-full rounded-lg border border-border bg-background pl-9 pr-4 text-xs focus:outline-none focus:ring-2 focus:ring-primary/20"
              />
            </div>
          </div>
          <div className="space-y-4">
            {reports.filter(r => r.name.toLowerCase().includes(searchQuery.toLowerCase())).map((report) => (
              <div key={report.id} className="flex items-center justify-between p-3 rounded-lg border border-border hover:bg-accent/30 transition-all group cursor-pointer">
                <div className="flex items-center gap-4">
                  <div className="h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center text-primary">
                    <FileText size={20} />
                  </div>
                  <div>
                    <p className="text-sm font-medium group-hover:text-primary transition-colors">{report.name}</p>
                    <div className="flex items-center gap-3 mt-1">
                      <span className="text-[10px] text-muted-foreground uppercase tracking-wider font-bold">{report.id}</span>
                      <span className="text-[10px] text-muted-foreground">•</span>
                      <span className="text-[10px] text-muted-foreground">{report.type}</span>
                    </div>
                  </div>
                </div>
                <div className="flex items-center gap-6">
                  <div className="text-right hidden sm:block">
                    <p className="text-xs font-medium">{report.date}</p>
                    <span className={cn(
                      "text-[10px] font-bold uppercase",
                      report.status === 'Generated' ? "text-green-500" : "text-yellow-500"
                    )}>
                      {report.status}
                    </span>
                  </div>
                  <button 
                    onClick={() => handleDownloadReport(report)}
                    className="p-1 hover:bg-accent rounded-md text-muted-foreground transition-colors"
                  >
                    <Download size={16} />
                  </button>
                </div>
              </div>
            ))}
          </div>
          <button className="w-full mt-4 py-2 text-xs font-medium text-muted-foreground hover:text-primary transition-colors flex items-center justify-center gap-2">
            View All Reports
            <ChevronRight size={14} />
          </button>
        </div>
      </div>

      {/* Project Profitability Table */}
      <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
        <div className="flex items-center justify-between mb-6">
          <div>
            <h3 className="font-bold text-lg">Project Profitability</h3>
            <p className="text-xs text-muted-foreground">Top 5 most profitable projects in selected period</p>
          </div>
          <div className="p-2 rounded-lg bg-emerald-500/10 text-emerald-500">
            <BarChart3 size={18} />
          </div>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-border text-left">
                <th className="pb-3 font-bold uppercase tracking-wider text-[10px] text-muted-foreground">Project Name</th>
                <th className="pb-3 font-bold uppercase tracking-wider text-[10px] text-muted-foreground text-right">Revenue</th>
                <th className="pb-3 font-bold uppercase tracking-wider text-[10px] text-muted-foreground text-right">Cost</th>
                <th className="pb-3 font-bold uppercase tracking-wider text-[10px] text-muted-foreground text-right">Profit</th>
                <th className="pb-3 font-bold uppercase tracking-wider text-[10px] text-muted-foreground text-right">Margin</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border">
              {projectProfitability.map((p) => (
                <tr key={p.name} className="group hover:bg-muted/30 transition-colors">
                  <td className="py-3 font-medium">{p.name}</td>
                  <td className="py-3 text-right font-mono">${p.revenue.toLocaleString()}</td>
                  <td className="py-3 text-right font-mono text-muted-foreground">${p.cost.toLocaleString()}</td>
                  <td className="py-3 text-right font-mono font-bold text-emerald-500">${p.profit.toLocaleString()}</td>
                  <td className="py-3 text-right">
                    <span className="inline-flex items-center px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-500/10 text-emerald-500">
                      {p.revenue > 0 ? ((p.profit / p.revenue) * 100).toFixed(1) : 0}%
                    </span>
                  </td>
                </tr>
              ))}
              {projectProfitability.length === 0 && (
                <tr>
                  <td colSpan={5} className="py-8 text-center text-muted-foreground">No project data available for this period</td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

function ReportStatCard({ title, value, icon: Icon, trend, trendType, description }: { title: string, value: string, icon: any, trend: string, trendType: 'up' | 'down' | 'neutral', description: string }) {
  return (
    <div className="rounded-xl border border-border bg-card p-4 shadow-sm">
      <div className="flex items-center justify-between mb-2">
        <div className="p-2 rounded-lg bg-accent text-muted-foreground">
          <Icon size={18} />
        </div>
        <div className={cn(
          "flex items-center gap-1 text-xs font-medium",
          trendType === 'up' ? "text-green-500" : trendType === 'down' ? "text-red-500" : "text-muted-foreground"
        )}>
          {trendType === 'up' && <ArrowUpRight size={14} />}
          {trendType === 'down' && <ArrowDownRight size={14} />}
          {trend}
        </div>
      </div>
      <div>
        <p className="text-sm text-muted-foreground">{title}</p>
        <p className="text-2xl font-bold">{value}</p>
        <p className="text-xs text-muted-foreground mt-1">{description}</p>
      </div>
    </div>
  );
}
