import { 
  Calendar, 
  CheckCircle2,
  CreditCard,
  Eye, 
  Filter, 
  Lock,
  MapPin, 
  Settings,
  ShoppingBag,
  Sparkles,
  TrendingUp,
  Unlock,
  Users, 
  Wallet, 
  Zap
} from 'lucide-react';
import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import LeadDetailModal from '@/components/provider/LeadDetailModal';
import { ProviderRegistrationModal } from '@/components/provider/ProviderRegistrationModal';
import { PersonaBadge } from '@/components/PersonaBadge';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { 
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Skeleton } from '@/components/ui/skeleton';
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { providerLeadsApi, providerServicesApi, providerWalletApi } from '@/db/api';
import { supabase } from '@/db/supabase';
import { useToast } from '@/hooks/use-toast';
import type { TouristPersona } from '@/types/lead';

import { useAuth } from '@/contexts/AuthContext';

const ProviderDashboard = () => {
  const { toast } = useToast();
  const navigate = useNavigate();
  const { profile: authProfile, loading: authLoading } = useAuth();
  const [loading, setLoading] = useState(true);
  const [leads, setLeads] = useState<any[]>([]);
  const [purchasedLeads, setPurchasedLeads] = useState<any[]>([]);
  const [wallet, setWallet] = useState<any>(null);
  const [providerService, setProviderService] = useState<any>(null);
  const [selectedLead, setSelectedLead] = useState<any>(null);
  const [isDetailModalOpen, setIsDetailModalOpen] = useState(false);
  const [isRegistrationModalOpen, setIsRegistrationModalOpen] = useState(false);
  const [currentProviderId, setCurrentProviderId] = useState<string>('');
  const [activeTab, setActiveTab] = useState<string>('available');
  
  // Filters
  const [destinationFilter, setDestinationFilter] = useState<string>('all');
  const [travelersFilter, setTravelersFilter] = useState<string>('all');
  const [activityFilter, setActivityFilter] = useState<string>('all');
  const [triggerSourceFilter, setTriggerSourceFilter] = useState<string>('all');

  useEffect(() => {
    if (!authLoading) {
      checkProviderAccess();
    }
  }, [authLoading]);

  const checkProviderAccess = async () => {
    try {
      if (!authProfile) {
        toast({
          title: 'Giriş Gerekli',
          description: 'Provider paneline erişmek için giriş yapmalısınız.',
          variant: 'destructive',
        });
        navigate('/sign-in');
        return;
      }

      // If user is not a provider, show registration modal
      if (authProfile.role === 'user') {
        setIsRegistrationModalOpen(true);
        setLoading(false);
        return;
      }

      if (authProfile.role !== 'provider' && authProfile.role !== 'admin') {
        toast({
          title: 'Erişim Reddedildi',
          description: 'Provider erişiminiz bulunmuyor.',
          variant: 'destructive',
        });
        navigate('/');
        return;
      }

      // Load provider data
      await loadProviderData(authProfile.id);
    } catch (error) {
      console.error('Access check error:', error);
      navigate('/');
    }
  };

  const loadProviderData = async (providerId: string) => {
    try {
      setLoading(true);
      setCurrentProviderId(providerId);
      console.log('[ProviderDashboard] Loading data for provider:', providerId);

      // Load provider service configuration
      const service = await providerServicesApi.get(providerId);
      console.log('[ProviderDashboard] Provider service loaded:', service);
      setProviderService(service);

      // Load wallet
      const walletData = await providerWalletApi.getOrCreate(providerId);
      console.log('[ProviderDashboard] Wallet loaded:', walletData);
      setWallet(walletData);

      // Load available leads and purchased leads
      await Promise.all([
        loadLeads(providerId),
        loadPurchasedLeads(providerId)
      ]);
      console.log('[ProviderDashboard] All data loaded successfully');
    } catch (error: any) {
      console.error('[ProviderDashboard] Error loading provider data:', error);
      toast({
        title: 'Hata',
        description: error.message || 'Provider verileri yüklenemedi.',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  const loadLeads = async (providerId: string) => {
    try {
      console.log('[ProviderDashboard] Loading leads for provider:', providerId);
      const filters: any = {};
      
      if (travelersFilter !== 'all') {
        const [min, max] = travelersFilter.split('-').map(Number);
        filters.min_travelers = min;
        filters.max_travelers = max || 999;
      }
      console.log('[ProviderDashboard] Filters:', filters);

      const availableLeads = await providerLeadsApi.getAvailable(providerId, filters);
      console.log('[ProviderDashboard] Available leads loaded:', availableLeads.length, 'leads');
      setLeads(availableLeads);
    } catch (error: any) {
      console.error('[ProviderDashboard] Error loading leads:', error);
      toast({
        title: 'Hata',
        description: 'Lead\'ler yüklenemedi: ' + (error.message || ''),
        variant: 'destructive',
      });
    }
  };

  const loadPurchasedLeads = async (providerId: string) => {
    try {
      console.log('[ProviderDashboard] Loading purchased leads for provider:', providerId);
      const purchased = await providerLeadsApi.getPurchased(providerId);
      console.log('[ProviderDashboard] Purchased leads loaded:', purchased.length, 'leads');
      setPurchasedLeads(purchased);
    } catch (error: any) {
      console.error('[ProviderDashboard] Error loading purchased leads:', error);
      toast({
        title: 'Hata',
        description: 'Satın alınan lead\'ler yüklenemedi: ' + (error.message || ''),
        variant: 'destructive',
      });
    }
  };

  const handlePurchaseSuccess = async () => {
    if (authProfile) {
      await loadProviderData(authProfile.id);
    }
    setIsDetailModalOpen(false);
  };

  const handleViewLead = (lead: any) => {
    setSelectedLead(lead);
    setIsDetailModalOpen(true);
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-background p-6">
        <div className="max-w-7xl mx-auto space-y-6">
          <Skeleton className="h-32 w-full" />
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            <Skeleton className="h-64" />
            <Skeleton className="h-64" />
            <Skeleton className="h-64" />
          </div>
        </div>
      </div>
    );
  }

  const filteredLeads = leads.filter(lead => {
    if (destinationFilter !== 'all' && lead.destination !== destinationFilter) return false;
    if (activityFilter !== 'all' && !lead.interests?.includes(activityFilter)) return false;
    if (triggerSourceFilter !== 'all' && lead.trigger_source !== triggerSourceFilter) return false;
    return true;
  });

  const uniqueDestinations = [...new Set(leads.map(l => l.destination))];
  const uniqueActivities = [...new Set(leads.flatMap(l => l.interests || []))];
  
  // Count AI recommended leads
  const aiLeadsCount = leads.filter(l => l.trigger_source === 'ai_route_recommendation').length;

  return (
    <div className="min-h-screen bg-background">
      {/* Header */}
      <div className="border-b bg-gradient-to-r from-primary/5 to-accent/5">
        <div className="max-w-7xl mx-auto px-6 py-8">
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-3xl font-bold">Provider Dashboard</h1>
              <p className="text-muted-foreground mt-1">
                {providerService?.business_name || 'Manage your leads and credits'}
              </p>
            </div>
            <Button
              variant="outline"
              onClick={() => navigate('/provider-settings')}
            >
              <Settings className="h-4 w-4 mr-2" />
              Settings
            </Button>
          </div>

          {/* Wallet Card */}
          <Card className="mt-6 bg-gradient-to-br from-primary to-primary/80 text-white border-none">
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-white/80 text-sm">Available Credits</p>
                  <p className="text-4xl font-bold mt-1">{wallet?.credit_balance || 0}</p>
                </div>
                <div className="flex flex-col gap-2">
                  <Button
                    variant="secondary"
                    size="sm"
                    onClick={() => toast({ title: 'Coming Soon', description: 'Credit purchase feature will be available soon.' })}
                  >
                    <CreditCard className="h-4 w-4 mr-2" />
                    Buy Credits
                  </Button>
                  <Button
                    variant="ghost"
                    size="sm"
                    className="text-white hover:bg-white/20"
                    onClick={() => navigate('/provider-transactions')}
                  >
                    <TrendingUp className="h-4 w-4 mr-2" />
                    History
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>

      {/* Main Content */}
      <div className="max-w-7xl mx-auto px-6 py-8">
        {/* Filters */}
        <Card className="mb-6">
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Filter className="h-5 w-5" />
              Filter Leads
              {aiLeadsCount > 0 && (
                <Badge variant="secondary" className="ml-auto flex items-center gap-1">
                  <Sparkles className="h-3 w-3" />
                  {aiLeadsCount} AI Önerisi
                </Badge>
              )}
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
              <div>
                <label className="text-sm font-medium mb-2 block">Destination</label>
                <Select value={destinationFilter} onValueChange={setDestinationFilter}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">All Destinations</SelectItem>
                    {uniqueDestinations.map(dest => (
                      <SelectItem key={dest} value={dest}>{dest}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div>
                <label className="text-sm font-medium mb-2 block">Travelers</label>
                <Select value={travelersFilter} onValueChange={setTravelersFilter}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">All</SelectItem>
                    <SelectItem value="1-2">1-2 people</SelectItem>
                    <SelectItem value="3-5">3-5 people</SelectItem>
                    <SelectItem value="6-10">6-10 people</SelectItem>
                    <SelectItem value="11-999">11+ people</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <label className="text-sm font-medium mb-2 block">Activity</label>
                <Select value={activityFilter} onValueChange={setActivityFilter}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">All Activities</SelectItem>
                    {uniqueActivities.map(activity => (
                      <SelectItem key={activity} value={activity}>{activity}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div>
                <label className="text-sm font-medium mb-2 block">Lead Kaynağı</label>
                <Select value={triggerSourceFilter} onValueChange={setTriggerSourceFilter}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">Tümü</SelectItem>
                    <SelectItem value="ai_route_recommendation">
                      <div className="flex items-center gap-2">
                        <Sparkles className="h-3 w-3" />
                        AI Önerisi
                      </div>
                    </SelectItem>
                    <SelectItem value="save_modal">Kaydet Modal</SelectItem>
                    <SelectItem value="planner_cta">Planner CTA</SelectItem>
                    <SelectItem value="contextual_banner">Bağlamsal Banner</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Tabs for Available and Purchased Leads */}
        <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-4">
          <TabsList className="grid w-full max-w-md grid-cols-2">
            <TabsTrigger value="available" className="flex items-center gap-2">
              <Eye className="h-4 w-4" />
              Mevcut Lead'ler ({filteredLeads.length})
            </TabsTrigger>
            <TabsTrigger value="purchased" className="flex items-center gap-2">
              <ShoppingBag className="h-4 w-4" />
              Satın Alınanlar ({purchasedLeads.length})
            </TabsTrigger>
          </TabsList>

          {/* Available Leads Tab */}
          <TabsContent value="available" className="space-y-4">
            {filteredLeads.length === 0 ? (
              <Card>
                <CardContent className="p-12 text-center">
                  <MapPin className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
                  <h3 className="text-lg font-semibold mb-2">Mevcut Lead Yok</h3>
                  <p className="text-muted-foreground">
                    Hizmet alanlarınıza ve filtrelerinize uygun lead bulunmuyor. Daha sonra tekrar kontrol edin veya ayarlarınızı düzenleyin.
                  </p>
                </CardContent>
              </Card>
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {filteredLeads.map(lead => {
                const isAIRecommended = lead.trigger_source === 'ai_route_recommendation';
                return (
                <Card 
                  key={lead.id} 
                  className={`hover:shadow-lg transition-shadow relative overflow-hidden ${
                    isAIRecommended ? 'border-primary/40 bg-gradient-to-br from-primary/5 to-secondary/5' : ''
                  }`}
                >
                  {/* AI Recommendation Badge */}
                  {isAIRecommended && (
                    <div className="absolute top-0 left-0 bg-gradient-to-r from-primary to-primary/80 text-white px-3 py-1 text-xs font-semibold rounded-br-lg flex items-center gap-1 shadow-md">
                      <Sparkles className="h-3 w-3" />
                      AI Önerisi
                    </div>
                  )}
                  
                  {/* Status Badge Ribbon */}
                  {lead.is_purchased && (
                    <div className="absolute top-0 right-0 bg-green-500 text-white px-3 py-1 text-xs font-semibold rounded-bl-lg flex items-center gap-1">
                      <CheckCircle2 className="h-3 w-3" />
                      Unlocked
                    </div>
                  )}
                  
                  <CardHeader className={isAIRecommended ? 'pt-8' : ''}>
                    <div className="flex items-start justify-between">
                      <div className="flex-1">
                        <CardTitle className="text-lg flex items-center gap-2">
                          <MapPin className="h-4 w-4 text-primary" />
                          {lead.destination}
                        </CardTitle>
                        <CardDescription className="mt-1">
                          {new Date(lead.start_date).toLocaleDateString()} - {new Date(lead.end_date).toLocaleDateString()}
                        </CardDescription>
                        {/* Persona Badge */}
                        {lead.tourist_persona && (
                          <div className="mt-2">
                            <PersonaBadge 
                              persona={lead.tourist_persona as TouristPersona}
                              confidence={lead.persona_confidence}
                              language="tr"
                              compact
                            />
                          </div>
                        )}
                      </div>
                    </div>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    {/* AI Recommendation Info */}
                    {isAIRecommended && lead.timeline_snapshot?.tour_recommendation && (
                      <div className="p-3 rounded-lg bg-primary/10 border border-primary/20 space-y-2">
                        <div className="flex items-center gap-2">
                          <Zap className="h-4 w-4 text-primary" />
                          <span className="text-xs font-semibold text-primary">AI Bu Hizmeti Önerdi</span>
                        </div>
                        <p className="text-xs text-muted-foreground">
                          {lead.timeline_snapshot.tour_recommendation.reason || 'Rotaya göre optimize edilmiş öneri'}
                        </p>
                        {lead.timeline_snapshot.tour_recommendation.comparison_metrics && (
                          <div className="flex gap-2 text-xs">
                            {lead.timeline_snapshot.tour_recommendation.comparison_metrics.time_saved_hours > 0 && (
                              <Badge variant="secondary" className="text-xs">
                                ⏱️ {lead.timeline_snapshot.tour_recommendation.comparison_metrics.time_saved_hours}sa tasarruf
                              </Badge>
                            )}
                            {lead.timeline_snapshot.tour_recommendation.comparison_metrics.distance_saved_km > 0 && (
                              <Badge variant="secondary" className="text-xs">
                                🚗 {lead.timeline_snapshot.tour_recommendation.comparison_metrics.distance_saved_km}km az
                              </Badge>
                            )}
                          </div>
                        )}
                      </div>
                    )}
                    
                    <div className="space-y-2 text-sm">
                      <div className="flex items-center gap-2">
                        <Users className="h-4 w-4 text-muted-foreground" />
                        <span>{lead.number_of_travelers} travelers</span>
                      </div>
                      <div className="flex items-center gap-2">
                        <Calendar className="h-4 w-4 text-muted-foreground" />
                        <span>{Math.ceil((new Date(lead.end_date).getTime() - new Date(lead.start_date).getTime()) / (1000 * 60 * 60 * 24))} days</span>
                      </div>
                    </div>

                    <div>
                      <p className="text-sm font-medium mb-2">Interests:</p>
                      <div className="flex flex-wrap gap-1">
                        {lead.interests?.slice(0, 3).map((interest: string, idx: number) => (
                          <Badge key={idx} variant="outline" className="text-xs">
                            {interest}
                          </Badge>
                        ))}
                        {lead.interests?.length > 3 && (
                          <Badge variant="outline" className="text-xs">
                            +{lead.interests.length - 3} more
                          </Badge>
                        )}
                      </div>
                    </div>

                    {/* Contact Preview */}
                    <div className={`p-3 rounded-lg space-y-1 ${lead.is_purchased ? 'bg-green-50 border border-green-200' : 'bg-muted/50'}`}>
                      <div className="flex items-center gap-2">
                        {lead.is_purchased ? (
                          <>
                            <Unlock className="h-3 w-3 text-green-600" />
                            <span className="text-xs text-green-600 font-medium">Full Access</span>
                          </>
                        ) : (
                          <>
                            <Lock className="h-3 w-3 text-muted-foreground" />
                            <span className="text-xs text-muted-foreground">Preview Only</span>
                          </>
                        )}
                      </div>
                      <p className={`text-sm font-mono ${!lead.is_purchased ? 'blur-[3px] select-none' : ''}`}>
                        {lead.is_purchased ? lead.email : lead.email_preview}
                      </p>
                      <p className={`text-sm font-mono ${!lead.is_purchased ? 'blur-[3px] select-none' : ''}`}>
                        {lead.is_purchased ? lead.whatsapp : lead.whatsapp_preview}
                      </p>
                    </div>

                    {/* Price Display */}
                    {!lead.is_purchased && (
                      <div className={`flex items-center justify-between p-3 rounded-lg border ${
                        isAIRecommended 
                          ? 'bg-gradient-to-r from-primary/10 to-secondary/10 border-primary/30' 
                          : 'bg-primary/5 border-primary/20'
                      }`}>
                        <div className="flex items-center gap-2">
                          <CreditCard className="h-4 w-4 text-primary" />
                          <span className="text-sm font-medium">Lead Price</span>
                        </div>
                        <div className="text-right">
                          <p className={`text-lg font-bold ${isAIRecommended ? 'text-primary' : 'text-primary'}`}>
                            {lead.final_price || lead.calculated_price || 20} Credits
                          </p>
                          {isAIRecommended && (
                            <Badge variant="secondary" className="text-xs mt-1">Premium Lead</Badge>
                          )}
                          {lead.override_price && !isAIRecommended && (
                            <Badge variant="outline" className="text-xs mt-1">Custom Price</Badge>
                          )}
                        </div>
                      </div>
                    )}

                    <Button
                      className="w-full"
                      variant={lead.is_purchased ? "outline" : "default"}
                      onClick={() => handleViewLead(lead)}
                    >
                      {lead.is_purchased ? (
                        <>
                          <Eye className="h-4 w-4 mr-2" />
                          View Full Details
                        </>
                      ) : (
                        <>
                          <Lock className="h-4 w-4 mr-2" />
                          View & Unlock ({lead.final_price || lead.calculated_price || 20} Credits)
                        </>
                      )}
                    </Button>
                  </CardContent>
                </Card>
              )})}
            </div>
          )}
          </TabsContent>

          {/* Purchased Leads Tab */}
          <TabsContent value="purchased" className="space-y-4">
            {purchasedLeads.length === 0 ? (
              <Card>
                <CardContent className="p-12 text-center">
                  <ShoppingBag className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
                  <h3 className="text-lg font-semibold mb-2">Henüz Lead Satın Almadınız</h3>
                  <p className="text-muted-foreground">
                    Satın aldığınız lead'ler burada görünecektir. Mevcut lead'leri görüntülemek için "Mevcut Lead'ler" sekmesine gidin.
                  </p>
                </CardContent>
              </Card>
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {purchasedLeads.map(lead => {
                  const isAIRecommended = lead.trigger_source === 'ai_route_recommendation';
                  return (
                  <Card 
                    key={lead.id} 
                    className={`hover:shadow-lg transition-shadow relative overflow-hidden ${
                      isAIRecommended ? 'border-primary/40 bg-gradient-to-br from-primary/5 to-secondary/5' : 'border-green-200'
                    }`}
                  >
                    {/* AI Recommendation Badge */}
                    {isAIRecommended && (
                      <div className="absolute top-0 left-0 bg-gradient-to-r from-primary to-primary/80 text-white px-3 py-1 text-xs font-semibold rounded-br-lg flex items-center gap-1 shadow-md z-10">
                        <Sparkles className="h-3 w-3" />
                        AI Önerisi
                      </div>
                    )}
                    
                    {/* Purchased Badge */}
                    <div className="absolute top-0 right-0 bg-green-500 text-white px-3 py-1 text-xs font-semibold rounded-bl-lg flex items-center gap-1">
                      <CheckCircle2 className="h-3 w-3" />
                      Satın Alındı
                    </div>
                    
                    <CardHeader className={isAIRecommended ? 'pt-8' : ''}>
                      <div className="flex items-start justify-between">
                        <div className="flex-1">
                          <CardTitle className="text-lg flex items-center gap-2">
                            <MapPin className="h-4 w-4 text-primary" />
                            {lead.destination}
                          </CardTitle>
                          <CardDescription className="mt-1">
                            {new Date(lead.start_date).toLocaleDateString('tr-TR')} - {new Date(lead.end_date).toLocaleDateString('tr-TR')}
                          </CardDescription>
                        </div>
                      </div>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      {/* AI Recommendation Info */}
                      {isAIRecommended && lead.timeline_snapshot?.tour_recommendation && (
                        <div className="p-3 rounded-lg bg-primary/10 border border-primary/20 space-y-2">
                          <div className="flex items-center gap-2">
                            <Zap className="h-4 w-4 text-primary" />
                            <span className="text-xs font-semibold text-primary">AI Bu Hizmeti Önerdi</span>
                          </div>
                          <p className="text-xs text-muted-foreground">
                            {lead.timeline_snapshot.tour_recommendation.reason || 'Rotaya göre optimize edilmiş öneri'}
                          </p>
                          {lead.timeline_snapshot.tour_recommendation.comparison_metrics && (
                            <div className="flex gap-2 text-xs">
                              {lead.timeline_snapshot.tour_recommendation.comparison_metrics.time_saved_hours > 0 && (
                                <Badge variant="secondary" className="text-xs">
                                  ⏱️ {lead.timeline_snapshot.tour_recommendation.comparison_metrics.time_saved_hours}sa tasarruf
                                </Badge>
                              )}
                              {lead.timeline_snapshot.tour_recommendation.comparison_metrics.distance_saved_km > 0 && (
                                <Badge variant="secondary" className="text-xs">
                                  🚗 {lead.timeline_snapshot.tour_recommendation.comparison_metrics.distance_saved_km}km az
                                </Badge>
                              )}
                            </div>
                          )}
                        </div>
                      )}
                      
                      <div className="space-y-2 text-sm">
                        <div className="flex items-center gap-2">
                          <Users className="h-4 w-4 text-muted-foreground" />
                          <span>{lead.number_of_travelers} kişi</span>
                        </div>
                        <div className="flex items-center gap-2">
                          <Calendar className="h-4 w-4 text-muted-foreground" />
                          <span>{Math.ceil((new Date(lead.end_date).getTime() - new Date(lead.start_date).getTime()) / (1000 * 60 * 60 * 24))} gün</span>
                        </div>
                      </div>

                      <div>
                        <p className="text-sm font-medium mb-2">İlgi Alanları:</p>
                        <div className="flex flex-wrap gap-1">
                          {lead.interests?.slice(0, 3).map((interest: string, idx: number) => (
                            <Badge key={idx} variant="outline" className="text-xs">
                              {interest}
                            </Badge>
                          ))}
                          {lead.interests?.length > 3 && (
                            <Badge variant="outline" className="text-xs">
                              +{lead.interests.length - 3} daha fazla
                            </Badge>
                          )}
                        </div>
                      </div>

                      {/* Full Contact Info */}
                      <div className="p-3 rounded-lg space-y-2 bg-green-50 border border-green-200">
                        <div className="flex items-center gap-2">
                          <Unlock className="h-3 w-3 text-green-600" />
                          <span className="text-xs text-green-600 font-medium">Tam Erişim</span>
                        </div>
                        <div className="space-y-1">
                          <p className="text-xs text-muted-foreground">E-posta:</p>
                          <p className="text-sm font-mono font-medium">{lead.email}</p>
                        </div>
                        <div className="space-y-1">
                          <p className="text-xs text-muted-foreground">WhatsApp:</p>
                          <p className="text-sm font-mono font-medium">{lead.whatsapp}</p>
                        </div>
                        <div className="space-y-1">
                          <p className="text-xs text-muted-foreground">Ülke:</p>
                          <p className="text-sm font-medium">{lead.country}</p>
                        </div>
                      </div>

                      {/* Purchase Info */}
                      <div className="pt-2 border-t text-xs text-muted-foreground">
                        <p>Satın alındı: {new Date(lead.purchased_at).toLocaleDateString('tr-TR')} {new Date(lead.purchased_at).toLocaleTimeString('tr-TR', { hour: '2-digit', minute: '2-digit' })}</p>
                        <p>Harcanan kredi: {lead.credits_spent || lead.final_price || 20}</p>
                      </div>

                      <Button
                        className="w-full"
                        variant="outline"
                        onClick={() => handleViewLead(lead)}
                      >
                        <Eye className="h-4 w-4 mr-2" />
                        Detayları Görüntüle
                      </Button>
                    </CardContent>
                  </Card>
                )})}
              </div>
            )}
          </TabsContent>
        </Tabs>
      </div>

      {/* Lead Detail Modal */}
      {selectedLead && currentProviderId && (
        <LeadDetailModal
          lead={selectedLead}
          isOpen={isDetailModalOpen}
          onClose={() => {
            setIsDetailModalOpen(false);
            setSelectedLead(null);
          }}
          onPurchaseSuccess={handlePurchaseSuccess}
          providerId={currentProviderId}
          walletBalance={wallet?.credit_balance || 0}
        />
      )}

      {/* Provider Registration Modal */}
      <ProviderRegistrationModal
        isOpen={isRegistrationModalOpen}
        onClose={() => {
          setIsRegistrationModalOpen(false);
          navigate('/');
        }}
        onSuccess={() => {
          setIsRegistrationModalOpen(false);
          checkProviderAccess();
        }}
      />
    </div>
  );
};

export default ProviderDashboard;
