import React, { useState } from "react";
import { base44 } from "@/api/base44Client";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Card, CardContent, CardHeader, CardTitle } 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, CheckCircle2, Edit2, X, Sparkles, Shield } from "lucide-react";
import { useToast } from "@/components/ui/use-toast";
import { useNavigate } from "react-router-dom";
import { createPageUrl } from "@/utils";

export default function PreferredVendorPanel({ user, compact = false }) {
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const navigate = useNavigate();
  const [showChangeDialog, setShowChangeDialog] = useState(false);

  // Fetch preferred vendor details
  const { data: preferredVendor, isLoading } = useQuery({
    queryKey: ['preferred-vendor', 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 for comparison
  const { data: allVendors } = useQuery({
    queryKey: ['all-vendors'],
    queryFn: () => base44.entities.Vendor.filter({ 
      approval_status: 'approved',
      is_active: true 
    }),
    initialData: [],
  });

  // Remove preferred vendor mutation
  const removePreferredMutation = useMutation({
    mutationFn: () => base44.auth.updateMe({ 
      preferred_vendor_id: null,
      preferred_vendor_name: null 
    }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['current-user'] });
      toast({
        title: "✅ Preferred Vendor Removed",
        description: "You can now select a new preferred vendor",
      });
    },
  });

  // Set preferred vendor mutation
  const setPreferredMutation = useMutation({
    mutationFn: (vendor) => base44.auth.updateMe({ 
      preferred_vendor_id: vendor.id,
      preferred_vendor_name: vendor.legal_name || vendor.doing_business_as 
    }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['current-user'] });
      queryClient.invalidateQueries({ queryKey: ['preferred-vendor'] });
      toast({
        title: "✅ Preferred Vendor Set",
        description: "All new orders will route to this vendor by default",
      });
      setShowChangeDialog(false);
    },
  });

  if (isLoading) {
    return (
      <Card className="border-slate-200">
        <CardContent className="p-6">
          <div className="animate-pulse flex items-center gap-3">
            <div className="w-12 h-12 bg-slate-200 rounded-lg" />
            <div className="flex-1">
              <div className="h-4 bg-slate-200 rounded w-1/2 mb-2" />
              <div className="h-3 bg-slate-200 rounded w-1/3" />
            </div>
          </div>
        </CardContent>
      </Card>
    );
  }

  if (!preferredVendor && !compact) {
    return (
      <Card className="border-2 border-dashed border-blue-300 bg-blue-50/50">
        <CardContent className="p-6 text-center">
          <div className="w-16 h-16 mx-auto mb-4 bg-blue-100 rounded-2xl flex items-center justify-center">
            <Star className="w-8 h-8 text-blue-600" />
          </div>
          <h3 className="font-bold text-lg text-slate-900 mb-2">
            No Preferred Vendor Selected
          </h3>
          <p className="text-sm text-slate-600 mb-4">
            Pick your go-to vendor for faster ordering and consistent service
          </p>
          <Button
            onClick={() => navigate(createPageUrl("VendorMarketplace"))}
            className="bg-blue-600 hover:bg-blue-700"
          >
            <Star className="w-4 h-4 mr-2" />
            Choose Preferred Vendor
          </Button>
        </CardContent>
      </Card>
    );
  }

  if (!preferredVendor) return null;

  if (compact) {
    return (
      <div className="flex items-center gap-3 p-3 bg-gradient-to-r from-blue-50 to-indigo-50 border-2 border-blue-200 rounded-lg">
        <div className="w-10 h-10 bg-blue-600 rounded-lg flex items-center justify-center flex-shrink-0">
          <Award className="w-5 h-5 text-white" />
        </div>
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 mb-0.5">
            <p className="text-xs font-bold text-blue-600 uppercase tracking-wider">Preferred Vendor</p>
            <Badge className="bg-blue-600 text-white text-xs px-2 py-0 border-0">PRIMARY</Badge>
          </div>
          <p className="font-bold text-sm text-slate-900 truncate">
            {preferredVendor.doing_business_as || preferredVendor.legal_name}
          </p>
        </div>
        <Button
          variant="ghost"
          size="sm"
          onClick={() => setShowChangeDialog(true)}
          className="text-blue-600 hover:text-blue-700 hover:bg-blue-100"
        >
          <Edit2 className="w-4 h-4" />
        </Button>
      </div>
    );
  }

  return (
    <>
      <Card className="border-2 border-blue-300 bg-gradient-to-br from-blue-50 via-white to-indigo-50 shadow-lg">
        <CardHeader className="border-b border-blue-200 pb-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="w-12 h-12 bg-gradient-to-br from-blue-600 to-indigo-600 rounded-xl flex items-center justify-center">
                <Award className="w-6 h-6 text-white" />
              </div>
              <div>
                <CardTitle className="text-lg font-bold text-slate-900">Your Preferred Vendor</CardTitle>
                <p className="text-xs text-slate-600 mt-0.5">All orders route here by default</p>
              </div>
            </div>
            <Badge className="bg-blue-600 text-white font-bold px-3 py-1.5 shadow-md">
              PRIMARY
            </Badge>
          </div>
        </CardHeader>
        
        <CardContent className="p-6">
          <div className="space-y-4">
            {/* Vendor Info */}
            <div className="flex items-start gap-4">
              <div className="w-16 h-16 bg-gradient-to-br from-slate-100 to-slate-200 rounded-xl flex items-center justify-center flex-shrink-0">
                <Users className="w-8 h-8 text-slate-600" />
              </div>
              <div className="flex-1">
                <h3 className="font-bold text-xl text-slate-900 mb-1">
                  {preferredVendor.doing_business_as || preferredVendor.legal_name}
                </h3>
                <div className="flex items-center gap-2 flex-wrap">
                  <Badge className="bg-emerald-100 text-emerald-700 text-xs">
                    <CheckCircle2 className="w-3 h-3 mr-1" />
                    Approved
                  </Badge>
                  {preferredVendor.region && (
                    <Badge variant="outline" className="text-xs">
                      <MapPin className="w-3 h-3 mr-1" />
                      {preferredVendor.region}
                    </Badge>
                  )}
                  {preferredVendor.service_specialty && (
                    <Badge variant="outline" className="text-xs">
                      {preferredVendor.service_specialty}
                    </Badge>
                  )}
                </div>
              </div>
            </div>

            {/* Stats */}
            <div className="grid grid-cols-3 gap-3 pt-4 border-t border-slate-200">
              <div className="text-center">
                <p className="text-2xl font-bold text-blue-600">
                  {preferredVendor.workforce_count || 0}
                </p>
                <p className="text-xs text-slate-500 mt-1">Staff Available</p>
              </div>
              <div className="text-center">
                <div className="flex items-center justify-center gap-1">
                  <Star className="w-5 h-5 text-amber-500 fill-amber-500" />
                  <p className="text-2xl font-bold text-slate-900">4.9</p>
                </div>
                <p className="text-xs text-slate-500 mt-1">Rating</p>
              </div>
              <div className="text-center">
                <p className="text-2xl font-bold text-emerald-600">98%</p>
                <p className="text-xs text-slate-500 mt-1">Fill Rate</p>
              </div>
            </div>

            {/* Actions */}
            <div className="flex gap-2 pt-4">
              <Button
                variant="outline"
                className="flex-1"
                onClick={() => setShowChangeDialog(true)}
              >
                <Edit2 className="w-4 h-4 mr-2" />
                Switch Vendor
              </Button>
              <Button
                variant="outline"
                className="flex-1"
                onClick={() => navigate(createPageUrl("VendorMarketplace"))}
              >
                <Sparkles className="w-4 h-4 mr-2" />
                View Market
              </Button>
              <Button
                variant="ghost"
                onClick={() => removePreferredMutation.mutate()}
                disabled={removePreferredMutation.isPending}
                className="text-red-600 hover:text-red-700 hover:bg-red-50"
              >
                <X className="w-4 h-4 mr-2" />
                Remove
              </Button>
            </div>

            {/* Benefits Badge */}
            <div className="bg-gradient-to-r from-green-50 to-emerald-50 border-2 border-green-200 rounded-lg p-3">
              <div className="flex items-center gap-2 text-sm">
                <Shield className="w-4 h-4 text-green-600 flex-shrink-0" />
                <p className="text-green-800 font-medium">
                  <strong>Priority Support:</strong> Faster response times and dedicated account management
                </p>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Change Vendor Dialog */}
      <Dialog open={showChangeDialog} onOpenChange={setShowChangeDialog}>
        <DialogContent className="max-w-3xl max-h-[85vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="text-2xl font-bold flex items-center gap-2">
              <Star className="w-6 h-6 text-blue-600" />
              Select New Preferred Vendor
            </DialogTitle>
            <DialogDescription>
              Choose a vendor to route all your future orders to by default
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-3 mt-4">
            {allVendors.map((vendor) => {
              const isCurrentPreferred = vendor.id === preferredVendor?.id;
              
              return (
                <div
                  key={vendor.id}
                  className={`p-4 rounded-lg border-2 transition-all cursor-pointer ${
                    isCurrentPreferred
                      ? 'border-blue-400 bg-blue-50'
                      : 'border-slate-200 hover:border-blue-300 hover:bg-slate-50'
                  }`}
                  onClick={() => !isCurrentPreferred && setPreferredMutation.mutate(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>
                        {isCurrentPreferred && (
                          <Badge className="bg-blue-600 text-white">
                            Current Preferred
                          </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>
                    {!isCurrentPreferred && (
                      <Button
                        onClick={(e) => {
                          e.stopPropagation();
                          setPreferredMutation.mutate(vendor);
                        }}
                        disabled={setPreferredMutation.isPending}
                        className="bg-blue-600 hover:bg-blue-700"
                      >
                        <CheckCircle2 className="w-4 h-4 mr-2" />
                        Select
                      </Button>
                    )}
                  </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>
        </DialogContent>
      </Dialog>
    </>
  );
}