import React, { useState, useEffect } from "react";
import { base44 } from "@/api/base44Client";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useNavigate } from "react-router-dom";
import { createPageUrl } from "@/utils";
import { Button } from "@/components/ui/button";
import { ArrowLeft, Loader2 } from "lucide-react";
import EventFormWizard from "../components/events/EventFormWizard";
import OrderReductionAlert from "../components/orders/OrderReductionAlert";
import { useToast } from "@/components/ui/use-toast";

export default function EditEvent() {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const { toast } = useToast();
  const urlParams = new URLSearchParams(window.location.search);
  const eventId = urlParams.get('id');
  
  const [showReductionAlert, setShowReductionAlert] = useState(false);
  const [pendingUpdate, setPendingUpdate] = useState(null);
  const [originalRequested, setOriginalRequested] = useState(0);

  const { data: user } = useQuery({
    queryKey: ['current-user-edit-event'],
    queryFn: () => base44.auth.me(),
  });

  const { data: allEvents, isLoading } = useQuery({
    queryKey: ['events'],
    queryFn: () => base44.entities.Event.list(),
    initialData: [],
  });

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

  const event = allEvents.find(e => e.id === eventId);
  
  useEffect(() => {
    if (event) {
      setOriginalRequested(event.requested || 0);
    }
  }, [event]);

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

  const handleSubmit = (eventData) => {
    // CRITICAL: Recalculate requested count from current roles
    const totalRequested = eventData.shifts.reduce((sum, shift) => {
      return sum + shift.roles.reduce((roleSum, role) => roleSum + (parseInt(role.count) || 0), 0);
    }, 0);
    
    const assignedCount = event.assigned_staff?.length || 0;
    const isVendor = user?.user_role === 'vendor' || user?.role === 'vendor';
    
    // If client is reducing headcount and vendor has already assigned staff
    if (!isVendor && totalRequested < originalRequested && assignedCount > totalRequested) {
      setPendingUpdate({ ...eventData, requested: totalRequested });
      setShowReductionAlert(true);
      
      // Notify vendor via email
      if (event.vendor_name) {
        base44.integrations.Core.SendEmail({
          to: `${event.vendor_name}@example.com`,
          subject: `⚠️ Order Reduced: ${event.event_name}`,
          body: `Client has reduced headcount for order: ${event.event_name}\n\nOriginal: ${originalRequested} staff\nNew: ${totalRequested} staff\nCurrently Assigned: ${assignedCount} staff\n\nExcess: ${assignedCount - totalRequested} staff must be removed.\n\nPlease log in to adjust assignments.`
        }).catch(console.error);
      }
      
      toast({
        title: "⚠️ Headcount Reduced",
        description: "Vendor has been notified to adjust staff assignments",
      });
      return;
    }
    
    // Normal update
    updateEventMutation.mutate({ 
      id: eventId, 
      data: { 
        ...eventData, 
        requested: totalRequested 
      } 
    });
  };

  const handleAutoUnassign = async () => {
    if (!pendingUpdate) return;
    
    const assignedStaff = event.assigned_staff || [];
    const excessCount = assignedStaff.length - pendingUpdate.requested;
    
    // Calculate reliability scores for assigned staff
    const staffWithScores = assignedStaff.map(assigned => {
      const staffData = allStaff.find(s => s.id === assigned.staff_id);
      return {
        ...assigned,
        reliability: staffData?.reliability_score || 50,
        total_shifts: staffData?.total_shifts || 0,
        no_shows: staffData?.no_show_count || 0,
        cancellations: staffData?.cancellation_count || 0
      };
    });
    
    // Sort by reliability (lowest first)
    staffWithScores.sort((a, b) => a.reliability - b.reliability);
    
    // Remove lowest reliability staff
    const staffToKeep = staffWithScores.slice(excessCount);
    
    await updateEventMutation.mutateAsync({
      id: eventId,
      data: {
        ...pendingUpdate,
        assigned_staff: staffToKeep.map(s => ({
          staff_id: s.staff_id,
          staff_name: s.staff_name,
          email: s.email,
          role: s.role
        }))
      }
    });
    
    setShowReductionAlert(false);
    setPendingUpdate(null);
    
    toast({
      title: "✅ Staff Auto-Unassigned",
      description: `Removed ${excessCount} lowest reliability staff members`,
    });
  };

  const handleManualUnassign = () => {
    setShowReductionAlert(false);
    toast({
      title: "Manual Adjustment Required",
      description: "Please manually remove excess staff from the order",
    });
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <Loader2 className="w-8 h-8 animate-spin text-blue-600" />
      </div>
    );
  }

  if (!event) {
    return (
      <div className="p-8 text-center">
        <h2 className="text-2xl font-bold text-slate-900 mb-4">Event Not Found</h2>
        <Button onClick={() => navigate(createPageUrl("Events"))}>
          Back to Events
        </Button>
      </div>
    );
  }

  return (
    <div className="p-4 md:p-8">
      <div className="max-w-7xl mx-auto">
        <div className="mb-8">
          <Button
            variant="ghost"
            onClick={() => navigate(createPageUrl("Events"))}
            className="mb-4 hover:bg-slate-100"
          >
            <ArrowLeft className="w-4 h-4 mr-2" />
            Back to Events
          </Button>
          <h1 className="text-3xl md:text-4xl font-bold text-slate-900 mb-2">Edit Event</h1>
          <p className="text-slate-600">Update information for {event.event_name}</p>
        </div>

        {showReductionAlert && pendingUpdate && (
          <div className="mb-6">
            <OrderReductionAlert
              originalRequested={originalRequested}
              newRequested={pendingUpdate.requested}
              currentAssigned={event.assigned_staff?.length || 0}
              onAutoUnassign={handleAutoUnassign}
              onManualUnassign={handleManualUnassign}
              lowReliabilityStaff={(event.assigned_staff || []).map(assigned => {
                const staffData = allStaff.find(s => s.id === assigned.staff_id);
                return {
                  name: assigned.staff_name,
                  reliability: staffData?.reliability_score || 50
                };
              }).sort((a, b) => a.reliability - b.reliability)}
            />
          </div>
        )}

        <EventFormWizard
          event={event}
          onSubmit={handleSubmit}
          isSubmitting={updateEventMutation.isPending}
          currentUser={user}
          onCancel={() => navigate(createPageUrl("Events"))}
        />
      </div>
    </div>
  );
}