import React, { useState } from "react";
import { base44 } from "@/api/base44Client";
import { 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 { Switch } from "@/components/ui/switch";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
import { useToast } from "@/components/ui/use-toast";
import {
  Lock, Unlock, Shield, DollarSign, TrendingUp, AlertTriangle,
  CheckCircle, X, Star, Users, Zap, ArrowRight, Heart, HeartOff,
  Settings, Info, Sparkles
} from "lucide-react";

export default function ClientVendorPreferences({ user, vendors, onUpdate }) {
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const [savingsModal, setSavingsModal] = useState({ open: false, vendor: null, savings: 0 });

  // Get user's locked vendors (vendors they don't want changed)
  const lockedVendorIds = user?.locked_vendor_ids || [];
  const allowOptimization = user?.allow_procurement_optimization !== false; // Default true

  // Calculate potential savings for each non-preferred vendor
  const vendorsWithSavings = vendors.map(vendor => {
    const currentRate = vendor.avgRate || 50;
    const preferredRate = 42; // Tier 1 rate
    const savingsPercent = currentRate > preferredRate ? ((currentRate - preferredRate) / currentRate * 100) : 0;
    const monthlySavings = savingsPercent > 0 ? (currentRate - preferredRate) * 40 * 4 : 0; // 40hrs/week * 4 weeks
    
    return {
      ...vendor,
      potentialSavingsPercent: savingsPercent,
      potentialMonthlySavings: monthlySavings,
      isLocked: lockedVendorIds.includes(vendor.id),
    };
  });

  const updatePreferencesMutation = useMutation({
    mutationFn: (data) => base44.auth.updateMe(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['current-user-marketplace'] });
      onUpdate?.();
    },
  });

  const toggleVendorLock = (vendorId, vendorName) => {
    const newLockedIds = lockedVendorIds.includes(vendorId)
      ? lockedVendorIds.filter(id => id !== vendorId)
      : [...lockedVendorIds, vendorId];

    updatePreferencesMutation.mutate({ locked_vendor_ids: newLockedIds });

    toast({
      title: lockedVendorIds.includes(vendorId) ? "Vendor Unlocked" : "Vendor Locked",
      description: lockedVendorIds.includes(vendorId)
        ? `${vendorName} can now be optimized by Procurement`
        : `${vendorName} will not be changed without your approval`,
    });
  };

  const toggleOptimization = (allowed) => {
    updatePreferencesMutation.mutate({ allow_procurement_optimization: allowed });

    toast({
      title: allowed ? "Optimization Enabled" : "Optimization Disabled",
      description: allowed
        ? "Procurement can suggest vendor optimizations for cost savings"
        : "Your vendor relationships will remain unchanged",
    });
  };

  const handleViewSavings = (vendor) => {
    setSavingsModal({
      open: true,
      vendor,
      savings: vendor.potentialMonthlySavings,
    });
  };

  const handleAcceptSavings = () => {
    // Remove from locked list if locked
    if (savingsModal.vendor?.isLocked) {
      const newLockedIds = lockedVendorIds.filter(id => id !== savingsModal.vendor.id);
      updatePreferencesMutation.mutate({ locked_vendor_ids: newLockedIds });
    }

    toast({
      title: "Optimization Request Submitted",
      description: `We'll find a better rate for your ${savingsModal.vendor?.legal_name} positions`,
    });

    setSavingsModal({ open: false, vendor: null, savings: 0 });
  };

  const totalPotentialSavings = vendorsWithSavings
    .filter(v => !v.isLocked && v.potentialMonthlySavings > 0)
    .reduce((sum, v) => sum + v.potentialMonthlySavings, 0);

  const lockedVendors = vendorsWithSavings.filter(v => v.isLocked);
  const optimizableVendors = vendorsWithSavings.filter(v => !v.isLocked && v.potentialSavingsPercent > 5);

  return (
    <div className="space-y-4">
      {/* Main Control Card */}
      <Card className="border-2 border-slate-200 bg-gradient-to-br from-white to-slate-50">
        <CardHeader className="pb-3">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-[#0A39DF] rounded-xl flex items-center justify-center">
                <Settings className="w-5 h-5 text-white" />
              </div>
              <div>
                <CardTitle className="text-lg">Vendor Preferences</CardTitle>
                <p className="text-sm text-slate-500">Control how your vendors are managed</p>
              </div>
            </div>
          </div>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* Optimization Toggle */}
          <div className="flex items-center justify-between p-4 bg-white rounded-xl border border-slate-200">
            <div className="flex items-center gap-3">
              <div className={`w-10 h-10 rounded-lg flex items-center justify-center ${
                allowOptimization ? 'bg-emerald-100' : 'bg-slate-100'
              }`}>
                {allowOptimization ? (
                  <Sparkles className="w-5 h-5 text-emerald-600" />
                ) : (
                  <Lock className="w-5 h-5 text-slate-500" />
                )}
              </div>
              <div>
                <p className="font-semibold text-slate-900">Allow Procurement Optimization</p>
                <p className="text-sm text-slate-500">
                  {allowOptimization 
                    ? "Procurement can suggest cost-saving vendor changes"
                    : "Your vendor relationships remain unchanged"
                  }
                </p>
              </div>
            </div>
            <Switch
              checked={allowOptimization}
              onCheckedChange={toggleOptimization}
            />
          </div>

          {/* Potential Savings Banner */}
          {allowOptimization && totalPotentialSavings > 0 && (
            <div className="p-4 bg-gradient-to-r from-emerald-50 to-green-50 rounded-xl border border-emerald-200">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-3">
                  <div className="w-12 h-12 bg-emerald-500 rounded-xl flex items-center justify-center">
                    <DollarSign className="w-6 h-6 text-white" />
                  </div>
                  <div>
                    <p className="font-bold text-emerald-900">Potential Monthly Savings</p>
                    <p className="text-sm text-emerald-700">
                      {optimizableVendors.length} vendor(s) eligible for optimization
                    </p>
                  </div>
                </div>
                <div className="text-right">
                  <p className="text-3xl font-bold text-emerald-600">
                    ${totalPotentialSavings.toLocaleString(undefined, { maximumFractionDigits: 0 })}
                  </p>
                  <p className="text-xs text-emerald-600">per month</p>
                </div>
              </div>
            </div>
          )}

          {/* Locked Vendors */}
          {lockedVendors.length > 0 && (
            <div>
              <div className="flex items-center gap-2 mb-3">
                <Lock className="w-4 h-4 text-amber-600" />
                <p className="font-semibold text-slate-700 text-sm">
                  Locked Vendors ({lockedVendors.length})
                </p>
                <Badge className="bg-amber-100 text-amber-700 text-xs">Protected</Badge>
              </div>
              <div className="space-y-2">
                {lockedVendors.map(vendor => (
                  <div 
                    key={vendor.id}
                    className="flex items-center justify-between p-3 bg-amber-50 rounded-lg border border-amber-200"
                  >
                    <div className="flex items-center gap-3">
                      <Avatar className="w-10 h-10">
                        <AvatarFallback className="bg-amber-200 text-amber-800 font-bold">
                          {vendor.legal_name?.charAt(0)}
                        </AvatarFallback>
                      </Avatar>
                      <div>
                        <p className="font-medium text-slate-900">{vendor.legal_name}</p>
                        <p className="text-xs text-slate-500">${vendor.avgRate?.toFixed(0)}/hr avg</p>
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      {vendor.potentialMonthlySavings > 0 && (
                        <Badge className="bg-emerald-100 text-emerald-700 text-xs">
                          Could save ${vendor.potentialMonthlySavings.toFixed(0)}/mo
                        </Badge>
                      )}
                      <Button
                        size="sm"
                        variant="ghost"
                        onClick={() => toggleVendorLock(vendor.id, vendor.legal_name)}
                        className="text-amber-700 hover:text-amber-900 hover:bg-amber-100"
                      >
                        <Unlock className="w-4 h-4 mr-1" />
                        Unlock
                      </Button>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Optimization Opportunities */}
          {allowOptimization && optimizableVendors.length > 0 && (
            <div>
              <div className="flex items-center gap-2 mb-3">
                <TrendingUp className="w-4 h-4 text-emerald-600" />
                <p className="font-semibold text-slate-700 text-sm">
                  Savings Opportunities ({optimizableVendors.length})
                </p>
              </div>
              <div className="space-y-2">
                {optimizableVendors.slice(0, 3).map(vendor => (
                  <div 
                    key={vendor.id}
                    className="flex items-center justify-between p-3 bg-white rounded-lg border border-slate-200 hover:border-emerald-300 hover:bg-emerald-50/50 transition-all"
                  >
                    <div className="flex items-center gap-3">
                      <Avatar className="w-10 h-10">
                        <AvatarFallback className="bg-slate-100 text-slate-700 font-bold">
                          {vendor.legal_name?.charAt(0)}
                        </AvatarFallback>
                      </Avatar>
                      <div>
                        <p className="font-medium text-slate-900">{vendor.legal_name}</p>
                        <div className="flex items-center gap-2">
                          <span className="text-xs text-slate-500">${vendor.avgRate?.toFixed(0)}/hr</span>
                          <ArrowRight className="w-3 h-3 text-emerald-500" />
                          <span className="text-xs text-emerald-600 font-medium">$42/hr</span>
                        </div>
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      <div className="text-right mr-2">
                        <p className="font-bold text-emerald-600">
                          Save ${vendor.potentialMonthlySavings.toFixed(0)}
                        </p>
                        <p className="text-xs text-slate-500">per month</p>
                      </div>
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => toggleVendorLock(vendor.id, vendor.legal_name)}
                        className="border-amber-300 text-amber-700 hover:bg-amber-50"
                      >
                        <Lock className="w-3 h-3 mr-1" />
                        Keep
                      </Button>
                      <Button
                        size="sm"
                        onClick={() => handleViewSavings(vendor)}
                        className="bg-emerald-600 hover:bg-emerald-700 text-white"
                      >
                        <Zap className="w-3 h-3 mr-1" />
                        Optimize
                      </Button>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Info Box */}
          <div className="flex items-start gap-3 p-3 bg-blue-50 rounded-lg border border-blue-200">
            <Info className="w-5 h-5 text-blue-600 mt-0.5 flex-shrink-0" />
            <div className="text-sm text-blue-800">
              <p className="font-medium">How this works:</p>
              <ul className="mt-1 space-y-1 text-blue-700">
                <li>• <strong>Locked vendors</strong> won't be changed without your approval</li>
                <li>• <strong>Optimization</strong> moves orders to preferred vendors for better rates</li>
                <li>• You can lock/unlock vendors anytime</li>
              </ul>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Savings Confirmation Modal */}
      <Dialog open={savingsModal.open} onOpenChange={(open) => setSavingsModal({ ...savingsModal, open })}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <TrendingUp className="w-5 h-5 text-emerald-600" />
              Switch to Preferred Vendor?
            </DialogTitle>
            <DialogDescription>
              Optimize your staffing costs while maintaining quality
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4 py-4">
            {/* Current vs New */}
            <div className="grid grid-cols-2 gap-4">
              <div className="p-4 bg-amber-50 rounded-xl border border-amber-200 text-center">
                <p className="text-xs text-amber-700 font-medium mb-1">CURRENT</p>
                <p className="font-bold text-slate-900">{savingsModal.vendor?.legal_name}</p>
                <p className="text-2xl font-bold text-amber-600 mt-2">
                  ${savingsModal.vendor?.avgRate?.toFixed(0)}/hr
                </p>
              </div>
              <div className="p-4 bg-emerald-50 rounded-xl border border-emerald-200 text-center">
                <p className="text-xs text-emerald-700 font-medium mb-1">PREFERRED</p>
                <p className="font-bold text-slate-900">Tier 1 Vendor</p>
                <p className="text-2xl font-bold text-emerald-600 mt-2">$42/hr</p>
              </div>
            </div>

            {/* Savings Highlight */}
            <div className="p-4 bg-gradient-to-r from-emerald-500 to-green-500 rounded-xl text-white text-center">
              <p className="text-sm opacity-90 mb-1">Your Monthly Savings</p>
              <p className="text-4xl font-bold">
                ${savingsModal.savings.toLocaleString(undefined, { maximumFractionDigits: 0 })}
              </p>
              <p className="text-sm opacity-90 mt-1">Same quality staff • Better rates</p>
            </div>

            {/* Benefits */}
            <div className="space-y-2">
              {[
                "Same quality staff from verified vendors",
                "Priority support and faster response times",
                "Dedicated account manager",
              ].map((benefit, idx) => (
                <div key={idx} className="flex items-center gap-2 text-sm text-slate-700">
                  <CheckCircle className="w-4 h-4 text-emerald-500" />
                  {benefit}
                </div>
              ))}
            </div>
          </div>

          <DialogFooter className="gap-2">
            <Button
              variant="outline"
              onClick={() => {
                toggleVendorLock(savingsModal.vendor?.id, savingsModal.vendor?.legal_name);
                setSavingsModal({ open: false, vendor: null, savings: 0 });
              }}
              className="border-amber-300 text-amber-700 hover:bg-amber-50"
            >
              <Lock className="w-4 h-4 mr-2" />
              Keep Current Vendor
            </Button>
            <Button
              onClick={handleAcceptSavings}
              className="bg-emerald-600 hover:bg-emerald-700"
            >
              <Zap className="w-4 h-4 mr-2" />
              Switch & Save ${savingsModal.savings.toFixed(0)}/mo
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}