import React, { useState } from "react";
import { base44 } from "@/api/base44Client";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Users, Search, Plus, CheckCircle2 } from "lucide-react";
import { useToast } from "@/components/ui/use-toast";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
} from "@/components/ui/command";

export default function QuickAssignPopover({ event, children }) {
  const [open, setOpen] = useState(false);
  const [selectedStaff, setSelectedStaff] = useState([]);
  const { toast } = useToast();
  const queryClient = useQueryClient();

  const { data: allStaff } = useQuery({
    queryKey: ['staff'],
    queryFn: () => base44.entities.Staff.list(),
    initialData: [],
  });

  const updateEventMutation = useMutation({
    mutationFn: ({ id, data }) => base44.entities.Event.update(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['events'] });
      setSelectedStaff([]);
      setOpen(false);
    },
  });

  const requestedCount = event.requested || 0;
  const currentAssigned = event.assigned_staff || [];
  const assignedCount = currentAssigned.length;
  const remainingSlots = requestedCount - assignedCount;

  const handleToggleStaff = (staffId) => {
    setSelectedStaff(prev => {
      if (prev.includes(staffId)) {
        return prev.filter(id => id !== staffId);
      } else {
        // Only allow selection up to remaining slots
        if (remainingSlots > 0 && prev.length >= remainingSlots) {
          toast({
            title: "Selection Limit",
            description: `You can only select ${remainingSlots} more staff member${remainingSlots !== 1 ? 's' : ''}`,
            variant: "destructive"
          });
          return prev;
        }
        return [...prev, staffId];
      }
    });
  };

  const handleAssign = () => {
    if (selectedStaff.length === 0) return;

    if (selectedStaff.length > remainingSlots && remainingSlots > 0) {
      toast({
        title: "Too Many Selected",
        description: `Only ${remainingSlots} slot${remainingSlots !== 1 ? 's' : ''} remaining. Assigning first ${remainingSlots}.`,
        variant: "destructive"
      });
    }

    const staffToAssign = remainingSlots > 0 
      ? selectedStaff.slice(0, remainingSlots)
      : selectedStaff;

    const newAssignments = staffToAssign.map(staffId => {
      const staff = allStaff.find(s => s.id === staffId);
      return {
        staff_id: staff.id,
        staff_name: staff.employee_name,
        position: staff.position || "",
        confirmed: false,
        notified: true,
        notified_at: new Date().toISOString()
      };
    });

    const updatedAssignedStaff = [...currentAssigned, ...newAssignments];
    const newStatus = updatedAssignedStaff.length >= requestedCount ? "Assigned" : "Pending";

    updateEventMutation.mutate({
      id: event.id,
      data: {
        ...event,
        assigned_staff: updatedAssignedStaff,
        assigned: updatedAssignedStaff.length,
        status: newStatus
      }
    });

    toast({
      title: "Staff Assigned",
      description: `${newAssignments.length} staff member${newAssignments.length !== 1 ? 's' : ''} assigned successfully`,
    });
  };

  const availableStaff = allStaff.filter(staff =>
    !currentAssigned.some(assigned => assigned.staff_id === staff.id)
  );

  const canSelectMore = remainingSlots === 0 || selectedStaff.length < remainingSlots;

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild onClick={(e) => e.stopPropagation()}>
        {children}
      </PopoverTrigger>
      <PopoverContent className="w-96 p-0" align="end" onClick={(e) => e.stopPropagation()}>
        <div className="p-4 border-b border-slate-200 space-y-3">
          <div className="flex items-center justify-between">
            <div>
              <h3 className="font-semibold text-sm">Quick Assign Staff</h3>
              <p className="text-xs text-slate-500">{event.event_name}</p>
            </div>
            <Badge variant={remainingSlots === 0 ? "default" : "outline"}>
              {assignedCount} / {requestedCount}
            </Badge>
          </div>

          {remainingSlots > 0 && (
            <div className="bg-blue-50 border border-blue-200 rounded-lg p-2 text-xs text-blue-800">
              Select up to <strong>{remainingSlots}</strong> staff member{remainingSlots !== 1 ? 's' : ''}
            </div>
          )}

          {remainingSlots === 0 && requestedCount > 0 && (
            <div className="bg-green-50 border border-green-200 rounded-lg p-2 text-xs text-green-800 flex items-center gap-2">
              <CheckCircle2 className="w-4 h-4" />
              <span>Fully staffed - no more assignments needed</span>
            </div>
          )}

          {selectedStaff.length > 0 && (
            <Button
              onClick={handleAssign}
              className="w-full bg-blue-600 hover:bg-blue-700 text-sm"
              disabled={updateEventMutation.isPending}
            >
              <Plus className="w-4 h-4 mr-2" />
              Assign {Math.min(selectedStaff.length, remainingSlots || selectedStaff.length)} Staff
            </Button>
          )}
        </div>

        <Command>
          <CommandInput placeholder="Search staff..." />
          <CommandEmpty>No staff found.</CommandEmpty>
          <CommandGroup className="max-h-64 overflow-auto">
            {availableStaff.map((staff) => {
              const isSelected = selectedStaff.includes(staff.id);
              const isDisabled = !canSelectMore && !isSelected && remainingSlots > 0;

              return (
                <CommandItem
                  key={staff.id}
                  onSelect={() => !isDisabled && handleToggleStaff(staff.id)}
                  className={`cursor-pointer ${isDisabled ? 'opacity-50 cursor-not-allowed' : ''}`}
                  disabled={isDisabled}
                >
                  <div className="flex items-center gap-3 w-full">
                    <Checkbox
                      checked={isSelected}
                      disabled={isDisabled}
                      onCheckedChange={() => !isDisabled && handleToggleStaff(staff.id)}
                      onClick={(e) => e.stopPropagation()}
                    />
                    <div className="w-8 h-8 bg-gradient-to-br from-blue-500 to-blue-600 rounded-lg flex items-center justify-center text-white text-xs font-bold">
                      {staff.initial || staff.employee_name?.charAt(0)}
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="font-medium text-slate-900 truncate text-sm">
                        {staff.employee_name}
                      </p>
                      <div className="flex items-center gap-2 text-xs text-slate-500">
                        {staff.position && <span>{staff.position}</span>}
                        {staff.department && (
                          <>
                            <span>•</span>
                            <span>{staff.department}</span>
                          </>
                        )}
                      </div>
                    </div>
                  </div>
                </CommandItem>
              );
            })}
          </CommandGroup>
        </Command>
      </PopoverContent>
    </Popover>
  );
}