import React, { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Download, Users, TrendingUp, Clock, AlertTriangle, Award } from "lucide-react";
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from "recharts";
import { Badge } from "@/components/ui/badge";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { useToast } from "@/components/ui/use-toast";
import ReportInsightsBanner from "./ReportInsightsBanner";

export default function StaffPerformanceReport({ staff, events, userRole = 'admin' }) {
  const { toast } = useToast();

  // Calculate staff metrics
  const staffMetrics = staff.map(s => {
    const assignments = events.filter(e => 
      e.assigned_staff?.some(as => as.staff_id === s.id)
    );
    
    const completedShifts = assignments.filter(e => e.status === 'Completed').length;
    const totalShifts = s.total_shifts || assignments.length || 1;
    const fillRate = totalShifts > 0 ? ((completedShifts / totalShifts) * 100).toFixed(1) : 0;
    const reliability = s.reliability_score || s.shift_coverage_percentage || 85;
    
    return {
      id: s.id,
      name: s.employee_name,
      position: s.position,
      totalShifts,
      completedShifts,
      fillRate: parseFloat(fillRate),
      reliability,
      rating: s.rating || 4.2,
      cancellations: s.cancellation_count || 0,
      noShows: s.no_show_count || 0,
    };
  }).sort((a, b) => b.reliability - a.reliability);

  // Top performers
  const topPerformers = staffMetrics.slice(0, 10);

  // Fill rate distribution
  const fillRateRanges = [
    { range: '90-100%', count: staffMetrics.filter(s => s.fillRate >= 90).length },
    { range: '80-89%', count: staffMetrics.filter(s => s.fillRate >= 80 && s.fillRate < 90).length },
    { range: '70-79%', count: staffMetrics.filter(s => s.fillRate >= 70 && s.fillRate < 80).length },
    { range: '60-69%', count: staffMetrics.filter(s => s.fillRate >= 60 && s.fillRate < 70).length },
    { range: '<60%', count: staffMetrics.filter(s => s.fillRate < 60).length },
  ];

  const avgReliability = staffMetrics.reduce((sum, s) => sum + s.reliability, 0) / staffMetrics.length || 0;
  const avgFillRate = staffMetrics.reduce((sum, s) => sum + s.fillRate, 0) / staffMetrics.length || 0;
  const totalCancellations = staffMetrics.reduce((sum, s) => sum + s.cancellations, 0);

  const handleExport = () => {
    const csv = [
      ['Staff Performance Report'],
      ['Generated', new Date().toISOString()],
      [''],
      ['Summary'],
      ['Average Reliability', `${avgReliability.toFixed(1)}%`],
      ['Average Fill Rate', `${avgFillRate.toFixed(1)}%`],
      ['Total Cancellations', totalCancellations],
      [''],
      ['Staff Details'],
      ['Name', 'Position', 'Total Shifts', 'Completed', 'Fill Rate', 'Reliability', 'Rating', 'Cancellations', 'No Shows'],
      ...staffMetrics.map(s => [
        s.name,
        s.position,
        s.totalShifts,
        s.completedShifts,
        `${s.fillRate}%`,
        `${s.reliability}%`,
        s.rating,
        s.cancellations,
        s.noShows,
      ]),
    ].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 = `staff-performance-${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: "Performance report downloaded as CSV" });
  };

  // At-risk workers
  const atRiskWorkers = staffMetrics.filter(s => s.reliability < 70 || s.noShows > 2);

  return (
    <div className="space-y-6">
      {/* AI Insights Banner */}
      <ReportInsightsBanner userRole={userRole} reportType="performance" />

      <div className="flex justify-between items-center">
        <div>
          <h2 className="text-xl font-bold text-slate-900">Workforce Performance</h2>
          <p className="text-sm text-slate-500">Reliability, fill rates & actionable insights</p>
        </div>
        <Button onClick={handleExport} size="sm" className="bg-[#0A39DF]">
          <Download className="w-4 h-4 mr-1" />
          Export
        </Button>
      </div>

      {/* Quick Actions */}
      {atRiskWorkers.length > 0 && (
        <div className="bg-amber-50 border border-amber-200 rounded-lg p-3 flex items-center justify-between">
          <div className="flex items-center gap-2">
            <AlertTriangle className="w-5 h-5 text-amber-600" />
            <span className="text-sm font-medium text-amber-800">
              {atRiskWorkers.length} workers need attention (reliability &lt;70% or 2+ no-shows)
            </span>
          </div>
          <Button size="sm" variant="outline" className="border-amber-300 text-amber-700 hover:bg-amber-100">
            View At-Risk Workers
          </Button>
        </div>
      )}

      {/* Decision Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card className={`border-l-4 ${avgReliability >= 85 ? 'border-l-green-500' : avgReliability >= 70 ? 'border-l-amber-500' : 'border-l-red-500'}`}>
          <CardContent className="pt-4 pb-3">
            <p className="text-xs text-slate-500 uppercase tracking-wider">Avg Reliability</p>
            <p className="text-2xl font-bold text-slate-900">{avgReliability.toFixed(1)}%</p>
            <p className={`text-xs mt-1 ${avgReliability >= 85 ? 'text-green-600' : 'text-amber-600'}`}>
              {avgReliability >= 85 ? '✓ Excellent' : avgReliability >= 70 ? '⚠ Needs attention' : '✗ Critical'}
            </p>
          </CardContent>
        </Card>

        <Card className={`border-l-4 ${avgFillRate >= 90 ? 'border-l-green-500' : avgFillRate >= 75 ? 'border-l-amber-500' : 'border-l-red-500'}`}>
          <CardContent className="pt-4 pb-3">
            <p className="text-xs text-slate-500 uppercase tracking-wider">Avg Fill Rate</p>
            <p className="text-2xl font-bold text-slate-900">{avgFillRate.toFixed(1)}%</p>
            <p className="text-xs text-slate-500 mt-1">{avgFillRate >= 90 ? 'Above target' : `${(90 - avgFillRate).toFixed(1)}% below target`}</p>
          </CardContent>
        </Card>

        <Card className={`border-l-4 ${totalCancellations < 5 ? 'border-l-green-500' : totalCancellations < 15 ? 'border-l-amber-500' : 'border-l-red-500'}`}>
          <CardContent className="pt-4 pb-3">
            <p className="text-xs text-slate-500 uppercase tracking-wider">Cancellations</p>
            <p className="text-2xl font-bold text-slate-900">{totalCancellations}</p>
            <p className="text-xs text-red-600 mt-1">~${(totalCancellations * 150).toLocaleString()} impact</p>
          </CardContent>
        </Card>

        <Card className="border-l-4 border-l-purple-500 bg-purple-50">
          <CardContent className="pt-4 pb-3">
            <p className="text-xs text-purple-600 uppercase tracking-wider font-semibold">Quick Decision</p>
            <p className="text-sm font-medium text-purple-900 mt-1">
              {atRiskWorkers.length > 0 
                ? `Review ${atRiskWorkers.length} at-risk workers before next scheduling cycle`
                : avgFillRate < 90
                ? 'Expand worker pool by 15% to improve fill rate'
                : 'Performance healthy — consider bonuses for top 10%'
              }
            </p>
          </CardContent>
        </Card>
      </div>

      {/* Fill Rate Distribution */}
      <Card>
        <CardHeader>
          <CardTitle>Fill Rate Distribution</CardTitle>
        </CardHeader>
        <CardContent>
          <ResponsiveContainer width="100%" height={300}>
            <BarChart data={fillRateRanges}>
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="range" />
              <YAxis />
              <Tooltip />
              <Legend />
              <Bar dataKey="count" fill="#0A39DF" name="Staff Count" />
            </BarChart>
          </ResponsiveContainer>
        </CardContent>
      </Card>

      {/* Top Performers Table */}
      <Card>
        <CardHeader>
          <CardTitle>Top Performers</CardTitle>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Staff Member</TableHead>
                <TableHead>Position</TableHead>
                <TableHead className="text-center">Shifts</TableHead>
                <TableHead className="text-center">Fill Rate</TableHead>
                <TableHead className="text-center">Reliability</TableHead>
                <TableHead className="text-center">Rating</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {topPerformers.map((staff) => (
                <TableRow key={staff.id}>
                  <TableCell>
                    <div className="flex items-center gap-3">
                      <Avatar className="w-8 h-8">
                        <AvatarFallback className="bg-blue-100 text-blue-700 text-xs">
                          {staff.name.charAt(0)}
                        </AvatarFallback>
                      </Avatar>
                      <span className="font-medium">{staff.name}</span>
                    </div>
                  </TableCell>
                  <TableCell className="text-slate-600">{staff.position}</TableCell>
                  <TableCell className="text-center">
                    <Badge variant="outline">{staff.completedShifts}/{staff.totalShifts}</Badge>
                  </TableCell>
                  <TableCell className="text-center">
                    <Badge className={
                      staff.fillRate >= 90 ? "bg-green-500" :
                      staff.fillRate >= 75 ? "bg-blue-500" : "bg-amber-500"
                    }>
                      {staff.fillRate}%
                    </Badge>
                  </TableCell>
                  <TableCell className="text-center">
                    <Badge className="bg-purple-500">{staff.reliability}%</Badge>
                  </TableCell>
                  <TableCell className="text-center">
                    <Badge variant="outline">{staff.rating}/5</Badge>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}