import React, { useState } from "react";
import { base44 } from "@/api/base44Client";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Calendar } from "@/components/ui/calendar";
import { Calendar as CalendarIcon, Users, Loader2, CheckCircle2, X } from "lucide-react";
import { useToast } from "@/components/ui/use-toast";
import { format } from "date-fns";
import { Badge } from "@/components/ui/badge";

export default function QuickReorderModal({ event, open, onOpenChange }) {
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const [selectedDates, setSelectedDates] = useState([]);
  const [formData, setFormData] = useState({
    requested: event?.requested || 1,
    notes: event?.notes || ""
  });

  const createEventsMutation = useMutation({
    mutationFn: async (ordersData) => {
      // Create multiple orders, one for each date
      const promises = ordersData.map(orderData => 
        base44.entities.Event.create(orderData)
      );
      return Promise.all(promises);
    },
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ['events'] });
      queryClient.invalidateQueries({ queryKey: ['client-events'] });
      toast({
        title: `${data.length} Order${data.length > 1 ? 's' : ''} Created Successfully! 🎉`,
        description: `Your order${data.length > 1 ? 's have' : ' has'} been placed and ${data.length > 1 ? 'are' : 'is'} pending confirmation.`,
      });
      onOpenChange(false);
      setSelectedDates([]);
    },
  });

  const handleDateSelect = (dates) => {
    setSelectedDates(dates || []);
  };

  const handleRemoveDate = (dateToRemove) => {
    setSelectedDates(selectedDates.filter(d => d.getTime() !== dateToRemove.getTime()));
  };

  const handleQuickReorder = () => {
    if (selectedDates.length === 0) {
      toast({
        title: "Date Required",
        description: "Please select at least one date for your order",
        variant: "destructive"
      });
      return;
    }

    // Create an order for each selected date
    const ordersData = selectedDates.map(date => ({
      event_name: event.event_name,
      business_id: event.business_id,
      business_name: event.business_name,
      hub: event.hub,
      event_location: event.event_location,
      event_type: event.event_type,
      client_name: event.client_name,
      client_email: event.client_email,
      client_phone: event.client_phone,
      client_address: event.client_address,
      date: format(date, 'yyyy-MM-dd'),
      requested: formData.requested,
      notes: formData.notes,
      status: "Pending",
      assigned: 0,
      assigned_staff: []
    }));

    createEventsMutation.mutate(ordersData);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[700px] max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <div className="flex items-center justify-center mb-4">
            <div className="w-16 h-16 bg-gradient-to-br from-[#0A39DF] to-[#1C323E] rounded-full flex items-center justify-center shadow-lg">
              <CheckCircle2 className="w-8 h-8 text-white" />
            </div>
          </div>
          <DialogTitle className="text-center text-2xl text-[#1C323E]">Quick Reorder</DialogTitle>
          <DialogDescription className="text-center text-base">
            Reorder "<strong className="text-[#0A39DF]">{event?.event_name}</strong>" - Select multiple dates
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-6 py-4">
          {/* Event Summary */}
          <div className="bg-gradient-to-br from-[#0A39DF]/5 to-[#1C323E]/5 rounded-lg p-4 border border-[#0A39DF]/20">
            <div className="space-y-2 text-sm">
              <div className="flex justify-between">
                <span className="text-slate-600">Service:</span>
                <span className="font-semibold text-[#1C323E]">{event?.event_name}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-slate-600">Location:</span>
                <span className="font-semibold text-[#1C323E]">{event?.event_location || "Same as before"}</span>
              </div>
            </div>
          </div>

          {/* Calendar - Multi Date Selection */}
          <div className="space-y-3">
            <Label className="text-base font-semibold flex items-center gap-2 text-[#1C323E]">
              <CalendarIcon className="w-5 h-5 text-[#0A39DF]" />
              Select Event Dates * (Click multiple dates)
            </Label>
            <div className="border-2 border-[#0A39DF]/30 rounded-lg p-4 bg-white">
              <Calendar
                mode="multiple"
                selected={selectedDates}
                onSelect={handleDateSelect}
                className="rounded-md"
                disabled={(date) => date < new Date()}
              />
            </div>
            
            {/* Selected Dates Display */}
            {selectedDates.length > 0 && (
              <div className="space-y-2">
                <div className="flex items-center justify-between">
                  <Label className="text-sm font-medium text-[#1C323E]">
                    Selected Dates ({selectedDates.length})
                  </Label>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => setSelectedDates([])}
                    className="text-xs text-red-600 hover:text-red-700 hover:bg-red-50"
                  >
                    Clear All
                  </Button>
                </div>
                <div className="flex flex-wrap gap-2 max-h-32 overflow-y-auto p-2 bg-slate-50 rounded-lg border border-slate-200">
                  {selectedDates.sort((a, b) => a - b).map((date, index) => (
                    <Badge 
                      key={index} 
                      className="bg-[#0A39DF] text-white px-3 py-1.5 flex items-center gap-2 hover:bg-[#0A39DF]/90"
                    >
                      <CalendarIcon className="w-3 h-3" />
                      {format(date, 'MMM d, yyyy')}
                      <button
                        onClick={() => handleRemoveDate(date)}
                        className="hover:bg-white/20 rounded-full p-0.5"
                      >
                        <X className="w-3 h-3" />
                      </button>
                    </Badge>
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* Staff Count */}
          <div className="space-y-2">
            <Label htmlFor="requested" className="text-base font-semibold flex items-center gap-2 text-[#1C323E]">
              <Users className="w-4 h-4 text-[#0A39DF]" />
              Number of Staff Needed
            </Label>
            <Input
              id="requested"
              type="number"
              min="1"
              value={formData.requested}
              onChange={(e) => setFormData({ ...formData, requested: parseInt(e.target.value) || 1 })}
              className="text-lg font-semibold border-2 border-[#0A39DF]/30 focus:border-[#0A39DF]"
            />
          </div>

          {/* Notes */}
          <div className="space-y-2">
            <Label htmlFor="notes" className="text-base font-semibold text-[#1C323E]">
              Special Instructions (Optional)
            </Label>
            <Textarea
              id="notes"
              value={formData.notes}
              onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
              placeholder="Any changes or special requests..."
              rows={3}
              className="border-2 border-[#0A39DF]/30 focus:border-[#0A39DF]"
            />
          </div>

          {/* Summary */}
          {selectedDates.length > 0 && (
            <div className="bg-gradient-to-r from-[#0A39DF]/10 to-[#1C323E]/10 rounded-lg p-4 border-2 border-[#0A39DF]/30">
              <p className="text-sm font-semibold text-[#1C323E] mb-2">Order Summary:</p>
              <ul className="text-sm text-slate-700 space-y-1">
                <li>• <strong>{selectedDates.length}</strong> order{selectedDates.length > 1 ? 's' : ''} will be created</li>
                <li>• <strong>{formData.requested}</strong> staff per event</li>
                <li>• Total: <strong className="text-[#0A39DF]">{selectedDates.length * formData.requested}</strong> staff across all dates</li>
              </ul>
            </div>
          )}
        </div>

        <DialogFooter className="gap-2">
          <Button
            variant="outline"
            onClick={() => onOpenChange(false)}
            disabled={createEventsMutation.isPending}
            className="flex-1 border-slate-300"
          >
            Cancel
          </Button>
          <Button
            onClick={handleQuickReorder}
            disabled={createEventsMutation.isPending || selectedDates.length === 0}
            className="flex-1 bg-gradient-to-r from-[#0A39DF] to-[#1C323E] hover:from-[#0A39DF]/90 hover:to-[#1C323E]/90 text-white shadow-lg"
          >
            {createEventsMutation.isPending ? (
              <>
                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                Creating {selectedDates.length} Order{selectedDates.length > 1 ? 's' : ''}...
              </>
            ) : (
              <>
                <CheckCircle2 className="w-4 h-4 mr-2" />
                Place {selectedDates.length || 0} Order{selectedDates.length !== 1 ? 's' : ''}
              </>
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}