import React from "react";
import { base44 } from "@/api/base44Client";
import { useQuery } from "@tanstack/react-query";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Progress } from "@/components/ui/progress";
import {
  Heart, HeartOff, Shield, AlertTriangle, TrendingUp, 
  Users, Lock, Unlock, Star, DollarSign, ArrowRight
} from "lucide-react";

export default function ClientLoyaltyCard({ vendorId, vendorName }) {
  // Fetch all users to check who has this vendor locked
  const { data: users = [] } = useQuery({
    queryKey: ['users-loyalty', vendorId],
    queryFn: async () => {
      const allUsers = await base44.entities.User.list();
      return allUsers.filter(u => 
        u.user_role === 'client' || u.role === 'client'
      );
    },
    initialData: [],
  });

  // Fetch businesses/clients that have worked with this vendor
  const { data: events = [] } = useQuery({
    queryKey: ['vendor-events-loyalty', vendorId],
    queryFn: async () => {
      const allEvents = await base44.entities.Event.list();
      return allEvents.filter(e => 
        e.vendor_name === vendorName || e.vendor_id === vendorId
      );
    },
    initialData: [],
  });

  // Get unique clients from events
  const uniqueClients = [...new Set(events.map(e => e.business_name).filter(Boolean))];

  // Categorize clients
  const loyalClients = users.filter(u => 
    u.locked_vendor_ids?.includes(vendorId) ||
    u.preferred_vendor_id === vendorId
  );

  const atRiskClients = users.filter(u => 
    u.allow_procurement_optimization !== false &&
    !u.locked_vendor_ids?.includes(vendorId) &&
    u.preferred_vendor_id !== vendorId &&
    uniqueClients.some(c => 
      u.company_name === c || u.full_name?.includes(c?.split(' ')[0])
    )
  );

  const loyalCount = loyalClients.length;
  const atRiskCount = atRiskClients.length;
  const totalClients = uniqueClients.length || 1;
  const loyaltyScore = totalClients > 0 ? Math.round((loyalCount / totalClients) * 100) : 0;

  return (
    <Card className="bg-white border-slate-200 shadow-sm">
      <CardHeader className="pb-3 border-b border-slate-100">
        <div className="flex items-center justify-between">
          <CardTitle className="text-sm flex items-center gap-2">
            <Heart className="w-4 h-4 text-pink-600" />
            Client Loyalty
          </CardTitle>
          <Badge className={`${loyaltyScore >= 70 ? 'bg-green-100 text-green-700' : loyaltyScore >= 40 ? 'bg-amber-100 text-amber-700' : 'bg-red-100 text-red-700'}`}>
            {loyaltyScore}% Retention
          </Badge>
        </div>
      </CardHeader>
      <CardContent className="p-4 space-y-4">
        {/* Loyalty Score Bar */}
        <div>
          <div className="flex items-center justify-between text-xs mb-2">
            <span className="text-slate-500">Client Retention Score</span>
            <span className="font-bold text-slate-700">{loyalCount}/{totalClients} locked</span>
          </div>
          <Progress 
            value={loyaltyScore} 
            className="h-2"
          />
        </div>

        {/* Stats Grid */}
        <div className="grid grid-cols-2 gap-3">
          <div className="p-3 bg-green-50 rounded-lg border border-green-200">
            <div className="flex items-center gap-2 mb-1">
              <Lock className="w-4 h-4 text-green-600" />
              <span className="text-xs font-medium text-green-700">Loyal</span>
            </div>
            <p className="text-2xl font-bold text-green-700">{loyalCount}</p>
            <p className="text-xs text-green-600">Won't switch vendors</p>
          </div>
          
          <div className="p-3 bg-amber-50 rounded-lg border border-amber-200">
            <div className="flex items-center gap-2 mb-1">
              <AlertTriangle className="w-4 h-4 text-amber-600" />
              <span className="text-xs font-medium text-amber-700">At Risk</span>
            </div>
            <p className="text-2xl font-bold text-amber-700">{atRiskCount}</p>
            <p className="text-xs text-amber-600">Open to optimization</p>
          </div>
        </div>

        {/* Loyal Clients List */}
        {loyalClients.length > 0 && (
          <div>
            <p className="text-xs font-semibold text-slate-600 mb-2 flex items-center gap-1">
              <Shield className="w-3 h-3 text-green-600" />
              Protected Relationships
            </p>
            <div className="space-y-2">
              {loyalClients.slice(0, 3).map((client, idx) => (
                <div 
                  key={client.id || idx}
                  className="flex items-center gap-2 p-2 bg-green-50/50 rounded-lg"
                >
                  <Avatar className="w-7 h-7">
                    <AvatarFallback className="bg-green-200 text-green-800 text-xs font-bold">
                      {client.full_name?.charAt(0) || client.company_name?.charAt(0) || 'C'}
                    </AvatarFallback>
                  </Avatar>
                  <div className="flex-1 min-w-0">
                    <p className="text-xs font-medium text-slate-900 truncate">
                      {client.company_name || client.full_name}
                    </p>
                  </div>
                  <Badge className="bg-green-100 text-green-700 text-[10px]">
                    <Lock className="w-2.5 h-2.5 mr-0.5" />
                    Locked
                  </Badge>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* At Risk Clients */}
        {atRiskClients.length > 0 && (
          <div>
            <p className="text-xs font-semibold text-slate-600 mb-2 flex items-center gap-1">
              <AlertTriangle className="w-3 h-3 text-amber-600" />
              Needs Attention
            </p>
            <div className="space-y-2">
              {atRiskClients.slice(0, 3).map((client, idx) => (
                <div 
                  key={client.id || idx}
                  className="flex items-center gap-2 p-2 bg-amber-50/50 rounded-lg"
                >
                  <Avatar className="w-7 h-7">
                    <AvatarFallback className="bg-amber-200 text-amber-800 text-xs font-bold">
                      {client.full_name?.charAt(0) || client.company_name?.charAt(0) || 'C'}
                    </AvatarFallback>
                  </Avatar>
                  <div className="flex-1 min-w-0">
                    <p className="text-xs font-medium text-slate-900 truncate">
                      {client.company_name || client.full_name}
                    </p>
                  </div>
                  <Badge className="bg-amber-100 text-amber-700 text-[10px]">
                    <Unlock className="w-2.5 h-2.5 mr-0.5" />
                    At Risk
                  </Badge>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Tips */}
        <div className="p-3 bg-blue-50 rounded-lg border border-blue-200">
          <p className="text-xs font-medium text-blue-800 mb-1">💡 Retention Tips</p>
          <ul className="text-xs text-blue-700 space-y-1">
            <li>• Maintain high fill rates to keep clients happy</li>
            <li>• Respond quickly to urgent requests</li>
            <li>• Offer competitive rates to at-risk clients</li>
          </ul>
        </div>

        {/* No Data State */}
        {totalClients === 0 && (
          <div className="text-center py-4">
            <Users className="w-8 h-8 mx-auto mb-2 text-slate-300" />
            <p className="text-xs text-slate-500">No client data yet</p>
          </div>
        )}
      </CardContent>
    </Card>
  );
}