import React, { useState } from "react";
import { DragDropContext, Droppable, Draggable } from "@hello-pangea/dnd";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Calendar, Clock, MapPin, Star } from "lucide-react";
import { format } from "date-fns";
import { validateWorkerAssignment } from "./DoubleBookingValidator";
import DoubleBookingOverrideDialog from "./DoubleBookingOverrideDialog";
import { useToast } from "@/components/ui/use-toast";
import { useQuery } from "@tanstack/react-query";
import { base44 } from "@/api/base44Client";

/**
 * Drag & Drop Scheduler Widget
 * Interactive visual scheduler for easy staff assignment
 */

export default function DragDropScheduler({ events, staff, onAssign, onUnassign }) {
  const [localEvents, setLocalEvents] = useState(events || []);
  const [localStaff, setLocalStaff] = useState(staff || []);
  const [overrideDialog, setOverrideDialog] = useState({ open: false, conflict: null, staffMember: null, eventId: null });
  const { toast } = useToast();
  
  const { data: user } = useQuery({
    queryKey: ['current-user-scheduler'],
    queryFn: () => base44.auth.me(),
  });
  
  const { data: allEvents = [] } = useQuery({
    queryKey: ['all-events-conflict-check'],
    queryFn: () => base44.entities.Event.list(),
    initialData: events,
  });
  
  const userRole = user?.user_role || user?.role || 'admin';
  
  const handleDragEnd = (result) => {
    const { source, destination, draggableId } = result;
    
    if (!destination) return;
    
    // Dragging from unassigned to event
    if (source.droppableId === "unassigned" && destination.droppableId.startsWith("event-")) {
      const eventId = destination.droppableId.replace("event-", "");
      const staffMember = localStaff.find(s => s.id === draggableId);
      const targetEvent = localEvents.find(e => e.id === eventId);
      
      if (!staffMember || !targetEvent) return;
      
      // Validate double booking
      const targetShift = targetEvent.shifts?.[0] || {};
      const validation = validateWorkerAssignment(
        staffMember.id,
        targetEvent,
        targetShift,
        allEvents,
        userRole
      );
      
      if (!validation.valid) {
        if (validation.conflict?.canOverride) {
          // Show override dialog for vendors
          setOverrideDialog({
            open: true,
            conflict: validation.conflict,
            staffMember,
            eventId
          });
        } else {
          // Hard block
          toast({
            title: "❌ Assignment Blocked",
            description: validation.message,
            variant: "destructive",
          });
        }
        return;
      }
      
      if (staffMember && onAssign) {
        onAssign(eventId, staffMember);
        
        // Update local state
        setLocalStaff(prev => prev.filter(s => s.id !== draggableId));
        setLocalEvents(prev => prev.map(e => {
          if (e.id === eventId) {
            return {
              ...e,
              assigned_staff: [...(e.assigned_staff || []), {
                staff_id: staffMember.id,
                staff_name: staffMember.employee_name,
                email: staffMember.email,
              }]
            };
          }
          return e;
        }));
      }
    }
    
    // Dragging from event back to unassigned
    if (source.droppableId.startsWith("event-") && destination.droppableId === "unassigned") {
      const eventId = source.droppableId.replace("event-", "");
      const event = localEvents.find(e => e.id === eventId);
      const staffMember = event?.assigned_staff?.find(s => s.staff_id === draggableId);
      
      if (staffMember && onUnassign) {
        onUnassign(eventId, draggableId);
        
        // Update local state
        setLocalEvents(prev => prev.map(e => {
          if (e.id === eventId) {
            return {
              ...e,
              assigned_staff: e.assigned_staff.filter(s => s.staff_id !== draggableId)
            };
          }
          return e;
        }));
        
        const fullStaff = staff.find(s => s.id === draggableId);
        if (fullStaff) {
          setLocalStaff(prev => [...prev, fullStaff]);
        }
      }
    }
    
    // Dragging between events
    if (source.droppableId.startsWith("event-") && destination.droppableId.startsWith("event-")) {
      const sourceEventId = source.droppableId.replace("event-", "");
      const destEventId = destination.droppableId.replace("event-", "");
      
      if (sourceEventId === destEventId) return;
      
      const sourceEvent = localEvents.find(e => e.id === sourceEventId);
      const staffMember = sourceEvent?.assigned_staff?.find(s => s.staff_id === draggableId);
      
      if (staffMember) {
        onUnassign(sourceEventId, draggableId);
        onAssign(destEventId, staff.find(s => s.id === draggableId));
        
        setLocalEvents(prev => prev.map(e => {
          if (e.id === sourceEventId) {
            return {
              ...e,
              assigned_staff: e.assigned_staff.filter(s => s.staff_id !== draggableId)
            };
          }
          if (e.id === destEventId) {
            return {
              ...e,
              assigned_staff: [...(e.assigned_staff || []), staffMember]
            };
          }
          return e;
        }));
      }
    }
  };
  
  const handleOverrideConfirm = () => {
    const { staffMember, eventId } = overrideDialog;
    
    // Proceed with assignment
    setLocalStaff(localStaff.filter(s => s.id !== staffMember.id));
    
    setLocalEvents(localEvents.map(event => {
      if (event.id === eventId) {
        return {
          ...event,
          assigned_staff: [...(event.assigned_staff || []), { staff_id: staffMember.id, staff_name: staffMember.employee_name }]
        };
      }
      return event;
    }));
    
    onAssign(eventId, staffMember);
    setOverrideDialog({ open: false, conflict: null, staffMember: null, eventId: null });
    
    toast({
      title: "✅ Double Shift Assigned",
      description: `${staffMember.employee_name} has been assigned with vendor override`,
    });
  };

  return (
    <>
      <DragDropContext onDragEnd={handleDragEnd}>
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Unassigned Staff Pool */}
        <Card className="lg:col-span-1">
          <CardHeader>
            <CardTitle className="text-base">Available Staff</CardTitle>
            <p className="text-sm text-slate-500">{localStaff.length} unassigned</p>
          </CardHeader>
          <CardContent>
            <Droppable droppableId="unassigned">
              {(provided, snapshot) => (
                <div
                  ref={provided.innerRef}
                  {...provided.droppableProps}
                  className={`min-h-[400px] rounded-lg p-3 transition-colors ${
                    snapshot.isDraggingOver ? 'bg-blue-50 border-2 border-blue-300' : 'bg-slate-50'
                  }`}
                >
                  {localStaff.map((s, index) => (
                    <Draggable key={s.id} draggableId={s.id} index={index}>
                      {(provided, snapshot) => (
                        <div
                          ref={provided.innerRef}
                          {...provided.draggableProps}
                          {...provided.dragHandleProps}
                          className={`bg-white rounded-lg p-3 mb-2 border border-slate-200 shadow-sm ${
                            snapshot.isDragging ? 'shadow-lg ring-2 ring-blue-400' : 'hover:shadow-md'
                          } transition-all cursor-move`}
                        >
                          <div className="flex items-center gap-3">
                            <Avatar className="w-10 h-10">
                              <AvatarFallback className="bg-blue-100 text-blue-700 font-bold">
                                {s.employee_name?.charAt(0)}
                              </AvatarFallback>
                            </Avatar>
                            <div className="flex-1 min-w-0">
                              <p className="font-semibold text-sm truncate">{s.employee_name}</p>
                              <p className="text-xs text-slate-500">{s.position}</p>
                              <div className="flex items-center gap-2 mt-1">
                                <Badge variant="outline" className="text-xs">
                                  <Star className="w-3 h-3 mr-1 text-amber-500" />
                                  {s.rating || 4.5}
                                </Badge>
                                <Badge variant="outline" className="text-xs">
                                  {s.reliability_score || 95}% reliable
                                </Badge>
                              </div>
                            </div>
                          </div>
                        </div>
                      )}
                    </Draggable>
                  ))}
                  {provided.placeholder}
                  {localStaff.length === 0 && (
                    <p className="text-center text-slate-400 mt-8">All staff assigned</p>
                  )}
                </div>
              )}
            </Droppable>
          </CardContent>
        </Card>
        
        {/* Events Schedule */}
        <div className="lg:col-span-2 space-y-4">
          {localEvents.map(event => (
            <Card key={event.id}>
              <CardHeader>
                <div className="flex items-start justify-between">
                  <div>
                    <CardTitle className="text-base">{event.event_name}</CardTitle>
                    <div className="flex items-center gap-4 mt-2 text-sm text-slate-500">
                      <span className="flex items-center gap-1">
                        <Calendar className="w-4 h-4" />
                        {format(new Date(event.date), 'MMM d, yyyy')}
                      </span>
                      <span className="flex items-center gap-1">
                        <MapPin className="w-4 h-4" />
                        {event.hub || event.event_location}
                      </span>
                    </div>
                  </div>
                  <Badge className={
                    (event.assigned_staff?.length || 0) >= (event.requested || 0)
                      ? "bg-green-100 text-green-700"
                      : "bg-amber-100 text-amber-700"
                  }>
                    {event.assigned_staff?.length || 0}/{event.requested || 0} filled
                  </Badge>
                </div>
              </CardHeader>
              <CardContent>
                <Droppable droppableId={`event-${event.id}`}>
                  {(provided, snapshot) => (
                    <div
                      ref={provided.innerRef}
                      {...provided.droppableProps}
                      className={`min-h-[120px] rounded-lg p-3 transition-colors ${
                        snapshot.isDraggingOver ? 'bg-green-50 border-2 border-green-300' : 'bg-slate-50'
                      }`}
                    >
                      <div className="grid grid-cols-2 gap-2">
                        {event.assigned_staff?.map((s, index) => (
                          <Draggable key={s.staff_id} draggableId={s.staff_id} index={index}>
                            {(provided, snapshot) => (
                              <div
                                ref={provided.innerRef}
                                {...provided.draggableProps}
                                {...provided.dragHandleProps}
                                className={`bg-white rounded-lg p-2 border border-slate-200 ${
                                  snapshot.isDragging ? 'shadow-lg ring-2 ring-green-400' : ''
                                } cursor-move`}
                              >
                                <div className="flex items-center gap-2">
                                  <Avatar className="w-8 h-8">
                                    <AvatarFallback className="bg-green-100 text-green-700 text-xs">
                                      {s.staff_name?.charAt(0)}
                                    </AvatarFallback>
                                  </Avatar>
                                  <div className="flex-1 min-w-0">
                                    <p className="font-medium text-xs truncate">{s.staff_name}</p>
                                    <p className="text-xs text-slate-500">{s.role}</p>
                                  </div>
                                </div>
                              </div>
                            )}
                          </Draggable>
                        ))}
                      </div>
                      {provided.placeholder}
                      {(!event.assigned_staff || event.assigned_staff.length === 0) && (
                        <p className="text-center text-slate-400 text-sm py-8">
                          Drag staff here to assign
                        </p>
                      )}
                    </div>
                  )}
                </Droppable>
              </CardContent>
            </Card>
          ))}
        </div>
      </div>
    </DragDropContext>
    
    <DoubleBookingOverrideDialog
      open={overrideDialog.open}
      onClose={() => setOverrideDialog({ open: false, conflict: null, staffMember: null, eventId: null })}
      conflict={overrideDialog.conflict}
      workerName={overrideDialog.staffMember?.employee_name || ''}
      onConfirm={handleOverrideConfirm}
    />
    </>
  );
}