import React, { useState } from "react";
import { base44 } from "@/api/base44Client";
import { useQuery } from "@tanstack/react-query";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Award, Star, MapPin, Users, TrendingUp, AlertTriangle, Zap, CheckCircle2, Send } from "lucide-react";

export default function VendorRoutingPanel({ 
  user, 
  selectedVendors = [], 
  onVendorChange,
  isRapid = false 
}) {
  const [showVendorSelector, setShowVendorSelector] = useState(false);
  const [selectionMode, setSelectionMode] = useState('single'); // 'single' | 'multi'

  // Fetch preferred vendor
  const { data: preferredVendor } = useQuery({
    queryKey: ['preferred-vendor-routing', user?.preferred_vendor_id],
    queryFn: async () => {
      if (!user?.preferred_vendor_id) return null;
      const vendors = await base44.entities.Vendor.list();
      return vendors.find(v => v.id === user.preferred_vendor_id);
    },
    enabled: !!user?.preferred_vendor_id,
  });

  // Fetch all approved vendors
  const { data: allVendors } = useQuery({
    queryKey: ['all-vendors-routing'],
    queryFn: () => base44.entities.Vendor.filter({ 
      approval_status: 'approved',
      is_active: true 
    }),
    initialData: [],
  });

  // Auto-select preferred vendor on mount if none selected
  React.useEffect(() => {
    if (preferredVendor && selectedVendors.length === 0) {
      onVendorChange([preferredVendor]);
    }
  }, [preferredVendor]);

  const handleVendorSelect = (vendor) => {
    if (selectionMode === 'single') {
      onVendorChange([vendor]);
      setShowVendorSelector(false);
    } else {
      // Multi-select mode
      const isSelected = selectedVendors.some(v => v.id === vendor.id);
      if (isSelected) {
        onVendorChange(selectedVendors.filter(v => v.id !== vendor.id));
      } else {
        onVendorChange([...selectedVendors, vendor]);
      }
    }
  };

  const handleMultiVendorDone = () => {
    if (selectedVendors.length === 0) {
      alert("Please select at least one vendor");
      return;
    }
    setShowVendorSelector(false);
  };

  const routingMode = selectedVendors.length > 1 ? 'multi' : 'single';

  return (
    <>
      <Card className={`border-2 ${
        isRapid 
          ? 'border-red-300 bg-gradient-to-br from-red-50 to-orange-50' 
          : 'border-blue-300 bg-gradient-to-br from-blue-50 to-indigo-50'
      }`}>
        <CardContent className="p-4">
          <div className="space-y-3">
            {/* Header */}
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <div className={`w-8 h-8 ${
                  isRapid ? 'bg-red-600' : 'bg-blue-600'
                } rounded-lg flex items-center justify-center`}>
                  {isRapid ? (
                    <Zap className="w-4 h-4 text-white" />
                  ) : (
                    <Send className="w-4 h-4 text-white" />
                  )}
                </div>
                <div>
                  <p className="text-xs font-bold text-slate-600 uppercase tracking-wider">
                    {isRapid ? 'RAPID ORDER ROUTING' : 'Order Routing'}
                  </p>
                  <p className="text-xs text-slate-500">
                    {routingMode === 'multi' 
                      ? `Sending to ${selectedVendors.length} vendors` 
                      : 'Default vendor routing'}
                  </p>
                </div>
              </div>
              
              {routingMode === 'multi' && (
                <Badge className="bg-purple-600 text-white font-bold">
                  MULTI-VENDOR
                </Badge>
              )}
            </div>

            {/* Selected Vendor(s) */}
            <div className="space-y-2">
              {selectedVendors.length === 0 && !preferredVendor && (
                <div className="p-3 bg-amber-50 border-2 border-amber-200 rounded-lg">
                  <div className="flex items-center gap-2 text-sm">
                    <AlertTriangle className="w-4 h-4 text-amber-600 flex-shrink-0" />
                    <p className="text-amber-800">
                      <strong>No vendor selected.</strong> Please choose a vendor.
                    </p>
                  </div>
                </div>
              )}

              {selectedVendors.map((vendor) => {
                const isPreferred = vendor.id === preferredVendor?.id;
                
                return (
                  <div
                    key={vendor.id}
                    className="p-3 bg-white border-2 border-slate-200 rounded-lg hover:border-blue-300 transition-all"
                  >
                    <div className="flex items-center justify-between">
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-1">
                          <p className="font-bold text-sm text-slate-900">
                            {vendor.doing_business_as || vendor.legal_name}
                          </p>
                          {isPreferred && (
                            <Badge className="bg-blue-600 text-white text-xs px-2 py-0 border-0">
                              <Award className="w-3 h-3 mr-1" />
                              Preferred
                            </Badge>
                          )}
                        </div>
                        <div className="flex items-center gap-2 text-xs text-slate-500">
                          {vendor.region && (
                            <span className="flex items-center gap-1">
                              <MapPin className="w-3 h-3" />
                              {vendor.region}
                            </span>
                          )}
                          <span className="flex items-center gap-1">
                            <Users className="w-3 h-3" />
                            {vendor.workforce_count || 0} staff
                          </span>
                        </div>
                      </div>
                      {routingMode === 'multi' && (
                        <CheckCircle2 className="w-5 h-5 text-green-600 flex-shrink-0" />
                      )}
                    </div>
                  </div>
                );
              })}
            </div>

            {/* Action Buttons */}
            <div className="grid grid-cols-2 gap-2 pt-2 border-t border-slate-200">
              <Button
                variant="outline"
                size="sm"
                onClick={() => {
                  setSelectionMode('single');
                  setShowVendorSelector(true);
                }}
                className="text-xs"
              >
                {selectedVendors.length === 0 ? 'Choose Vendor' : 'Change Vendor'}
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={() => {
                  setSelectionMode('multi');
                  setShowVendorSelector(true);
                }}
                className="text-xs bg-purple-50 border-purple-300 text-purple-700 hover:bg-purple-100"
              >
                <Zap className="w-3 h-3 mr-1" />
                Multi-Vendor
              </Button>
            </div>

            {/* Info Banner */}
            {routingMode === 'multi' && (
              <div className="bg-purple-50 border-2 border-purple-200 rounded-lg p-2">
                <p className="text-xs text-purple-800">
                  <strong>Multi-Vendor Mode:</strong> Order sent to all selected vendors. 
                  First to confirm gets the job.
                </p>
              </div>
            )}

            {isRapid && (
              <div className="bg-red-50 border-2 border-red-200 rounded-lg p-2">
                <p className="text-xs text-red-800">
                  <strong>RAPID Priority:</strong> This order will be marked urgent with priority notification.
                </p>
              </div>
            )}
          </div>
        </CardContent>
      </Card>

      {/* Vendor Selector Dialog */}
      <Dialog open={showVendorSelector} onOpenChange={setShowVendorSelector}>
        <DialogContent className="max-w-3xl max-h-[85vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="text-2xl font-bold flex items-center gap-2">
              {selectionMode === 'multi' ? (
                <>
                  <Zap className="w-6 h-6 text-purple-600" />
                  Select Multiple Vendors
                </>
              ) : (
                <>
                  <Send className="w-6 h-6 text-blue-600" />
                  Select Vendor
                </>
              )}
            </DialogTitle>
            <DialogDescription>
              {selectionMode === 'multi' 
                ? 'Select multiple vendors to send this order to all at once. First to confirm gets the job.'
                : 'Choose which vendor should receive this order'}
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-3 mt-4">
            {allVendors.map((vendor) => {
              const isSelected = selectedVendors.some(v => v.id === vendor.id);
              const isPreferred = vendor.id === preferredVendor?.id;
              
              return (
                <div
                  key={vendor.id}
                  className={`p-4 rounded-lg border-2 transition-all cursor-pointer ${
                    isSelected
                      ? 'border-blue-400 bg-blue-50'
                      : 'border-slate-200 hover:border-blue-300 hover:bg-slate-50'
                  }`}
                  onClick={() => handleVendorSelect(vendor)}
                >
                  <div className="flex items-center justify-between">
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-2">
                        <h3 className="font-bold text-lg text-slate-900">
                          {vendor.doing_business_as || vendor.legal_name}
                        </h3>
                        {isPreferred && (
                          <Badge className="bg-blue-600 text-white">
                            <Award className="w-3 h-3 mr-1" />
                            Preferred
                          </Badge>
                        )}
                        {isSelected && selectionMode === 'multi' && (
                          <Badge className="bg-green-600 text-white">
                            <CheckCircle2 className="w-3 h-3 mr-1" />
                            Selected
                          </Badge>
                        )}
                      </div>
                      <div className="flex items-center gap-2 flex-wrap mb-2">
                        {vendor.region && (
                          <Badge variant="outline" className="text-xs">
                            <MapPin className="w-3 h-3 mr-1" />
                            {vendor.region}
                          </Badge>
                        )}
                        {vendor.service_specialty && (
                          <Badge variant="outline" className="text-xs">
                            {vendor.service_specialty}
                          </Badge>
                        )}
                      </div>
                      <div className="flex items-center gap-4 text-sm text-slate-600">
                        <span className="flex items-center gap-1">
                          <Users className="w-4 h-4" />
                          {vendor.workforce_count || 0} staff
                        </span>
                        <span className="flex items-center gap-1">
                          <Star className="w-4 h-4 text-amber-500 fill-amber-500" />
                          4.9
                        </span>
                        <span className="flex items-center gap-1">
                          <TrendingUp className="w-4 h-4 text-green-600" />
                          98% fill rate
                        </span>
                      </div>
                    </div>
                  </div>
                </div>
              );
            })}

            {allVendors.length === 0 && (
              <div className="text-center py-8 text-slate-400">
                <Users className="w-12 h-12 mx-auto mb-3 opacity-50" />
                <p className="font-medium">No vendors available</p>
              </div>
            )}
          </div>

          {selectionMode === 'multi' && (
            <div className="flex items-center justify-between pt-4 border-t">
              <p className="text-sm text-slate-600">
                {selectedVendors.length} vendor{selectedVendors.length !== 1 ? 's' : ''} selected
              </p>
              <Button
                onClick={handleMultiVendorDone}
                disabled={selectedVendors.length === 0}
                className="bg-purple-600 hover:bg-purple-700"
              >
                <CheckCircle2 className="w-4 h-4 mr-2" />
                Confirm Selection
              </Button>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </>
  );
}