import React, { useState } from "react";
import { base44 } from "@/api/base44Client";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { useToast } from "@/components/ui/use-toast";
import { Edit2, Trash2, ArrowLeftRight, Clock, MapPin, Check, X } from "lucide-react";
import { format } from "date-fns";
import { calculateOrderStatus } from "../orders/OrderStatusUtils";

export default function AssignedStaffManager({ event, shift, role }) {
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const [editTarget, setEditTarget] = useState(null);
  const [swapTarget, setSwapTarget] = useState(null);
  const [editTimes, setEditTimes] = useState({ start: "", end: "" });

  // Get assigned staff for this role
  const assignedStaff = (event.assigned_staff || []).filter(
    s => s.role === role?.role
  );

  // Remove staff mutation
  const removeMutation = useMutation({
    mutationFn: async (staffId) => {
      const updatedAssignedStaff = (event.assigned_staff || []).filter(
        s => s.staff_id !== staffId || s.role !== role.role
      );

      const updatedShifts = (event.shifts || []).map(s => {
        if (s.shift_name === shift.shift_name) {
          const updatedRoles = (s.roles || []).map(r => {
            if (r.role === role.role) {
              return {
                ...r,
                assigned: Math.max((r.assigned || 0) - 1, 0),
              };
            }
            return r;
          });
          return { ...s, roles: updatedRoles };
        }
        return s;
      });

      const updatedEvent = {
        assigned_staff: updatedAssignedStaff,
        shifts: updatedShifts,
        // NEVER MODIFY REQUESTED - it's set by client, not by staff assignment
      };
      
      // Auto-update status based on staffing level
      updatedEvent.status = calculateOrderStatus({
        ...event,
        ...updatedEvent
      });
      
      await base44.entities.Event.update(event.id, updatedEvent);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['events'] });
      toast({
        title: "✅ Staff Removed",
        description: "Staff member has been removed from this assignment",
      });
    },
  });

  // Edit times mutation
  const editMutation = useMutation({
    mutationFn: async () => {
      const updatedShifts = (event.shifts || []).map(s => {
        if (s.shift_name === shift.shift_name) {
          const updatedRoles = (s.roles || []).map(r => {
            if (r.role === role.role) {
              return {
                ...r,
                start_time: editTimes.start,
                end_time: editTimes.end,
              };
            }
            return r;
          });
          return { ...s, roles: updatedRoles };
        }
        return s;
      });

      await base44.entities.Event.update(event.id, {
        shifts: updatedShifts,
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['events'] });
      toast({
        title: "✅ Times Updated",
        description: "Assignment times have been updated",
      });
      setEditTarget(null);
    },
  });

  const handleEdit = (staff) => {
    setEditTarget(staff);
    setEditTimes({
      start: role.start_time || "09:00",
      end: role.end_time || "17:00",
    });
  };

  const handleSaveEdit = () => {
    editMutation.mutate();
  };

  const handleRemove = (staffId) => {
    if (confirm("Are you sure you want to remove this staff member?")) {
      removeMutation.mutate(staffId);
    }
  };

  if (!assignedStaff.length) {
    return (
      <div className="text-center py-6 text-slate-500 text-sm">
        No staff assigned yet
      </div>
    );
  }

  return (
    <>
      <div className="space-y-2">
        {assignedStaff.map((staff) => (
          <div
            key={staff.staff_id}
            className="flex items-center gap-3 p-3 bg-white border border-slate-200 rounded-lg hover:shadow-sm transition-shadow"
          >
            <Avatar className="w-10 h-10 bg-gradient-to-br from-blue-400 to-blue-500">
              <AvatarFallback className="text-white font-bold">
                {staff.staff_name?.charAt(0) || 'S'}
              </AvatarFallback>
            </Avatar>

            <div className="flex-1 min-w-0">
              <p className="font-medium text-slate-900">{staff.staff_name}</p>
              <div className="flex items-center gap-2 text-xs text-slate-600">
                <Badge variant="outline" className="text-xs">
                  {staff.role}
                </Badge>
                {role.start_time && role.end_time && (
                  <span className="flex items-center gap-1">
                    <Clock className="w-3 h-3" />
                    {role.start_time} - {role.end_time}
                  </span>
                )}
              </div>
            </div>

            <div className="flex items-center gap-1">
              <Button
                variant="ghost"
                size="sm"
                onClick={() => handleEdit(staff)}
                className="h-8 w-8 p-0"
                title="Edit times"
              >
                <Edit2 className="w-4 h-4 text-slate-600" />
              </Button>
              <Button
                variant="ghost"
                size="sm"
                onClick={() => handleRemove(staff.staff_id)}
                disabled={removeMutation.isPending}
                className="h-8 w-8 p-0"
                title="Remove"
              >
                <Trash2 className="w-4 h-4 text-red-600" />
              </Button>
            </div>
          </div>
        ))}
      </div>

      {/* Edit Times Dialog */}
      <Dialog open={!!editTarget} onOpenChange={() => setEditTarget(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Edit Assignment Times</DialogTitle>
          </DialogHeader>
          
          <div className="space-y-4">
            <div>
              <Label>Staff Member</Label>
              <p className="text-sm font-medium mt-1">{editTarget?.staff_name}</p>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>Start Time</Label>
                <Input
                  type="time"
                  value={editTimes.start}
                  onChange={(e) => setEditTimes({ ...editTimes, start: e.target.value })}
                />
              </div>
              <div>
                <Label>End Time</Label>
                <Input
                  type="time"
                  value={editTimes.end}
                  onChange={(e) => setEditTimes({ ...editTimes, end: e.target.value })}
                />
              </div>
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setEditTarget(null)}>
              <X className="w-4 h-4 mr-2" />
              Cancel
            </Button>
            <Button
              onClick={handleSaveEdit}
              disabled={editMutation.isPending}
              className="bg-blue-600 hover:bg-blue-700"
            >
              <Check className="w-4 h-4 mr-2" />
              {editMutation.isPending ? "Saving..." : "Save Changes"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}