import React from "react";
import { 
  Dialog, 
  DialogContent, 
  DialogHeader, 
  DialogTitle,
} from "@/common/components/ui/dialog";
import EventFormWizard from "./EventFormWizard";
import { useCreateOrder, useListBusinesses, useListHubs } from "@/dataconnect-generated/react";
import { OrderType, OrderStatus } from "@/dataconnect-generated";
import { dataConnect } from "@/features/auth/firebase";
import { useToast } from "@/common/components/ui/use-toast";
import { useQueryClient } from "@tanstack/react-query";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/common/components/ui/select";
import { Label } from "@/common/components/ui/label";

interface CreateOrderDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export default function CreateOrderDialog({ open, onOpenChange }: CreateOrderDialogProps) {
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const [selectedBusinessId, setSelectedBusinessId] = React.useState<string>("");
  const [selectedHubId, setSelectedHubId] = React.useState<string>("");

  const { data: businessesData } = useListBusinesses(dataConnect);
  const { data: hubsData } = useListHubs(dataConnect);

  const createOrderMutation = useCreateOrder(dataConnect, {
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["listOrders"] });
      toast({
        title: "✅ Order Created",
        description: "Your new order has been created successfully.",
      });
      onOpenChange(false);
    },
    onError: (error) => {
      toast({
        title: "❌ Creation Failed",
        description: error.message || "Could not create the order. Please try again.",
        variant: "destructive",
      });
    },
  });

  const handleSubmit = (eventData: Record<string, any>) => {
    if (!selectedBusinessId || !selectedHubId) {
      toast({
        title: "Missing Information",
        description: "Please select a business and a hub.",
        variant: "destructive",
      });
      return;
    }

    // Recalculate requested count from current roles
    const totalRequested = eventData.shifts.reduce((sum: number, shift: any) => {
      const roles = Array.isArray(shift.roles) ? shift.roles : [];
      return sum + roles.reduce((roleSum: number, role: any) => roleSum + (parseInt(role.count) || 0), 0);
    }, 0);

    createOrderMutation.mutate({
      eventName: eventData.event_name,
      businessId: selectedBusinessId,
      teamHubId: selectedHubId,
      orderType: OrderType.RAPID, // Defaulting to RAPID as per common use in this app
      date: eventData.date,
      startDate: eventData.startDate || eventData.date,
      endDate: eventData.endDate,
      notes: eventData.notes,
      shifts: eventData.shifts,
      requested: totalRequested,
      total: eventData.total,
      poReference: eventData.po_reference,
      status: OrderStatus.POSTED
    });
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>Create New Order</DialogTitle>
        </DialogHeader>
        
        <div className="grid grid-cols-2 gap-4 mb-6">
          <div className="space-y-2">
            <Label>Business</Label>
            <Select value={selectedBusinessId} onValueChange={setSelectedBusinessId}>
              <SelectTrigger>
                <SelectValue placeholder="Select Business" />
              </SelectTrigger>
              <SelectContent>
                {businessesData?.businesses.map((b) => (
                  <SelectItem key={b.id} value={b.id}>
                    {b.businessName}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label>Team Hub</Label>
            <Select value={selectedHubId} onValueChange={setSelectedHubId}>
              <SelectTrigger>
                <SelectValue placeholder="Select Hub" />
              </SelectTrigger>
              <SelectContent>
                {hubsData?.hubs.map((h) => (
                  <SelectItem key={h.id} value={h.id}>
                    {h.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </div>

        <EventFormWizard
          event={null}
          onSubmit={handleSubmit}
          isSubmitting={createOrderMutation.isPending}
          currentUser={null}
          onCancel={() => onOpenChange(false)}
        />
      </DialogContent>
    </Dialog>
  );
}
