import React, { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Download, DollarSign, TrendingUp, AlertCircle } from "lucide-react";
import { BarChart, Bar, LineChart, Line, PieChart, Pie, Cell, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from "recharts";
import { Badge } from "@/components/ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useToast } from "@/components/ui/use-toast";

const COLORS = ['#0A39DF', '#3b82f6', '#60a5fa', '#93c5fd', '#dbeafe'];

export default function StaffingCostReport({ events, invoices }) {
  const [dateRange, setDateRange] = useState("30");
  const { toast } = useToast();

  // Calculate costs by month
  const costsByMonth = events.reduce((acc, event) => {
    if (!event.date || !event.total) return acc;
    const date = new Date(event.date);
    const month = date.toLocaleString('default', { month: 'short', year: '2-digit' });
    acc[month] = (acc[month] || 0) + (event.total || 0);
    return acc;
  }, {});

  const monthlyData = Object.entries(costsByMonth).map(([month, cost]) => ({
    month,
    cost: Math.round(cost),
    budget: Math.round(cost * 1.1), // 10% buffer
  }));

  // Costs by department
  const costsByDepartment = events.reduce((acc, event) => {
    event.shifts?.forEach(shift => {
      shift.roles?.forEach(role => {
        const dept = role.department || 'Unassigned';
        acc[dept] = (acc[dept] || 0) + (role.total_value || 0);
      });
    });
    return acc;
  }, {});

  const departmentData = Object.entries(costsByDepartment)
    .map(([name, value]) => ({ name, value: Math.round(value) }))
    .sort((a, b) => b.value - a.value);

  // Budget adherence
  const totalSpent = events.reduce((sum, e) => sum + (e.total || 0), 0);
  const totalBudget = totalSpent * 1.15; // Assume 15% buffer
  const adherence = totalBudget > 0 ? ((totalSpent / totalBudget) * 100).toFixed(1) : 0;

  const handleExport = () => {
    const data = {
      summary: {
        totalSpent: totalSpent.toFixed(2),
        totalBudget: totalBudget.toFixed(2),
        adherence: `${adherence}%`,
      },
      monthlyBreakdown: monthlyData,
      departmentBreakdown: departmentData,
    };

    const csv = [
      ['Staffing Cost Report'],
      ['Generated', new Date().toISOString()],
      [''],
      ['Summary'],
      ['Total Spent', totalSpent.toFixed(2)],
      ['Total Budget', totalBudget.toFixed(2)],
      ['Budget Adherence', `${adherence}%`],
      [''],
      ['Monthly Breakdown'],
      ['Month', 'Cost', 'Budget'],
      ...monthlyData.map(d => [d.month, d.cost, d.budget]),
      [''],
      ['Department Breakdown'],
      ['Department', 'Cost'],
      ...departmentData.map(d => [d.name, d.value]),
    ].map(row => row.join(',')).join('\n');

    const blob = new Blob([csv], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `staffing-costs-${new Date().toISOString().split('T')[0]}.csv`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);

    toast({ title: "✅ Report Exported", description: "Cost report downloaded as CSV" });
  };

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h2 className="text-xl font-bold text-slate-900">Staffing Costs & Budget Adherence</h2>
          <p className="text-sm text-slate-500">Track spending and budget compliance</p>
        </div>
        <div className="flex gap-2">
          <Select value={dateRange} onValueChange={setDateRange}>
            <SelectTrigger className="w-32">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="7">Last 7 days</SelectItem>
              <SelectItem value="30">Last 30 days</SelectItem>
              <SelectItem value="90">Last 90 days</SelectItem>
              <SelectItem value="365">Last year</SelectItem>
            </SelectContent>
          </Select>
          <Button onClick={handleExport} variant="outline">
            <Download className="w-4 h-4 mr-2" />
            Export CSV
          </Button>
        </div>
      </div>

      {/* Summary Cards */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-slate-500">Total Spent</p>
                <p className="text-2xl font-bold text-slate-900">${totalSpent.toLocaleString(undefined, { maximumFractionDigits: 0 })}</p>
              </div>
              <div className="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center">
                <DollarSign className="w-6 h-6 text-blue-600" />
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-slate-500">Budget</p>
                <p className="text-2xl font-bold text-slate-900">${totalBudget.toLocaleString(undefined, { maximumFractionDigits: 0 })}</p>
              </div>
              <div className="w-12 h-12 bg-green-100 rounded-full flex items-center justify-center">
                <TrendingUp className="w-6 h-6 text-green-600" />
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-slate-500">Budget Adherence</p>
                <p className="text-2xl font-bold text-slate-900">{adherence}%</p>
                <Badge className={adherence < 90 ? "bg-green-500" : adherence < 100 ? "bg-amber-500" : "bg-red-500"}>
                  {adherence < 90 ? "Under Budget" : adherence < 100 ? "On Track" : "Over Budget"}
                </Badge>
              </div>
              <div className="w-12 h-12 bg-purple-100 rounded-full flex items-center justify-center">
                <AlertCircle className="w-6 h-6 text-purple-600" />
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Monthly Cost Trend */}
      <Card>
        <CardHeader>
          <CardTitle>Monthly Cost Trend</CardTitle>
        </CardHeader>
        <CardContent>
          <ResponsiveContainer width="100%" height={300}>
            <LineChart data={monthlyData}>
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="month" />
              <YAxis />
              <Tooltip formatter={(value) => `$${value.toLocaleString()}`} />
              <Legend />
              <Line type="monotone" dataKey="cost" stroke="#0A39DF" strokeWidth={2} name="Actual Cost" />
              <Line type="monotone" dataKey="budget" stroke="#10b981" strokeWidth={2} strokeDasharray="5 5" name="Budget" />
            </LineChart>
          </ResponsiveContainer>
        </CardContent>
      </Card>

      {/* Department Breakdown */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <Card>
          <CardHeader>
            <CardTitle>Costs by Department</CardTitle>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300}>
              <PieChart>
                <Pie
                  data={departmentData}
                  cx="50%"
                  cy="50%"
                  labelLine={false}
                  label={({ name, percent }) => `${name}: ${(percent * 100).toFixed(0)}%`}
                  outerRadius={80}
                  fill="#8884d8"
                  dataKey="value"
                >
                  {departmentData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                  ))}
                </Pie>
                <Tooltip formatter={(value) => `$${value.toLocaleString()}`} />
              </PieChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Department Spending</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              {departmentData.slice(0, 5).map((dept, idx) => (
                <div key={idx} className="flex items-center justify-between">
                  <span className="text-sm font-medium">{dept.name}</span>
                  <Badge variant="outline">${dept.value.toLocaleString()}</Badge>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}