import React, { useMemo } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Users, TrendingUp, UserPlus, AlertCircle, CheckCircle } from "lucide-react";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";

export default function TalentRadar({ event, allStaff, availabilityData, onAssign }) {
  // Calculate three intelligent buckets
  const buckets = useMemo(() => {
    const readyNow = [];
    const likelyAvailable = [];
    const needsWork = [];

    allStaff.forEach(staff => {
      const availability = availabilityData.find(a => a.staff_id === staff.id);
      
      // Skip if already assigned to this event
      if (event.assigned_staff?.some(a => a.staff_id === staff.id)) return;
      
      // Skip if blocked
      if (availability?.availability_status === 'BLOCKED') return;

      // Calculate match score
      const matchScore = calculateMatchScore(staff, event, availability);

      // Ready Now: Confirmed available + good match
      if (availability?.availability_status === 'CONFIRMED_AVAILABLE' && matchScore >= 70) {
        readyNow.push({ staff, availability, matchScore });
      }
      // Likely Available: Unknown but high prediction score
      else if (
        availability?.availability_status === 'UNKNOWN' && 
        availability?.predicted_availability_score >= 70
      ) {
        likelyAvailable.push({ staff, availability, matchScore });
      }
      // Needs Work: High need index
      if (availability && availability.need_work_index >= 60) {
        needsWork.push({ staff, availability, matchScore });
      }
    });

    // Sort by match score and need
    readyNow.sort((a, b) => {
      const scoreA = a.matchScore + (a.availability?.need_work_index || 0) * 0.3;
      const scoreB = b.matchScore + (b.availability?.need_work_index || 0) * 0.3;
      return scoreB - scoreA;
    });

    likelyAvailable.sort((a, b) => b.matchScore - a.matchScore);
    needsWork.sort((a, b) => b.availability.need_work_index - a.availability.need_work_index);

    return { readyNow, likelyAvailable, needsWork };
  }, [allStaff, availabilityData, event]);

  const renderWorkerCard = (item, bucket) => {
    const { staff, availability, matchScore } = item;
    
    return (
      <Card key={staff.id} className="border hover:shadow-md transition-shadow">
        <CardContent className="p-4">
          <div className="flex items-start justify-between gap-3">
            <div className="flex items-start gap-3 flex-1">
              <Avatar className="w-10 h-10">
                <AvatarFallback className="bg-blue-500 text-white font-bold text-sm">
                  {staff.employee_name?.charAt(0)?.toUpperCase()}
                </AvatarFallback>
              </Avatar>
              <div className="flex-1 min-w-0">
                <p className="font-semibold text-sm text-slate-900 truncate">{staff.employee_name}</p>
                <p className="text-xs text-slate-500">{staff.position || 'Staff'}</p>
                
                <div className="flex gap-1 mt-2 flex-wrap">
                  <Badge variant="outline" className="text-[10px] px-1.5 py-0">
                    {matchScore}% match
                  </Badge>
                  {availability?.scheduled_hours_this_period > 0 && (
                    <Badge variant="secondary" className="text-[10px] px-1.5 py-0">
                      {availability.scheduled_hours_this_period}h scheduled
                    </Badge>
                  )}
                  {bucket === 'needs' && (
                    <Badge className="bg-orange-500 text-white text-[10px] px-1.5 py-0">
                      Needs work
                    </Badge>
                  )}
                  {bucket === 'likely' && (
                    <Badge className="bg-blue-500 text-white text-[10px] px-1.5 py-0">
                      {availability?.predicted_availability_score}% likely
                    </Badge>
                  )}
                </div>
              </div>
            </div>
            <Button 
              size="sm" 
              onClick={() => onAssign(staff, bucket)}
              className="flex-shrink-0"
            >
              Assign
            </Button>
          </div>
        </CardContent>
      </Card>
    );
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-lg font-bold text-slate-900">Talent Radar</h3>
          <p className="text-sm text-slate-500">Smart worker recommendations for this shift</p>
        </div>
      </div>

      <Tabs defaultValue="ready" className="space-y-4">
        <TabsList>
          <TabsTrigger value="ready" className="flex items-center gap-2">
            <CheckCircle className="w-4 h-4" />
            Ready Now ({buckets.readyNow.length})
          </TabsTrigger>
          <TabsTrigger value="likely" className="flex items-center gap-2">
            <TrendingUp className="w-4 h-4" />
            Likely Available ({buckets.likelyAvailable.length})
          </TabsTrigger>
          <TabsTrigger value="needs" className="flex items-center gap-2">
            <AlertCircle className="w-4 h-4" />
            Needs Work ({buckets.needsWork.length})
          </TabsTrigger>
        </TabsList>

        <TabsContent value="ready" className="space-y-3">
          <Card className="bg-green-50 border-green-200">
            <CardContent className="p-4">
              <p className="text-sm text-green-800">
                <strong>Ready Now:</strong> These workers have confirmed their availability and are the best match for this shift.
              </p>
            </CardContent>
          </Card>
          {buckets.readyNow.length === 0 ? (
            <p className="text-sm text-slate-500 text-center py-8">No workers confirmed available</p>
          ) : (
            <div className="grid gap-3">
              {buckets.readyNow.map(item => renderWorkerCard(item, 'ready'))}
            </div>
          )}
        </TabsContent>

        <TabsContent value="likely" className="space-y-3">
          <Card className="bg-blue-50 border-blue-200">
            <CardContent className="p-4">
              <p className="text-sm text-blue-800">
                <strong>Likely Available:</strong> These workers haven't confirmed availability but historically accept similar shifts. Assignment requires worker confirmation.
              </p>
            </CardContent>
          </Card>
          {buckets.likelyAvailable.length === 0 ? (
            <p className="text-sm text-slate-500 text-center py-8">No predictions available</p>
          ) : (
            <div className="grid gap-3">
              {buckets.likelyAvailable.map(item => renderWorkerCard(item, 'likely'))}
            </div>
          )}
        </TabsContent>

        <TabsContent value="needs" className="space-y-3">
          <Card className="bg-orange-50 border-orange-200">
            <CardContent className="p-4">
              <p className="text-sm text-orange-800">
                <strong>Needs Work:</strong> These workers are under-scheduled and could benefit from additional hours. They may accept even if not explicitly available.
              </p>
            </CardContent>
          </Card>
          {buckets.needsWork.length === 0 ? (
            <p className="text-sm text-slate-500 text-center py-8">No under-utilized workers</p>
          ) : (
            <div className="grid gap-3">
              {buckets.needsWork.map(item => renderWorkerCard(item, 'needs'))}
            </div>
          )}
        </TabsContent>
      </Tabs>
    </div>
  );
}

// Helper function to calculate match score
function calculateMatchScore(staff, event, availability) {
  let score = 50; // Base score

  // Skill match
  const eventRole = event.shifts?.[0]?.roles?.[0]?.role;
  if (eventRole && staff.position === eventRole) {
    score += 20;
  } else if (eventRole && staff.position_2 === eventRole) {
    score += 10;
  }

  // Reliability
  if (staff.reliability_score) {
    score += (staff.reliability_score / 100) * 15;
  }

  // Compliance
  if (staff.background_check_status === 'cleared') {
    score += 10;
  }

  // Acceptance rate
  if (availability?.acceptance_rate) {
    score += (availability.acceptance_rate / 100) * 5;
  }

  return Math.min(100, Math.round(score));
}