import {
  AlertCircle,
  Calendar,
  CheckCircle2,
  Clock,
  CreditCard,
  Eye,
  Lock,
  Mail,
  MapPin,
  Phone,
  Sparkles,
  Unlock,
  Users,
  Zap,
  Target,
} from 'lucide-react';
import React, { useState } from 'react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { ScrollArea } from '@/components/ui/scroll-area';
import { Separator } from '@/components/ui/separator';
import { PersonaBadge } from '@/components/planner/PersonaBadge';
import { getSpendPotentialColor, getSpendPotentialLabel } from '@/types/persona';
import { leadPurchasesApi } from '@/db/api';
import { useToast } from '@/hooks/use-toast';

interface LeadDetailModalProps {
  lead: any;
  isOpen: boolean;
  onClose: () => void;
  onPurchaseSuccess: () => void;
  providerId: string;
  walletBalance: number;
}

const LeadDetailModal: React.FC<LeadDetailModalProps> = ({
  lead,
  isOpen,
  onClose,
  onPurchaseSuccess,
  providerId,
  walletBalance,
}) => {
  const { toast } = useToast();
  const [isPurchasing, setIsPurchasing] = useState(false);

  if (!lead) return null;

  const isPurchased = lead.is_purchased;
  const leadCost = lead.final_price || lead.calculated_price || 20; // Use final_price from lead
  const canAfford = walletBalance >= leadCost;
  const isAIRecommended = lead.trigger_source === 'ai_route_recommendation';

  const handlePurchase = async () => {
    if (!canAfford) {
      toast({
        title: 'Insufficient Credits',
        description: `You need ${leadCost} credits to unlock this lead. Current balance: ${walletBalance}`,
        variant: 'destructive',
      });
      return;
    }

    try {
      setIsPurchasing(true);

      // Price is determined server-side from leads.final_price
      await leadPurchasesApi.purchase(providerId, lead.id);

      toast({
        title: 'Lead Unlocked!',
        description: `Lead purchased for ${leadCost} credits. You can now view the full contact details.`,
      });

      onPurchaseSuccess();
    } catch (error: any) {
      console.error('Purchase error:', error);
      toast({
        title: 'Purchase Failed',
        description: error.message || 'Failed to unlock lead.',
        variant: 'destructive',
      });
    } finally {
      setIsPurchasing(false);
    }
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      weekday: 'short',
      year: 'numeric',
      month: 'short',
      day: 'numeric',
    });
  };

  const calculateDuration = () => {
    const start = new Date(lead.start_date);
    const end = new Date(lead.end_date);
    const days = Math.ceil((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24));
    return days;
  };

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-4xl max-h-[90vh] flex flex-col">
        <DialogHeader className="flex-shrink-0">
          <div className="flex items-start justify-between">
            <div className="flex-1">
              <DialogTitle className="text-2xl flex items-center gap-2">
                <MapPin className="h-6 w-6 text-primary" />
                {lead.destination}
              </DialogTitle>
              <DialogDescription className="mt-2">
                {formatDate(lead.start_date)} - {formatDate(lead.end_date)} • {calculateDuration()} gün
              </DialogDescription>
            </div>
            <div className="flex flex-col items-end gap-2">
              {isAIRecommended && (
                <Badge variant="secondary" className="bg-gradient-to-r from-primary/20 to-secondary/20 text-primary border-primary/30">
                  <Sparkles className="h-3 w-3 mr-1" />
                  AI Önerisi
                </Badge>
              )}
              {isPurchased ? (
                <Badge variant="secondary" className="bg-green-100 text-green-800 border-green-200">
                  <CheckCircle2 className="h-3 w-3 mr-1" />
                  Kilidi Açıldı
                </Badge>
              ) : (
                <Badge variant="secondary" className="bg-amber-100 text-amber-800 border-amber-200">
                  <Lock className="h-3 w-3 mr-1" />
                  Önizleme Modu
                </Badge>
              )}
            </div>
          </div>
        </DialogHeader>

        <ScrollArea className="flex-1 overflow-y-auto pr-4 -mr-4">
          <div className="space-y-6 py-4 pr-4">
            {/* AI Recommendation Info */}
            {isAIRecommended && lead.timeline_snapshot?.tour_recommendation && (
              <Card className="border-primary/30 bg-gradient-to-br from-primary/10 to-secondary/10">
                <CardHeader>
                  <CardTitle className="text-lg flex items-center gap-2">
                    <Sparkles className="h-5 w-5 text-primary" />
                    AI Önerisi Detayları
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="p-3 rounded-lg bg-background/80 border">
                    <p className="text-sm font-medium mb-1 flex items-center gap-2">
                      <Zap className="h-4 w-4 text-primary" />
                      Neden Bu Hizmet Önerildi?
                    </p>
                    <p className="text-sm text-muted-foreground">
                      {lead.timeline_snapshot.tour_recommendation.reason || 'Rotaya göre optimize edilmiş öneri'}
                    </p>
                  </div>

                  {lead.timeline_snapshot.tour_recommendation.comparison_metrics && (
                    <div className="grid grid-cols-2 gap-3">
                      {lead.timeline_snapshot.tour_recommendation.comparison_metrics.time_saved_hours > 0 && (
                        <div className="p-3 rounded-lg bg-background/80 border">
                          <p className="text-xs text-muted-foreground mb-1">Zaman Kazancı</p>
                          <p className="text-lg font-bold text-primary">
                            {lead.timeline_snapshot.tour_recommendation.comparison_metrics.time_saved_hours} saat
                          </p>
                        </div>
                      )}
                      {lead.timeline_snapshot.tour_recommendation.comparison_metrics.distance_saved_km > 0 && (
                        <div className="p-3 rounded-lg bg-background/80 border">
                          <p className="text-xs text-muted-foreground mb-1">Mesafe Kazancı</p>
                          <p className="text-lg font-bold text-primary">
                            {lead.timeline_snapshot.tour_recommendation.comparison_metrics.distance_saved_km} km
                          </p>
                        </div>
                      )}
                    </div>
                  )}

                  {lead.timeline_snapshot.tour_recommendation.why_better_than_self && 
                   lead.timeline_snapshot.tour_recommendation.why_better_than_self.length > 0 && (
                    <div>
                      <p className="text-sm font-medium mb-2">Avantajlar:</p>
                      <ul className="space-y-1">
                        {lead.timeline_snapshot.tour_recommendation.why_better_than_self.slice(0, 3).map((reason: string, idx: number) => (
                          <li key={idx} className="text-sm text-muted-foreground flex items-start gap-2">
                            <span className="text-primary mt-0.5">•</span>
                            <span>{reason}</span>
                          </li>
                        ))}
                      </ul>
                    </div>
                  )}

                  <div className="p-3 rounded-lg bg-primary/10 border border-primary/20">
                    <p className="text-xs font-semibold text-primary mb-1">💡 Yüksek Dönüşüm Potansiyeli</p>
                    <p className="text-xs text-muted-foreground">
                      Bu müşteri AI tarafından önerildi ve hizmetinize özel ilgi gösterdi. Hızlı yanıt vererek dönüşüm şansınızı artırın.
                    </p>
                  </div>
                </CardContent>
              </Card>
            )}
            
            {/* Persona Information */}
            {lead.tourist_persona && (
              <Card className="border-primary/30 bg-gradient-to-br from-purple-50/50 to-blue-50/50 dark:from-purple-950/20 dark:to-blue-950/20">
                <CardHeader>
                  <CardTitle className="text-lg flex items-center gap-2">
                    <Target className="h-5 w-5 text-primary" />
                    Turist Profili
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                      <span className="text-3xl">{lead.tourist_persona.emoji}</span>
                      <div>
                        <p className="font-semibold text-lg">
                          {lead.tourist_persona.sales_label}
                        </p>
                        <p className="text-sm text-muted-foreground">
                          {lead.tourist_persona.description}
                        </p>
                      </div>
                    </div>
                    {lead.persona_confidence && (
                      <Badge variant="outline" className="text-xs">
                        %{Math.round(lead.persona_confidence * 100)} güven
                      </Badge>
                    )}
                  </div>

                  <div className="flex items-center gap-2">
                    <span className="text-sm font-medium">Harcama potansiyeli:</span>
                    <Badge className={getSpendPotentialColor(lead.tourist_persona.spend_potential)}>
                      {getSpendPotentialLabel(lead.tourist_persona.spend_potential)}
                    </Badge>
                  </div>

                  {/* Satın alınmışsa önerilen hizmetleri göster */}
                  {isPurchased && lead.tourist_persona.recommended_services && lead.tourist_persona.recommended_services.length > 0 && (
                    <div>
                      <p className="text-sm font-medium mb-2">Önerilen hizmetleriniz:</p>
                      <div className="flex flex-wrap gap-2">
                        {lead.tourist_persona.recommended_services.map((service: string, idx: number) => (
                          <Badge key={idx} variant="outline" className="text-xs">
                            {service}
                          </Badge>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* Satın alınmamışsa teaser göster */}
                  {!isPurchased && (
                    <div className="bg-amber-100 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg p-3">
                      <div className="flex items-start gap-2">
                        <Lock className="h-4 w-4 text-amber-600 dark:text-amber-400 mt-0.5" />
                        <p className="text-sm text-amber-800 dark:text-amber-300">
                          Bu profil için önerilen hizmetleri görmek için lead kilidini açın.
                        </p>
                      </div>
                    </div>
                  )}
                </CardContent>
              </Card>
            )}
            
            {/* Trip Overview */}
            <Card>
              <CardHeader>
                <CardTitle className="text-lg">Seyahat Özeti</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <div className="flex items-center gap-3">
                    <div className="h-10 w-10 rounded-full bg-primary/10 flex items-center justify-center">
                      <Users className="h-5 w-5 text-primary" />
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground">Yolcu Sayısı</p>
                      <p className="font-semibold">{lead.number_of_travelers} kişi</p>
                    </div>
                  </div>
                  <div className="flex items-center gap-3">
                    <div className="h-10 w-10 rounded-full bg-primary/10 flex items-center justify-center">
                      <Clock className="h-5 w-5 text-primary" />
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground">Süre</p>
                      <p className="font-semibold">{calculateDuration()} gün</p>
                    </div>
                  </div>
                </div>

                <Separator />

                <div>
                  <p className="text-sm font-medium mb-2">İlgi Alanları & Aktiviteler</p>
                  <div className="flex flex-wrap gap-2">
                    {lead.interests?.map((interest: string, idx: number) => (
                      <Badge key={idx} variant="outline">
                        {interest}
                      </Badge>
                    ))}
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* Contact Information */}
            <Card className={isPurchased ? 'border-green-200 bg-green-50/50' : 'border-amber-200 bg-amber-50/50'}>
              <CardHeader>
                <CardTitle className="text-lg flex items-center gap-2">
                  {isPurchased ? (
                    <>
                      <Unlock className="h-5 w-5 text-green-600" />
                      <span className="text-green-600">İletişim Bilgileri (Kilidi Açıldı)</span>
                    </>
                  ) : (
                    <>
                      <Lock className="h-5 w-5 text-amber-600" />
                      <span className="text-amber-600">İletişim Bilgileri (Önizleme)</span>
                    </>
                  )}
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-3">
                {!isPurchased && (
                  <div className="bg-amber-100 border border-amber-200 rounded-lg p-3 mb-4">
                    <div className="flex items-start gap-2">
                      <AlertCircle className="h-4 w-4 text-amber-600 mt-0.5" />
                      <p className="text-sm text-amber-800">
                        İletişim bilgileri bulanık. Tüm bilgileri görmek için lead kilidini açın.
                      </p>
                    </div>
                  </div>
                )}

                <div className="space-y-3">
                  <div className="flex items-center gap-3">
                    <Mail className="h-4 w-4 text-muted-foreground" />
                    <div className="flex-1">
                      <p className="text-sm text-muted-foreground">Email</p>
                      <p className={`font-mono ${!isPurchased ? 'blur-[4px] select-none pointer-events-none' : ''}`}>
                        {isPurchased ? lead.email : lead.email_preview}
                      </p>
                    </div>
                  </div>

                  <div className="flex items-center gap-3">
                    <Phone className="h-4 w-4 text-muted-foreground" />
                    <div className="flex-1">
                      <p className="text-sm text-muted-foreground">WhatsApp</p>
                      <p className={`font-mono ${!isPurchased ? 'blur-[4px] select-none pointer-events-none' : ''}`}>
                        {isPurchased ? lead.whatsapp : lead.whatsapp_preview}
                      </p>
                    </div>
                  </div>

                  {isPurchased && lead.country && (
                    <div className="flex items-center gap-3">
                      <MapPin className="h-4 w-4 text-muted-foreground" />
                      <div className="flex-1">
                        <p className="text-sm text-muted-foreground">Country</p>
                        <p className="font-medium">{lead.country}</p>
                      </div>
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>

            {/* Timeline */}
            {lead.timeline_snapshot && Array.isArray(lead.timeline_snapshot) && lead.timeline_snapshot.length > 0 && (
              <Card>
                <CardHeader>
                  <CardTitle className="text-lg flex items-center gap-2">
                    <Calendar className="h-5 w-5" />
                    Planlanan Zaman Çizelgesi
                    {!isPurchased && (
                      <Badge variant="outline" className="ml-2">
                        <Eye className="h-3 w-3 mr-1" />
                        Önizleme
                      </Badge>
                    )}
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="space-y-4">
                    {lead.timeline_snapshot.map((day: any, idx: number) => (
                      <div key={idx} className="border-l-2 border-primary/30 pl-4 pb-4 last:pb-0">
                        <div className="flex items-center gap-2 mb-2">
                          <div className="h-6 w-6 rounded-full bg-primary text-primary-foreground text-xs flex items-center justify-center font-semibold">
                            {idx + 1}
                          </div>
                          <p className="font-semibold">
                            Gün {idx + 1}
                            {day.date && ` - ${new Date(day.date).toLocaleDateString('tr-TR', { month: 'short', day: 'numeric' })}`}
                          </p>
                        </div>
                        {day.activities && day.activities.length > 0 ? (
                          <div className="space-y-2 ml-8">
                            {day.activities.map((activity: any, actIdx: number) => (
                              <div key={actIdx} className="text-sm">
                                <p className="font-medium">{activity.name || activity.title}</p>
                                {activity.time && (
                                  <p className="text-muted-foreground text-xs">{activity.time}</p>
                                )}
                              </div>
                            ))}
                          </div>
                        ) : (
                          <p className="text-sm text-muted-foreground ml-8">Aktivite planlanmamış</p>
                        )}
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>
            )}

            {/* Planned Activities */}
            {lead.planned_activities && lead.planned_activities.length > 0 && (
              <Card>
                <CardHeader>
                  <CardTitle className="text-lg">Planned Activities</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                    {lead.planned_activities.map((activity: any, idx: number) => (
                      <div key={idx} className="border rounded-lg p-3">
                        <p className="font-medium">{activity.name}</p>
                        <p className="text-sm text-muted-foreground">{activity.type}</p>
                        {activity.location && (
                          <p className="text-xs text-muted-foreground mt-1 flex items-center gap-1">
                            <MapPin className="h-3 w-3" />
                            {activity.location}
                          </p>
                        )}
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>
            )}
          </div>
        </ScrollArea>

        <DialogFooter className="flex-shrink-0 border-t pt-4 mt-4">
          {!isPurchased ? (
            <div className="flex flex-col w-full gap-4">
              {/* Pricing Breakdown */}
              <div className="bg-muted/50 rounded-lg p-4">
                <div className="space-y-2">
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-muted-foreground">Temel Fiyat</span>
                    <span className="font-medium">{lead.base_price || 20} Credit</span>
                  </div>
                  
                  {/* Show activity multipliers if any */}
                  {lead.planned_activities && lead.planned_activities.length > 0 && (
                    <>
                      {lead.planned_activities.some((a: any) => 
                        a.type?.toLowerCase().includes('balloon') || a.name?.toLowerCase().includes('balloon')
                      ) && (
                        <div className="flex items-center justify-between text-sm">
                          <span className="text-muted-foreground flex items-center gap-2">
                            <Badge variant="outline" className="text-xs">Hot Air Balloon</Badge>
                            +100%
                          </span>
                          <span className="font-medium text-amber-600">×2.0</span>
                        </div>
                      )}
                      
                      {lead.planned_activities.some((a: any) => 
                        a.type?.toLowerCase().includes('atv') || a.name?.toLowerCase().includes('atv') ||
                        a.type?.toLowerCase().includes('horse') || a.name?.toLowerCase().includes('horse') ||
                        a.type?.toLowerCase().includes('riding') || a.name?.toLowerCase().includes('riding')
                      ) && (
                        <div className="flex items-center justify-between text-sm">
                          <span className="text-muted-foreground flex items-center gap-2">
                            <Badge variant="outline" className="text-xs">ATV/Horse Riding</Badge>
                            +50%
                          </span>
                          <span className="font-medium text-amber-600">×1.5</span>
                        </div>
                      )}
                      
                      {lead.planned_activities.some((a: any) => 
                        a.type?.toLowerCase().includes('guided') || a.name?.toLowerCase().includes('guided') ||
                        a.type?.toLowerCase().includes('tour') || a.name?.toLowerCase().includes('tour')
                      ) && (
                        <div className="flex items-center justify-between text-sm">
                          <span className="text-muted-foreground flex items-center gap-2">
                            <Badge variant="outline" className="text-xs">Guided Tour</Badge>
                            +40%
                          </span>
                          <span className="font-medium text-amber-600">×1.4</span>
                        </div>
                      )}
                    </>
                  )}
                  
                  {lead.override_price && (
                    <div className="flex items-center justify-between text-sm pt-2 border-t">
                      <span className="text-muted-foreground">Admin Özel Fiyat</span>
                      <Badge variant="outline" className="text-xs">Özel Fiyat</Badge>
                    </div>
                  )}
                  
                  <Separator className="my-2" />
                  
                  <div className="flex items-center justify-between">
                    <span className="font-semibold">Toplam Fiyat</span>
                    <span className="text-2xl font-bold text-primary">{leadCost} Credit</span>
                  </div>
                </div>
              </div>

              {/* Balance and Action */}
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-muted-foreground">Bakiyeniz</p>
                  <p className={`text-xl font-bold ${canAfford ? 'text-green-600' : 'text-destructive'}`}>
                    {walletBalance} Credit
                  </p>
                  {!canAfford && (
                    <p className="text-xs text-destructive mt-1">
                      {leadCost - walletBalance} credit daha gerekli
                    </p>
                  )}
                </div>
                <div className="flex gap-2">
                  <Button variant="outline" onClick={onClose} disabled={isPurchasing}>
                    Kapat
                  </Button>
                  <Button
                    onClick={handlePurchase}
                    disabled={isPurchasing || !canAfford}
                    className="min-w-[140px]"
                  >
                    {isPurchasing ? (
                      'Kilidi Açılıyor...'
                    ) : !canAfford ? (
                      <>
                        <AlertCircle className="h-4 w-4 mr-2" />
                        Yetersiz Credit
                      </>
                    ) : (
                      <>
                        <Unlock className="h-4 w-4 mr-2" />
                        {leadCost} Credit ile Aç
                      </>
                    )}
                  </Button>
                </div>
              </div>
            </div>
          ) : (
            <div className="flex items-center justify-between w-full">
              <div className="flex items-center gap-2 text-green-600">
                <CheckCircle2 className="h-5 w-5" />
                <span className="font-semibold">Bu lead'in kilidi açıldı. Tüm bilgilere tam erişiminiz var.</span>
              </div>
              <Button onClick={onClose}>Kapat</Button>
            </div>
          )}
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

export default LeadDetailModal;
