import { 
  Calendar, 
  Clock,
  DollarSign, 
  Edit,
  Eye, 
  Filter,
  MapPin, 
  Package,
  RotateCcw,
  Trash2,
  TrendingUp,
  Users,
  ArrowUpDown,
} from 'lucide-react';
import React, { useEffect, 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 {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Skeleton } from '@/components/ui/skeleton';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { PersonaBadge } from '@/components/PersonaBadge';
import { adminLeadsApi } from '@/db/api';
import { supabase } from '@/db/supabase';
import { useToast } from '@/hooks/use-toast';
import type { TouristPersona } from '@/types/lead';

const AdminLeads: React.FC = () => {
  const { toast } = useToast();
  const [leads, setLeads] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedLead, setSelectedLead] = useState<any>(null);
  const [isDetailModalOpen, setIsDetailModalOpen] = useState(false);
  const [isPriceModalOpen, setIsPriceModalOpen] = useState(false);
  const [overridePrice, setOverridePrice] = useState('');
  const [isUpdatingPrice, setIsUpdatingPrice] = useState(false);
  const [deleteLeadId, setDeleteLeadId] = useState<string | null>(null);
  const [isDeleting, setIsDeleting] = useState(false);

  // Filters
  const [destinationFilter, setDestinationFilter] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [personaFilter, setPersonaFilter] = useState('all');
  const [startDateFilter, setStartDateFilter] = useState('');
  const [endDateFilter, setEndDateFilter] = useState('');
  
  // Sorting
  const [sortBy, setSortBy] = useState('created_at_desc');

  useEffect(() => {
    loadLeads();
  }, []);

  useEffect(() => {
    // Apply sorting when sortBy changes
    if (leads.length > 0) {
      const sortedData = applySorting(leads, sortBy);
      setLeads(sortedData);
    }
  }, [sortBy]);

  const loadLeads = async () => {
    try {
      setLoading(true);
      const data = await adminLeadsApi.getAll();
      setLeads(data);
    } catch (error: any) {
      console.error('Error loading leads:', error);
      toast({
        title: 'Error',
        description: 'Failed to load leads.',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  const handleApplyFilters = async () => {
    try {
      setLoading(true);
      const data = await adminLeadsApi.getAll({
        destination: destinationFilter || undefined,
        status: statusFilter !== 'all' ? statusFilter : undefined,
        personaType: personaFilter !== 'all' ? personaFilter : undefined,
        startDate: startDateFilter || undefined,
        endDate: endDateFilter || undefined,
      });
      
      // Apply sorting
      const sortedData = applySorting(data, sortBy);
      setLeads(sortedData);
    } catch (error: any) {
      console.error('Error filtering leads:', error);
      toast({
        title: 'Error',
        description: 'Failed to filter leads.',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  const applySorting = (data: any[], sortOption: string) => {
    const sortedData = [...data];
    
    const SPEND_POTENTIAL_ORDER: Record<string, number> = {
      'very_high': 4,
      'high': 3,
      'medium': 2,
      'low': 1,
    };

    switch (sortOption) {
      case 'created_at_desc':
        sortedData.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());
        break;
      case 'created_at_asc':
        sortedData.sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime());
        break;
      case 'spend_desc':
        sortedData.sort((a, b) => {
          const aScore = SPEND_POTENTIAL_ORDER[a.tourist_persona?.spend_potential || 'low'] || 0;
          const bScore = SPEND_POTENTIAL_ORDER[b.tourist_persona?.spend_potential || 'low'] || 0;
          return bScore - aScore;
        });
        break;
      case 'spend_asc':
        sortedData.sort((a, b) => {
          const aScore = SPEND_POTENTIAL_ORDER[a.tourist_persona?.spend_potential || 'low'] || 0;
          const bScore = SPEND_POTENTIAL_ORDER[b.tourist_persona?.spend_potential || 'low'] || 0;
          return aScore - bScore;
        });
        break;
      case 'confidence_desc':
        sortedData.sort((a, b) => (b.persona_confidence || 0) - (a.persona_confidence || 0));
        break;
      case 'confidence_asc':
        sortedData.sort((a, b) => (a.persona_confidence || 0) - (b.persona_confidence || 0));
        break;
      case 'price_desc':
        sortedData.sort((a, b) => (b.final_price || 0) - (a.final_price || 0));
        break;
      case 'price_asc':
        sortedData.sort((a, b) => (a.final_price || 0) - (b.final_price || 0));
        break;
      default:
        break;
    }

    return sortedData;
  };

  const handleResetFilters = () => {
    setDestinationFilter('');
    setStatusFilter('all');
    setPersonaFilter('all');
    setStartDateFilter('');
    setEndDateFilter('');
    setSortBy('created_at_desc');
    loadLeads();
  };

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

  const handleOpenPriceModal = (lead: any) => {
    setSelectedLead(lead);
    setOverridePrice(lead.override_price?.toString() || '');
    setIsPriceModalOpen(true);
  };

  const handleOverridePrice = async () => {
    if (!selectedLead) return;

    try {
      setIsUpdatingPrice(true);

      const priceValue = overridePrice === '' ? null : parseInt(overridePrice);

      if (priceValue !== null && (isNaN(priceValue) || priceValue < 0)) {
        toast({
          title: 'Invalid Price',
          description: 'Please enter a valid positive number or leave empty to remove override.',
          variant: 'destructive',
        });
        return;
      }

      await adminLeadsApi.overridePrice(selectedLead.id, priceValue);

      toast({
        title: 'Success',
        description: priceValue === null 
          ? 'Price override removed. Using calculated price.'
          : `Lead price updated to ${priceValue} credits.`,
      });

      setIsPriceModalOpen(false);
      await loadLeads();
    } catch (error: any) {
      console.error('Error overriding price:', error);
      toast({
        title: 'Error',
        description: error.message || 'Failed to update price.',
        variant: 'destructive',
      });
    } finally {
      setIsUpdatingPrice(false);
    }
  };

  const handleDeleteLead = async () => {
    if (!deleteLeadId) return;
    setIsDeleting(true);
    try {
      await adminLeadsApi.delete(deleteLeadId);
      toast({ title: 'Lead silindi' });
      setDeleteLeadId(null);
      loadLeads();
    } catch (e: any) {
      toast({ title: 'Hata', description: e.message, variant: 'destructive' });
    } finally {
      setIsDeleting(false);
    }
  };

  const handleStatusChange = async (leadId: string, status: string) => {
    try {
      await adminLeadsApi.setStatus(leadId, status);
      toast({ title: 'Lead durumu güncellendi' });
      loadLeads();
    } catch (e: any) {
      toast({ title: 'Hata', description: e.message, variant: 'destructive' });
    }
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'new':
        return <Badge variant="outline" className="bg-blue-50 text-blue-700 border-blue-200">New</Badge>;
      case 'sold':
        return <Badge variant="outline" className="bg-green-50 text-green-700 border-green-200">Sold</Badge>;
      case 'expired':
        return <Badge variant="outline" className="bg-gray-50 text-gray-700 border-gray-200">Expired</Badge>;
      default:
        return <Badge variant="outline">{status}</Badge>;
    }
  };

  const calculateDuration = (startDate: string, endDate: string) => {
    const start = new Date(startDate);
    const end = new Date(endDate);
    return Math.ceil((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24));
  };

  // Calculate summary stats
  const totalLeads = leads.length;
  const soldLeads = leads.filter(l => l.status === 'sold').length;
  const totalRevenue = leads.reduce((sum, l) => sum + (l.total_revenue || 0), 0);
  const avgRevenuePerLead = totalLeads > 0 ? (totalRevenue / totalLeads).toFixed(1) : 0;

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold">Leads Management</h1>
        <p className="text-muted-foreground mt-1">
          View and manage all travel leads in the system
        </p>
      </div>

      {/* Summary Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">Total Leads</CardTitle>
            <Package className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{totalLeads}</div>
            <p className="text-xs text-muted-foreground mt-1">All time</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">Sold Leads</CardTitle>
            <TrendingUp className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{soldLeads}</div>
            <p className="text-xs text-muted-foreground mt-1">
              {totalLeads > 0 ? ((soldLeads / totalLeads) * 100).toFixed(1) : 0}% conversion
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">Total Revenue</CardTitle>
            <DollarSign className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{totalRevenue} Credits</div>
            <p className="text-xs text-muted-foreground mt-1">From all purchases</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">Avg Revenue/Lead</CardTitle>
            <TrendingUp className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{avgRevenuePerLead} Credits</div>
            <p className="text-xs text-muted-foreground mt-1">Per lead</p>
          </CardContent>
        </Card>
      </div>

      {/* Filters */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Filter className="h-5 w-5" />
            Filtreler ve Sıralama
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-6 gap-4">
            <div>
              <label className="text-sm font-medium mb-2 block">Destination</label>
              <Input
                placeholder="Search destination..."
                value={destinationFilter}
                onChange={(e) => setDestinationFilter(e.target.value)}
              />
            </div>

            <div>
              <label className="text-sm font-medium mb-2 block">Status</label>
              <Select value={statusFilter} onValueChange={setStatusFilter}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Status</SelectItem>
                  <SelectItem value="new">New</SelectItem>
                  <SelectItem value="sold">Sold</SelectItem>
                  <SelectItem value="expired">Expired</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div>
              <label className="text-sm font-medium mb-2 block">Persona Type</label>
              <Select value={personaFilter} onValueChange={setPersonaFilter}>
                <SelectTrigger>
                  <SelectValue placeholder="All Personas" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">Tümü</SelectItem>
                  <SelectItem value="romantic_couple">💑 Romantik Çift</SelectItem>
                  <SelectItem value="luxury_traveler">👑 Lüks Gezgin</SelectItem>
                  <SelectItem value="content_creator">📸 İçerik Üreticisi</SelectItem>
                  <SelectItem value="budget_backpacker">🎒 Bütçe Gezgini</SelectItem>
                  <SelectItem value="family_explorer">👨‍👩‍👧‍👦 Aile Gezgini</SelectItem>
                  <SelectItem value="solo_adventurer">🧗 Solo Maceracı</SelectItem>
                  <SelectItem value="group_tour">👥 Grup Turu</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div>
              <label className="text-sm font-medium mb-2 block">Start Date From</label>
              <Input
                type="date"
                value={startDateFilter}
                onChange={(e) => setStartDateFilter(e.target.value)}
              />
            </div>

            <div>
              <label className="text-sm font-medium mb-2 block">Start Date To</label>
              <Input
                type="date"
                value={endDateFilter}
                onChange={(e) => setEndDateFilter(e.target.value)}
              />
            </div>

            <div className="flex items-end gap-2">
              <Button onClick={handleApplyFilters} className="flex-1">
                Apply
              </Button>
              <Button onClick={handleResetFilters} variant="outline">
                <RotateCcw className="h-4 w-4" />
              </Button>
            </div>
          </div>
          
          {/* Sorting Section */}
          <div className="mt-4 pt-4 border-t">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="md:col-span-2">
                <label className="text-sm font-medium mb-2 block">Sıralama</label>
                <Select value={sortBy} onValueChange={setSortBy}>
                  <SelectTrigger>
                    <SelectValue placeholder="Sıralama seçin" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="created_at_desc">En Yeni</SelectItem>
                    <SelectItem value="created_at_asc">En Eski</SelectItem>
                    <SelectItem value="spend_desc">Harcama Potansiyeli (Yüksek → Düşük)</SelectItem>
                    <SelectItem value="spend_asc">Harcama Potansiyeli (Düşük → Yüksek)</SelectItem>
                    <SelectItem value="confidence_desc">Güven Skoru (Yüksek → Düşük)</SelectItem>
                    <SelectItem value="confidence_asc">Güven Skoru (Düşük → Yüksek)</SelectItem>
                    <SelectItem value="price_desc">Fiyat (Yüksek → Düşük)</SelectItem>
                    <SelectItem value="price_asc">Fiyat (Düşük → Yüksek)</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Leads Table */}
      <Card>
        <CardHeader>
          <CardTitle>All Leads ({leads.length})</CardTitle>
        </CardHeader>
        <CardContent>
          {loading ? (
            <div className="space-y-3">
              {[1, 2, 3, 4, 5].map((i) => (
                <Skeleton key={i} className="h-16 w-full bg-muted" />
              ))}
            </div>
          ) : leads.length === 0 ? (
            <div className="text-center py-12">
              <Package className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
              <p className="text-lg font-medium">No leads found</p>
              <p className="text-sm text-muted-foreground">
                Try adjusting your filters or check back later
              </p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Destination</TableHead>
                    <TableHead>Persona</TableHead>
                    <TableHead>Dates</TableHead>
                    <TableHead>Travelers</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead>Providers Unlocked</TableHead>
                    <TableHead>Price</TableHead>
                    <TableHead>Revenue</TableHead>
                    <TableHead>Created</TableHead>
                    <TableHead>Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {leads.map((lead) => (
                    <TableRow key={lead.id}>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <MapPin className="h-4 w-4 text-muted-foreground" />
                          <div>
                            <p className="font-medium">{lead.destination}</p>
                            <p className="text-xs text-muted-foreground">{lead.country}</p>
                          </div>
                        </div>
                      </TableCell>
                      <TableCell>
                        {lead.tourist_persona ? (
                          <PersonaBadge 
                            persona={lead.tourist_persona as TouristPersona}
                            confidence={lead.persona_confidence}
                            language="en"
                            compact
                          />
                        ) : (
                          <span className="text-sm text-muted-foreground">N/A</span>
                        )}
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <Calendar className="h-4 w-4 text-muted-foreground" />
                          <div className="text-sm">
                            <p>{new Date(lead.start_date).toLocaleDateString()}</p>
                            <p className="text-xs text-muted-foreground">
                              {calculateDuration(lead.start_date, lead.end_date)} days
                            </p>
                          </div>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <Users className="h-4 w-4 text-muted-foreground" />
                          <span>{lead.number_of_travelers}</span>
                        </div>
                      </TableCell>
                      <TableCell>{getStatusBadge(lead.status)}</TableCell>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <Users className="h-4 w-4 text-muted-foreground" />
                          <span className="font-semibold">{lead.providers_unlocked}</span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="space-y-1">
                          <div className="flex items-center gap-2">
                            <DollarSign className="h-4 w-4 text-muted-foreground" />
                            <span className="font-semibold">{lead.final_price || lead.calculated_price || 20}</span>
                          </div>
                          {lead.override_price ? (
                            <Badge variant="outline" className="text-xs bg-amber-50 text-amber-700 border-amber-200">
                              Override
                            </Badge>
                          ) : (
                            <Badge variant="outline" className="text-xs">
                              Auto
                            </Badge>
                          )}
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <DollarSign className="h-4 w-4 text-muted-foreground" />
                          <span className="font-semibold">{lead.total_revenue}</span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <Clock className="h-4 w-4 text-muted-foreground" />
                          <span className="text-sm">
                            {new Date(lead.created_at).toLocaleDateString()}
                          </span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <Button
                            size="icon"
                            variant="ghost"
                            onClick={() => handleViewLead(lead)}
                            title="View"
                          >
                            <Eye className="h-4 w-4" />
                          </Button>
                          <Button
                            size="icon"
                            variant="ghost"
                            onClick={() => handleOpenPriceModal(lead)}
                            title="Price Override"
                          >
                            <Edit className="h-4 w-4" />
                          </Button>
                          <Select
                            value={lead.status}
                            onValueChange={(value) => handleStatusChange(lead.id, value)}
                          >
                            <SelectTrigger className="w-[110px] h-8 text-xs">
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="new">New</SelectItem>
                              <SelectItem value="sold">Sold</SelectItem>
                              <SelectItem value="expired">Expired</SelectItem>
                              <SelectItem value="cancelled">Cancelled</SelectItem>
                            </SelectContent>
                          </Select>
                          <Button
                            size="icon"
                            variant="ghost"
                            className="text-destructive hover:text-destructive hover:bg-destructive/10"
                            onClick={() => setDeleteLeadId(lead.id)}
                            title="Delete"
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Lead Detail Modal */}
      <Dialog open={isDetailModalOpen} onOpenChange={setIsDetailModalOpen}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <MapPin className="h-5 w-5 text-primary" />
              {selectedLead?.destination}
            </DialogTitle>
            <DialogDescription>
              Lead details and statistics
            </DialogDescription>
          </DialogHeader>

          {selectedLead && (
            <div className="space-y-6 py-4">
              {/* Persona Info */}
              {selectedLead.tourist_persona && (
                <PersonaBadge 
                  persona={selectedLead.tourist_persona as TouristPersona}
                  confidence={selectedLead.persona_confidence}
                  language="en"
                  showDetails
                />
              )}

              {/* Trip Info */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <p className="text-sm text-muted-foreground">Destination</p>
                  <p className="font-semibold">{selectedLead.destination}, {selectedLead.country}</p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">Status</p>
                  <div className="mt-1">{getStatusBadge(selectedLead.status)}</div>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">Travel Dates</p>
                  <p className="font-semibold">
                    {new Date(selectedLead.start_date).toLocaleDateString()} - {new Date(selectedLead.end_date).toLocaleDateString()}
                  </p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">Duration</p>
                  <p className="font-semibold">
                    {calculateDuration(selectedLead.start_date, selectedLead.end_date)} days
                  </p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">Travelers</p>
                  <p className="font-semibold">{selectedLead.number_of_travelers} people</p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">Created</p>
                  <p className="font-semibold">{new Date(selectedLead.created_at).toLocaleDateString()}</p>
                </div>
              </div>

              {/* Pricing Breakdown */}
              <Card className="bg-blue-50 border-blue-200">
                <CardHeader>
                  <CardTitle className="text-lg">Lead Pricing</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="space-y-3">
                    <div className="flex items-center justify-between">
                      <span className="text-sm text-muted-foreground">Base Price</span>
                      <span className="font-medium">{selectedLead.base_price || 20} Credits</span>
                    </div>
                    <div className="flex items-center justify-between">
                      <span className="text-sm text-muted-foreground">Calculated Price</span>
                      <span className="font-medium">{selectedLead.calculated_price || 20} Credits</span>
                    </div>
                    {selectedLead.override_price && (
                      <div className="flex items-center justify-between pt-2 border-t">
                        <span className="text-sm text-muted-foreground">Admin Override</span>
                        <Badge variant="outline" className="bg-amber-50 text-amber-700 border-amber-200">
                          {selectedLead.override_price} Credits
                        </Badge>
                      </div>
                    )}
                    <div className="flex items-center justify-between pt-2 border-t">
                      <span className="font-semibold">Final Price</span>
                      <span className="text-xl font-bold text-primary">
                        {selectedLead.final_price || selectedLead.calculated_price || 20} Credits
                      </span>
                    </div>
                  </div>
                </CardContent>
              </Card>

              {/* Revenue Stats */}
              <Card className="bg-primary/5 border-primary/20">
                <CardHeader>
                  <CardTitle className="text-lg">Revenue Statistics</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <p className="text-sm text-muted-foreground">Providers Unlocked</p>
                      <p className="text-2xl font-bold">{selectedLead.providers_unlocked}</p>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground">Total Revenue</p>
                      <p className="text-2xl font-bold">{selectedLead.total_revenue} Credits</p>
                    </div>
                  </div>
                </CardContent>
              </Card>

              {/* Contact Info (Admin can view) */}
              <Card>
                <CardHeader>
                  <CardTitle className="text-lg">Contact Information</CardTitle>
                </CardHeader>
                <CardContent className="space-y-2">
                  <div>
                    <p className="text-sm text-muted-foreground">Email</p>
                    <p className="font-mono">{selectedLead.email}</p>
                  </div>
                  <div>
                    <p className="text-sm text-muted-foreground">WhatsApp</p>
                    <p className="font-mono">{selectedLead.whatsapp}</p>
                  </div>
                </CardContent>
              </Card>

              {/* Interests */}
              {selectedLead.interests && selectedLead.interests.length > 0 && (
                <div>
                  <p className="text-sm font-medium mb-2">Interests & Activities</p>
                  <div className="flex flex-wrap gap-2">
                    {selectedLead.interests.map((interest: string, idx: number) => (
                      <Badge key={idx} variant="outline">
                        {interest}
                      </Badge>
                    ))}
                  </div>
                </div>
              )}

              {/* Planned Activities */}
              {selectedLead.planned_activities && selectedLead.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">
                      {selectedLead.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>
                        </div>
                      ))}
                    </div>
                  </CardContent>
                </Card>
              )}
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* Price Override Modal */}
      <Dialog open={isPriceModalOpen} onOpenChange={setIsPriceModalOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Override Lead Price</DialogTitle>
            <DialogDescription>
              Set a custom price for this lead. Leave empty to use the calculated price.
            </DialogDescription>
          </DialogHeader>

          {selectedLead && (
            <div className="space-y-4 py-4">
              <div className="bg-muted/50 p-4 rounded-lg space-y-2">
                <div className="flex items-center justify-between text-sm">
                  <span className="text-muted-foreground">Base Price</span>
                  <span className="font-medium">{selectedLead.base_price || 20} Credits</span>
                </div>
                <div className="flex items-center justify-between text-sm">
                  <span className="text-muted-foreground">Calculated Price</span>
                  <span className="font-medium">{selectedLead.calculated_price || 20} Credits</span>
                </div>
                <div className="flex items-center justify-between text-sm pt-2 border-t">
                  <span className="font-semibold">Current Final Price</span>
                  <span className="text-lg font-bold text-primary">
                    {selectedLead.final_price || selectedLead.calculated_price || 20} Credits
                  </span>
                </div>
              </div>

              <div>
                <label className="text-sm font-medium mb-2 block">
                  Override Price (Credits)
                </label>
                <Input
                  type="number"
                  placeholder="Leave empty to use calculated price"
                  value={overridePrice}
                  onChange={(e) => setOverridePrice(e.target.value)}
                  min="0"
                />
                <p className="text-xs text-muted-foreground mt-2">
                  Enter a custom price or leave empty to remove override and use the calculated price based on activities.
                </p>
              </div>

              {overridePrice && !isNaN(parseInt(overridePrice)) && (
                <div className="bg-primary/10 p-4 rounded-lg border border-primary/20">
                  <p className="text-sm text-muted-foreground">New Price</p>
                  <p className="text-2xl font-bold text-primary">{overridePrice} Credits</p>
                  <Badge variant="outline" className="mt-2">Custom Override</Badge>
                </div>
              )}

              {overridePrice === '' && selectedLead.override_price && (
                <div className="bg-blue-50 p-4 rounded-lg border border-blue-200">
                  <div className="flex items-center gap-2">
                    <RotateCcw className="h-4 w-4 text-blue-600" />
                    <p className="text-sm text-blue-800 font-medium">
                      This will remove the override and use calculated price: {selectedLead.calculated_price || 20} Credits
                    </p>
                  </div>
                </div>
              )}
            </div>
          )}

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setIsPriceModalOpen(false)}
              disabled={isUpdatingPrice}
            >
              Cancel
            </Button>
            <Button
              onClick={handleOverridePrice}
              disabled={isUpdatingPrice}
            >
              {isUpdatingPrice ? 'Updating...' : overridePrice === '' ? 'Remove Override' : 'Set Price'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Delete Confirmation Alert */}
      <AlertDialog open={!!deleteLeadId} onOpenChange={() => setDeleteLeadId(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Lead'i Sil</AlertDialogTitle>
            <AlertDialogDescription>
              Bu lead kalici olarak silinecek. Satın almalar da silinir. Devam?
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>İptal</AlertDialogCancel>
            <AlertDialogAction
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
              onClick={handleDeleteLead}
              disabled={isDeleting}
            >
              {isDeleting ? 'Siliniyor...' : 'Sil'}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
};

export default AdminLeads;
