// ../src/pages/Contacts.tsx
import { useState, useMemo } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Link, useNavigate } from 'react-router-dom';
import {
  Plus, Search, Filter, MoreHorizontal, Mail, Phone, Building2,
  ArrowUpDown, Loader2, Trash2, Pencil, Download, Upload, Tag,
  RefreshCcw, ChevronLeft, ChevronRight, X, Check,
  ArrowUp, ArrowDown, FileJson, FileSpreadsheet, Users,
  UserPlus, TrendingUp, Clock, Grid3X3, List, Eye,
  Sparkles, Copy, ExternalLink, LayoutGrid, TableIcon
} from 'lucide-react';
import { useContacts, useTags, ContactWithTags } from '@/hooks/useContacts';
import { useTrashedContacts } from '@/hooks/useTrash';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { StatusBadge } from '@/components/ui/status-badge';
import { Checkbox } from '@/components/ui/checkbox';
import { Label } from '@/components/ui/label';
import { Card, CardContent } from '@/components/ui/card';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import {
  DropdownMenu, DropdownMenuContent, DropdownMenuItem,
  DropdownMenuSeparator, DropdownMenuTrigger, DropdownMenuSub,
  DropdownMenuSubTrigger, DropdownMenuSubContent,
} from '@/components/ui/dropdown-menu';
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from '@/components/ui/select';
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from '@/components/ui/table';
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 {
  Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle,
} from '@/components/ui/sheet';
import { ContactFormDialog } from '@/components/contacts/ContactFormDialog';
import { toast } from 'sonner';
import { cn } from '@/lib/utils';

type SortField = 'name' | 'email' | 'company' | 'status' | 'created_at';
type SortDirection = 'asc' | 'desc';
type ContactStatus = 'lead' | 'prospect' | 'customer' | 'churned';
type ViewMode = 'table' | 'grid';

const STATUS_OPTIONS: ContactStatus[] = ['lead', 'prospect', 'customer', 'churned'];

const statusConfig = {
  lead: { color: 'bg-blue-500', bgLight: 'bg-blue-500/10', text: 'text-blue-600', icon: Sparkles },
  prospect: { color: 'bg-amber-500', bgLight: 'bg-amber-500/10', text: 'text-amber-600', icon: TrendingUp },
  customer: { color: 'bg-emerald-500', bgLight: 'bg-emerald-500/10', text: 'text-emerald-600', icon: Check },
  churned: { color: 'bg-slate-400', bgLight: 'bg-slate-400/10', text: 'text-slate-500', icon: Clock },
};

// Stats Card Component
function StatsCard({ 
  title, 
  value, 
  icon: Icon, 
  trend, 
  color,
  onClick,
  isActive 
}: { 
  title: string; 
  value: number; 
  icon: any; 
  trend?: number;
  color: string;
  onClick?: () => void;
  isActive?: boolean;
}) {
  return (
    <motion.div
      whileHover={{ scale: 1.02, y: -2 }}
      whileTap={{ scale: 0.98 }}
    >
      <Card 
        className={cn(
          "cursor-pointer transition-all duration-300 border-2",
          isActive 
            ? "border-primary shadow-lg shadow-primary/20" 
            : "border-transparent hover:border-border hover:shadow-md"
        )}
        onClick={onClick}
      >
        <CardContent className="p-4">
          <div className="flex items-center justify-between">
            <div className="space-y-1">
              <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider">{title}</p>
              <p className="text-2xl font-bold">{value}</p>
              {trend !== undefined && (
                <p className={cn(
                  "text-xs font-medium flex items-center gap-1",
                  trend >= 0 ? "text-emerald-600" : "text-red-500"
                )}>
                  <TrendingUp className={cn("h-3 w-3", trend < 0 && "rotate-180")} />
                  {Math.abs(trend)}% this month
                </p>
              )}
            </div>
            <div className={cn("p-3 rounded-xl", color)}>
              <Icon className="h-5 w-5 text-white" />
            </div>
          </div>
        </CardContent>
      </Card>
    </motion.div>
  );
}

// Contact Card for Grid View
function ContactCard({ 
  contact, 
  isSelected,
  onSelect,
  onEdit,
  onDelete,
  onStatusChange 
}: { 
  contact: ContactWithTags;
  isSelected: boolean;
  onSelect: () => void;
  onEdit: () => void;
  onDelete: () => void;
  onStatusChange: (status: ContactStatus) => void;
}) {
  const navigate = useNavigate();
  
  const getInitials = (firstName: string, lastName: string) => {
    return `${firstName[0] ?? ''}${lastName[0] ?? ''}`.toUpperCase();
  };

  return (
    <motion.div
      layout
      initial={{ opacity: 0, scale: 0.9 }}
      animate={{ opacity: 1, scale: 1 }}
      exit={{ opacity: 0, scale: 0.9 }}
      whileHover={{ y: -4 }}
      className="group"
    >
      <Card className={cn(
        "relative overflow-hidden transition-all duration-300",
        isSelected 
          ? "ring-2 ring-primary shadow-lg" 
          : "hover:shadow-lg hover:border-border"
      )}>
        {/* Selection checkbox */}
        <div className="absolute top-3 left-3 z-10">
          <Checkbox
            checked={isSelected}
            onCheckedChange={onSelect}
            className="bg-background/80 backdrop-blur-sm"
          />
        </div>

        {/* Quick actions */}
        <div className="absolute top-3 right-3 z-10 opacity-0 group-hover:opacity-100 transition-opacity">
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="secondary" size="icon" className="h-8 w-8 shadow-md">
                <MoreHorizontal className="h-4 w-4" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuItem onClick={() => navigate(`/contacts/${contact.id}`)}>
                <Eye className="h-4 w-4 mr-2" />
                View Details
              </DropdownMenuItem>
              <DropdownMenuItem onClick={onEdit}>
                <Pencil className="h-4 w-4 mr-2" />
                Edit
              </DropdownMenuItem>
              <DropdownMenuSub>
                <DropdownMenuSubTrigger>
                  <RefreshCcw className="h-4 w-4 mr-2" />
                  Change Status
                </DropdownMenuSubTrigger>
                <DropdownMenuSubContent>
                  {STATUS_OPTIONS.map(s => (
                    <DropdownMenuItem 
                      key={s} 
                      onClick={() => onStatusChange(s)}
                      className="capitalize"
                    >
                      {contact.status === s && <Check className="h-4 w-4 mr-2" />}
                      {s}
                    </DropdownMenuItem>
                  ))}
                </DropdownMenuSubContent>
              </DropdownMenuSub>
              <DropdownMenuSeparator />
              <DropdownMenuItem onClick={onDelete} className="text-destructive">
                <Trash2 className="h-4 w-4 mr-2" />
                Delete
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>

        <CardContent className="p-6 pt-10">
          <div className="flex flex-col items-center text-center">
            {/* Avatar with gradient border */}
            <div className="relative mb-4">
              <div className="absolute inset-0 rounded-full bg-gradient-to-r from-primary via-purple-500 to-pink-500 blur-sm opacity-50 animate-pulse" />
              <Avatar className="h-16 w-16 relative ring-2 ring-background">
                {contact.avatar_url && <AvatarImage src={contact.avatar_url} alt={contact.first_name} />}
                <AvatarFallback className="bg-gradient-to-br from-primary/20 to-purple-500/20 text-primary text-lg font-semibold">
                  {getInitials(contact.first_name, contact.last_name)}
                </AvatarFallback>
              </Avatar>
            </div>

            {/* Name */}
            <Link 
              to={`/contacts/${contact.id}`}
              className="font-semibold text-lg hover:text-primary transition-colors line-clamp-1"
            >
              {contact.first_name} {contact.last_name}
            </Link>

            {/* Company */}
            {contact.company && (
              <div className="flex items-center gap-1 text-sm text-muted-foreground mt-0.5">
                <Building2 className="h-3 w-3" />
                <span className="line-clamp-1">{contact.company}</span>
              </div>
            )}

            {/* Status */}
            <div className="mt-3">
              <StatusBadge status={contact.status} />
            </div>

            {/* Tags */}
            {contact.tags.length > 0 && (
              <div className="flex items-center gap-1 mt-3 flex-wrap justify-center">
                {contact.tags.slice(0, 3).map((tag) => (
                  <span
                    key={tag.id}
                    className="inline-flex h-5 items-center rounded-full px-2 text-xs font-medium"
                    style={{ backgroundColor: `${tag.color}20`, color: tag.color }}
                  >
                    {tag.name}
                  </span>
                ))}
                {contact.tags.length > 3 && (
                  <span className="text-xs text-muted-foreground">+{contact.tags.length - 3}</span>
                )}
              </div>
            )}

            {/* Contact Actions */}
            <div className="flex items-center gap-2 mt-4 pt-4 border-t w-full justify-center">
              <TooltipProvider>
                <Tooltip>
                  <TooltipTrigger asChild>
                    <Button 
                      variant="ghost" 
                      size="icon" 
                      className="h-9 w-9 rounded-full"
                      onClick={(e) => {
                        e.stopPropagation();
                        navigator.clipboard.writeText(contact.email);
                        toast.success('Email copied!');
                      }}
                    >
                      <Mail className="h-4 w-4" />
                    </Button>
                  </TooltipTrigger>
                  <TooltipContent>{contact.email}</TooltipContent>
                </Tooltip>
              </TooltipProvider>

              {contact.phone && (
                <TooltipProvider>
                  <Tooltip>
                    <TooltipTrigger asChild>
                      <Button 
                        variant="ghost" 
                        size="icon" 
                        className="h-9 w-9 rounded-full"
                        onClick={(e) => {
                          e.stopPropagation();
                          navigator.clipboard.writeText(contact.phone!);
                          toast.success('Phone copied!');
                        }}
                      >
                        <Phone className="h-4 w-4" />
                      </Button>
                    </TooltipTrigger>
                    <TooltipContent>{contact.phone}</TooltipContent>
                  </Tooltip>
                </TooltipProvider>
              )}

              <TooltipProvider>
                <Tooltip>
                  <TooltipTrigger asChild>
                    <Button 
                      variant="ghost" 
                      size="icon" 
                      className="h-9 w-9 rounded-full"
                      onClick={() => navigate(`/contacts/${contact.id}`)}
                    >
                      <ExternalLink className="h-4 w-4" />
                    </Button>
                  </TooltipTrigger>
                  <TooltipContent>View Details</TooltipContent>
                </Tooltip>
              </TooltipProvider>
            </div>
          </div>
        </CardContent>
      </Card>
    </motion.div>
  );
}

// Empty State Component
function EmptyState({ hasFilters, onAddContact }: { hasFilters: boolean; onAddContact: () => void }) {
  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      className="flex flex-col items-center justify-center py-16 px-4"
    >
      <div className="relative mb-6">
        <div className="absolute inset-0 bg-gradient-to-r from-primary/20 to-purple-500/20 rounded-full blur-2xl" />
        <div className="relative bg-gradient-to-br from-primary/10 to-purple-500/10 rounded-full p-6">
          <Users className="h-12 w-12 text-primary" />
        </div>
      </div>
      <h3 className="text-xl font-semibold mb-2">
        {hasFilters ? 'No contacts found' : 'No contacts yet'}
      </h3>
      <p className="text-muted-foreground text-center max-w-sm mb-6">
        {hasFilters 
          ? "Try adjusting your filters or search terms to find what you're looking for."
          : "Get started by adding your first contact. You can import from CSV or add them manually."
        }
      </p>
      {!hasFilters && (
        <div className="flex items-center gap-3">
          <Button onClick={onAddContact} className="gap-2">
            <Plus className="h-4 w-4" />
            Add Contact
          </Button>
          <Button variant="outline" className="gap-2">
            <Upload className="h-4 w-4" />
            Import
          </Button>
        </div>
      )}
    </motion.div>
  );
}

export default function Contacts() {
  const navigate = useNavigate();
  const { contacts, isLoading, createContact, updateContact, isCreating, isUpdating } = useContacts();
  const { softDelete, isSoftDeleting } = useTrashedContacts();
  const { data: tags = [] } = useTags();
  
  // View Mode
  const [viewMode, setViewMode] = useState<ViewMode>('table');
  
  // Search & Filters
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState<ContactStatus | 'all'>('all');
  const [tagFilter, setTagFilter] = useState<string | 'all'>('all');
  const [sourceFilter, setSourceFilter] = useState<string | 'all'>('all');
  
  // Selection
  const [selectedContacts, setSelectedContacts] = useState<string[]>([]);
  
  // Sorting
  const [sortField, setSortField] = useState<SortField>('created_at');
  const [sortDirection, setSortDirection] = useState<SortDirection>('desc');
  
  // Pagination
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  
  // Dialogs
  const [isFormOpen, setIsFormOpen] = useState(false);
  const [editingContact, setEditingContact] = useState<ContactWithTags | null>(null);
  const [deletingContactId, setDeletingContactId] = useState<string | null>(null);
  const [isBulkDeleteOpen, setIsBulkDeleteOpen] = useState(false);
  const [isImportOpen, setIsImportOpen] = useState(false);
  const [importData, setImportData] = useState<string>('');
  const [isFiltersOpen, setIsFiltersOpen] = useState(false);

  // Stats
  const stats = useMemo(() => {
    const total = contacts.length;
    const leads = contacts.filter(c => c.status === 'lead').length;
    const prospects = contacts.filter(c => c.status === 'prospect').length;
    const customers = contacts.filter(c => c.status === 'customer').length;
    const churned = contacts.filter(c => c.status === 'churned').length;
    
    return { total, leads, prospects, customers, churned };
  }, [contacts]);

  // Get unique sources for filter
  const sources = useMemo(() => {
    const uniqueSources = new Set(contacts.map(c => c.source).filter(Boolean));
    return Array.from(uniqueSources) as string[];
  }, [contacts]);

  // Filtered & Sorted contacts
  const filteredContacts = useMemo(() => {
    let result = contacts.filter((contact) => {
      const searchLower = searchQuery.toLowerCase();
      const matchesSearch = 
        contact.first_name.toLowerCase().includes(searchLower) ||
        contact.last_name.toLowerCase().includes(searchLower) ||
        contact.email.toLowerCase().includes(searchLower) ||
        contact.company?.toLowerCase().includes(searchLower) ||
        contact.phone?.toLowerCase().includes(searchLower);
      
      const matchesStatus = statusFilter === 'all' || contact.status === statusFilter;
      const matchesTag = tagFilter === 'all' || contact.tags.some(t => t.id === tagFilter);
      const matchesSource = sourceFilter === 'all' || contact.source === sourceFilter;
      
      return matchesSearch && matchesStatus && matchesTag && matchesSource;
    });

    // Sort
    result.sort((a, b) => {
      let aVal: string | Date, bVal: string | Date;
      
      switch (sortField) {
        case 'name':
          aVal = `${a.first_name} ${a.last_name}`.toLowerCase();
          bVal = `${b.first_name} ${b.last_name}`.toLowerCase();
          break;
        case 'email':
          aVal = a.email.toLowerCase();
          bVal = b.email.toLowerCase();
          break;
        case 'company':
          aVal = (a.company || '').toLowerCase();
          bVal = (b.company || '').toLowerCase();
          break;
        case 'status':
          aVal = a.status;
          bVal = b.status;
          break;
        case 'created_at':
          aVal = new Date(a.created_at);
          bVal = new Date(b.created_at);
          break;
        default:
          aVal = a.created_at;
          bVal = b.created_at;
      }
      
      if (aVal < bVal) return sortDirection === 'asc' ? -1 : 1;
      if (aVal > bVal) return sortDirection === 'asc' ? 1 : -1;
      return 0;
    });

    return result;
  }, [contacts, searchQuery, statusFilter, tagFilter, sourceFilter, sortField, sortDirection]);

  // Pagination
  const totalPages = Math.ceil(filteredContacts.length / pageSize);
  const paginatedContacts = useMemo(() => {
    const start = (currentPage - 1) * pageSize;
    return filteredContacts.slice(start, start + pageSize);
  }, [filteredContacts, currentPage, pageSize]);

  // Reset page when filters change
  const handleFilterChange = () => {
    setCurrentPage(1);
  };

  const toggleContact = (id: string) => {
    setSelectedContacts((prev) =>
      prev.includes(id) ? prev.filter((c) => c !== id) : [...prev, id]
    );
  };

  const toggleAll = () => {
    if (selectedContacts.length === paginatedContacts.length) {
      setSelectedContacts([]);
    } else {
      setSelectedContacts(paginatedContacts.map((c) => c.id));
    }
  };

  const getInitials = (firstName: string, lastName: string) => {
    return `${firstName[0] ?? ''}${lastName[0] ?? ''}`.toUpperCase();
  };

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

  const handleSort = (field: SortField) => {
    if (sortField === field) {
      setSortDirection(prev => prev === 'asc' ? 'desc' : 'asc');
    } else {
      setSortField(field);
      setSortDirection('asc');
    }
  };

  const SortIcon = ({ field }: { field: SortField }) => {
    if (sortField !== field) return <ArrowUpDown className="h-3 w-3 opacity-50" />;
    return sortDirection === 'asc' ? 
      <ArrowUp className="h-3 w-3" /> : 
      <ArrowDown className="h-3 w-3" />;
  };

  const handleEdit = (contact: ContactWithTags) => {
    setEditingContact(contact);
    setIsFormOpen(true);
  };

  const handleDelete = async () => {
    if (deletingContactId) {
      await softDelete({ contactId: deletingContactId, deletedFrom: 'Contacts List' });
      setDeletingContactId(null);
    }
  };

  const handleBulkDelete = async () => {
    for (const id of selectedContacts) {
      await softDelete({ contactId: id, deletedFrom: 'Bulk Delete' });
    }
    setSelectedContacts([]);
    setIsBulkDeleteOpen(false);
    toast.success(`${selectedContacts.length} contacts moved to trash`);
  };

  const handleBulkStatusChange = async (status: ContactStatus) => {
    for (const id of selectedContacts) {
      const contact = contacts.find(c => c.id === id);
      if (contact) {
        await updateContact({ id, status, previousData: contact });
      }
    }
    setSelectedContacts([]);
    toast.success(`Status updated for ${selectedContacts.length} contacts`);
  };

  const handleFormSubmit = async (data: any) => {
    if (editingContact) {
      await updateContact(data);
    } else {
      await createContact(data);
    }
    setEditingContact(null);
  };

  const handleFormClose = (open: boolean) => {
    setIsFormOpen(open);
    if (!open) {
      setEditingContact(null);
    }
  };

  // Export functions
  const exportAsCSV = () => {
    const selectedData = selectedContacts.length > 0 
      ? contacts.filter(c => selectedContacts.includes(c.id))
      : filteredContacts;
    
    const headers = ['First Name', 'Last Name', 'Email', 'Phone', 'Company', 'Status', 'Source', 'Created'];
    const rows = selectedData.map(c => [
      c.first_name,
      c.last_name,
      c.email,
      c.phone || '',
      c.company || '',
      c.status,
      c.source || '',
      formatDate(c.created_at)
    ]);
    
    const csv = [headers, ...rows].map(row => row.map(cell => `"${cell}"`).join(',')).join('\n');
    downloadFile(csv, 'contacts.csv', 'text/csv');
    toast.success(`Exported ${selectedData.length} contacts as CSV`);
  };

  const exportAsJSON = () => {
    const selectedData = selectedContacts.length > 0 
      ? contacts.filter(c => selectedContacts.includes(c.id))
      : filteredContacts;
    
    const exportData = selectedData.map(({ tags, ...c }) => ({
      ...c,
      tags: tags.map(t => t.name)
    }));
    
    const json = JSON.stringify(exportData, null, 2);
    downloadFile(json, 'contacts.json', 'application/json');
    toast.success(`Exported ${selectedData.length} contacts as JSON`);
  };

  const downloadFile = (content: string, filename: string, mimeType: string) => {
    const blob = new Blob([content], { type: mimeType });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    a.click();
    URL.revokeObjectURL(url);
  };

  // Import functions
  const handleImport = async () => {
    try {
      let rows: any[] = [];
      
      // Try parsing as JSON first
      try {
        const jsonData = JSON.parse(importData);
        rows = Array.isArray(jsonData) ? jsonData : [jsonData];
      } catch {
        // Parse as CSV
        const lines = importData.trim().split('\n');
        const headers = lines[0].split(',').map(h => h.replace(/"/g, '').trim().toLowerCase());
        
        for (let i = 1; i < lines.length; i++) {
          const values = lines[i].split(',').map(v => v.replace(/"/g, '').trim());
          const row: Record<string, string> = {};
          headers.forEach((h, idx) => {
            row[h] = values[idx] || '';
          });
          rows.push(row);
        }
      }

      let imported = 0;
      for (const row of rows) {
        const contact = {
          first_name: row.first_name || row['first name'] || '',
          last_name: row.last_name || row['last name'] || '',
          email: row.email || '',
          phone: row.phone || null,
          company: row.company || null,
          source: row.source || 'Import',
          status: (['lead', 'prospect', 'customer', 'churned'].includes(row.status) ? row.status : 'lead') as ContactStatus,
        };
        
        if (contact.first_name && contact.last_name && contact.email) {
          await createContact(contact);
          imported++;
        }
      }
      
      setIsImportOpen(false);
      setImportData('');
      toast.success(`Imported ${imported} contacts`);
    } catch (error) {
      toast.error('Failed to parse import data. Please check the format.');
    }
  };

  const clearFilters = () => {
    setStatusFilter('all');
    setTagFilter('all');
    setSourceFilter('all');
    setSearchQuery('');
    handleFilterChange();
  };

  const activeFiltersCount = [statusFilter !== 'all', tagFilter !== 'all', sourceFilter !== 'all'].filter(Boolean).length;

  // Generate page numbers for pagination
  const getPageNumbers = () => {
    const pages: (number | 'ellipsis')[] = [];
    const maxVisible = 5;
    
    if (totalPages <= maxVisible) {
      for (let i = 1; i <= totalPages; i++) pages.push(i);
    } else {
      if (currentPage <= 3) {
        for (let i = 1; i <= 4; i++) pages.push(i);
        pages.push('ellipsis');
        pages.push(totalPages);
      } else if (currentPage >= totalPages - 2) {
        pages.push(1);
        pages.push('ellipsis');
        for (let i = totalPages - 3; i <= totalPages; i++) pages.push(i);
      } else {
        pages.push(1);
        pages.push('ellipsis');
        for (let i = currentPage - 1; i <= currentPage + 1; i++) pages.push(i);
        pages.push('ellipsis');
        pages.push(totalPages);
      }
    }
    
    return pages;
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-[50vh]">
        <div className="text-center space-y-4">
          <div className="relative">
            <div className="absolute inset-0 bg-gradient-to-r from-primary/20 to-purple-500/20 rounded-full blur-2xl animate-pulse" />
            <Loader2 className="h-12 w-12 animate-spin text-primary relative" />
          </div>
          <p className="text-muted-foreground">Loading contacts...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6 animate-fade-in">
      {/* Header */}
      <div className="flex items-center justify-between flex-wrap gap-4">
        <div>
          <h1 className="text-3xl font-bold tracking-tight bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text">
            Contacts
          </h1>
          <p className="text-muted-foreground mt-1">
            Manage and organize your contacts
          </p>
        </div>
        <div className="flex items-center gap-2">
          {/* Import */}
          <Button variant="outline" onClick={() => setIsImportOpen(true)}>
            <Upload className="h-4 w-4 mr-2" />
            Import
          </Button>
          
          {/* Export */}
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="outline">
                <Download className="h-4 w-4 mr-2" />
                Export
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuItem onClick={exportAsCSV}>
                <FileSpreadsheet className="h-4 w-4 mr-2" />
                Export as CSV
              </DropdownMenuItem>
              <DropdownMenuItem onClick={exportAsJSON}>
                <FileJson className="h-4 w-4 mr-2" />
                Export as JSON
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
          
          <Button 
            className="bg-gradient-to-r from-primary to-purple-600 hover:from-primary/90 hover:to-purple-600/90 shadow-lg shadow-primary/25 gap-2"
            onClick={() => setIsFormOpen(true)}
          >
            <Plus className="h-4 w-4" />
            Add Contact
          </Button>
        </div>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
        <StatsCard
          title="Total Contacts"
          value={stats.total}
          icon={Users}
          color="bg-gradient-to-br from-slate-600 to-slate-700"
          onClick={() => { setStatusFilter('all'); handleFilterChange(); }}
          isActive={statusFilter === 'all'}
        />
        <StatsCard
          title="Leads"
          value={stats.leads}
          icon={Sparkles}
          color="bg-gradient-to-br from-blue-500 to-blue-600"
          onClick={() => { setStatusFilter('lead'); handleFilterChange(); }}
          isActive={statusFilter === 'lead'}
        />
        <StatsCard
          title="Prospects"
          value={stats.prospects}
          icon={TrendingUp}
          color="bg-gradient-to-br from-amber-500 to-orange-500"
          onClick={() => { setStatusFilter('prospect'); handleFilterChange(); }}
          isActive={statusFilter === 'prospect'}
        />
        <StatsCard
          title="Customers"
          value={stats.customers}
          icon={Check}
          color="bg-gradient-to-br from-emerald-500 to-green-600"
          onClick={() => { setStatusFilter('customer'); handleFilterChange(); }}
          isActive={statusFilter === 'customer'}
        />
        <StatsCard
          title="Churned"
          value={stats.churned}
          icon={Clock}
          color="bg-gradient-to-br from-slate-400 to-slate-500"
          onClick={() => { setStatusFilter('churned'); handleFilterChange(); }}
          isActive={statusFilter === 'churned'}
        />
      </div>

      {/* Search, Filters & View Toggle */}
      <div className="flex items-center gap-3 flex-wrap">
        <div className="relative flex-1 min-w-[200px] max-w-sm">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input
            placeholder="Search by name, email, company..."
            value={searchQuery}
            onChange={(e) => { setSearchQuery(e.target.value); handleFilterChange(); }}
            className="pl-9 bg-background"
          />
          {searchQuery && (
            <Button
              variant="ghost"
              size="icon"
              className="absolute right-1 top-1/2 -translate-y-1/2 h-7 w-7"
              onClick={() => { setSearchQuery(''); handleFilterChange(); }}
            >
              <X className="h-3 w-3" />
            </Button>
          )}
        </div>
        
        {/* Filter Button */}
        <Button 
          variant={activeFiltersCount > 0 ? "secondary" : "outline"} 
          className="gap-2"
          onClick={() => setIsFiltersOpen(true)}
        >
          <Filter className="h-4 w-4" />
          Filters
          {activeFiltersCount > 0 && (
            <Badge className="ml-1 h-5 w-5 p-0 flex items-center justify-center rounded-full bg-primary text-primary-foreground">
              {activeFiltersCount}
            </Badge>
          )}
        </Button>

        {/* View Toggle */}
        <div className="flex items-center border rounded-lg p-1 bg-muted/50">
          <Button
            variant={viewMode === 'table' ? 'secondary' : 'ghost'}
            size="sm"
            className="h-8 px-3"
            onClick={() => setViewMode('table')}
          >
            <List className="h-4 w-4" />
          </Button>
          <Button
            variant={viewMode === 'grid' ? 'secondary' : 'ghost'}
            size="sm"
            className="h-8 px-3"
            onClick={() => setViewMode('grid')}
          >
            <LayoutGrid className="h-4 w-4" />
          </Button>
        </div>

        {/* Results count */}
        <div className="text-sm text-muted-foreground ml-auto">
          {filteredContacts.length} of {contacts.length} contacts
        </div>

        {/* Bulk Actions */}
        <AnimatePresence>
          {selectedContacts.length > 0 && (
            <motion.div
              initial={{ opacity: 0, scale: 0.9 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0, scale: 0.9 }}
              className="flex items-center gap-2 pl-4 border-l"
            >
              <Badge variant="secondary" className="font-normal bg-primary/10 text-primary">
                {selectedContacts.length} selected
              </Badge>
              
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button variant="outline" size="sm">
                    <RefreshCcw className="h-4 w-4 mr-1" />
                    Status
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent>
                  {STATUS_OPTIONS.map(s => (
                    <DropdownMenuItem key={s} onClick={() => handleBulkStatusChange(s)} className="capitalize">
                      {s}
                    </DropdownMenuItem>
                  ))}
                </DropdownMenuContent>
              </DropdownMenu>
              
              <Button 
                variant="outline" 
                size="sm" 
                className="text-destructive border-destructive/30 hover:bg-destructive/10"
                onClick={() => setIsBulkDeleteOpen(true)}
              >
                <Trash2 className="h-4 w-4 mr-1" />
                Delete
              </Button>
              
              <Button 
                variant="ghost" 
                size="icon"
                className="h-8 w-8"
                onClick={() => setSelectedContacts([])}
              >
                <X className="h-4 w-4" />
              </Button>
            </motion.div>
          )}
        </AnimatePresence>
      </div>

      {/* Active Filters Display */}
      <AnimatePresence>
        {activeFiltersCount > 0 && (
          <motion.div
            initial={{ opacity: 0, height: 0 }}
            animate={{ opacity: 1, height: 'auto' }}
            exit={{ opacity: 0, height: 0 }}
            className="flex items-center gap-2 flex-wrap"
          >
            <span className="text-sm text-muted-foreground">Active filters:</span>
            {statusFilter !== 'all' && (
              <Badge variant="secondary" className="gap-1 pr-1 capitalize">
                Status: {statusFilter}
                <Button
                  variant="ghost"
                  size="icon"
                  className="h-4 w-4 ml-1 hover:bg-background/50"
                  onClick={() => { setStatusFilter('all'); handleFilterChange(); }}
                >
                  <X className="h-3 w-3" />
                </Button>
              </Badge>
            )}
            {tagFilter !== 'all' && (
              <Badge variant="secondary" className="gap-1 pr-1">
                Tag: {tags.find(t => t.id === tagFilter)?.name}
                <Button
                  variant="ghost"
                  size="icon"
                  className="h-4 w-4 ml-1 hover:bg-background/50"
                  onClick={() => { setTagFilter('all'); handleFilterChange(); }}
                >
                  <X className="h-3 w-3" />
                </Button>
              </Badge>
            )}
            {sourceFilter !== 'all' && (
              <Badge variant="secondary" className="gap-1 pr-1">
                Source: {sourceFilter}
                <Button
                  variant="ghost"
                  size="icon"
                  className="h-4 w-4 ml-1 hover:bg-background/50"
                  onClick={() => { setSourceFilter('all'); handleFilterChange(); }}
                >
                  <X className="h-3 w-3" />
                </Button>
              </Badge>
            )}
            <Button variant="ghost" size="sm" onClick={clearFilters} className="text-xs">
              Clear all
            </Button>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Content */}
      {paginatedContacts.length === 0 ? (
        <EmptyState 
          hasFilters={searchQuery !== '' || activeFiltersCount > 0} 
          onAddContact={() => setIsFormOpen(true)} 
        />
      ) : viewMode === 'grid' ? (
        /* Grid View */
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
          <AnimatePresence mode="popLayout">
            {paginatedContacts.map((contact) => (
              <ContactCard
                key={contact.id}
                contact={contact}
                isSelected={selectedContacts.includes(contact.id)}
                onSelect={() => toggleContact(contact.id)}
                onEdit={() => handleEdit(contact)}
                onDelete={() => setDeletingContactId(contact.id)}
                onStatusChange={(status) => updateContact({ id: contact.id, status, previousData: contact })}
              />
            ))}
          </AnimatePresence>
        </div>
      ) : (
        /* Table View */
        <div className="rounded-xl border border-border overflow-hidden bg-card shadow-sm">
          <Table>
            <TableHeader>
              <TableRow className="bg-muted/50 hover:bg-muted/50">
                <TableHead className="w-12">
                  <Checkbox
                    checked={selectedContacts.length === paginatedContacts.length && paginatedContacts.length > 0}
                    onCheckedChange={toggleAll}
                  />
                </TableHead>
                <TableHead>
                  <button 
                    onClick={() => handleSort('name')} 
                    className="flex items-center gap-1.5 hover:text-foreground transition-colors font-semibold"
                  >
                    Contact
                    <SortIcon field="name" />
                  </button>
                </TableHead>
                <TableHead>
                  <button 
                    onClick={() => handleSort('email')} 
                    className="flex items-center gap-1.5 hover:text-foreground transition-colors font-semibold"
                  >
                    Email
                    <SortIcon field="email" />
                  </button>
                </TableHead>
                <TableHead>
                  <button 
                    onClick={() => handleSort('company')} 
                    className="flex items-center gap-1.5 hover:text-foreground transition-colors font-semibold"
                  >
                    Company
                    <SortIcon field="company" />
                  </button>
                </TableHead>
                <TableHead>
                  <button 
                    onClick={() => handleSort('status')} 
                    className="flex items-center gap-1.5 hover:text-foreground transition-colors font-semibold"
                  >
                    Status
                    <SortIcon field="status" />
                  </button>
                </TableHead>
                <TableHead className="font-semibold">Tags</TableHead>
                <TableHead>
                  <button 
                    onClick={() => handleSort('created_at')} 
                    className="flex items-center gap-1.5 hover:text-foreground transition-colors font-semibold"
                  >
                    Created
                    <SortIcon field="created_at" />
                  </button>
                </TableHead>
                <TableHead className="w-12" />
              </TableRow>
            </TableHeader>
            <TableBody>
              {paginatedContacts.map((contact, index) => (
                <motion.tr
                  key={contact.id}
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                  transition={{ delay: index * 0.02 }}
                  className={cn(
                    "group border-b border-border last:border-0 transition-colors",
                    selectedContacts.includes(contact.id) 
                      ? "bg-primary/5 hover:bg-primary/10" 
                      : "hover:bg-accent/50"
                  )}
                >
                  <TableCell>
                    <Checkbox
                      checked={selectedContacts.includes(contact.id)}
                      onCheckedChange={() => toggleContact(contact.id)}
                    />
                  </TableCell>
                  <TableCell>
                    <Link to={`/contacts/${contact.id}`} className="flex items-center gap-3 group/link">
                      <div className="relative">
                        <Avatar className="h-10 w-10 ring-2 ring-transparent group-hover/link:ring-primary/20 transition-all">
                          {contact.avatar_url && <AvatarImage src={contact.avatar_url} alt={contact.first_name} />}
                          <AvatarFallback className="bg-gradient-to-br from-primary/20 to-purple-500/20 text-primary text-sm font-semibold">
                            {getInitials(contact.first_name, contact.last_name)}
                          </AvatarFallback>
                        </Avatar>
                      </div>
                      <div>
                        <span className="font-medium group-hover/link:text-primary transition-colors">
                          {contact.first_name} {contact.last_name}
                        </span>
                        {contact.phone && (
                          <div className="flex items-center gap-1 text-xs text-muted-foreground">
                            <Phone className="h-3 w-3" />
                            {contact.phone}
                          </div>
                        )}
                      </div>
                    </Link>
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center gap-2">
                      <div className="flex items-center gap-1.5 text-sm text-muted-foreground">
                        <Mail className="h-3.5 w-3.5" />
                        <span className="max-w-[200px] truncate">{contact.email}</span>
                      </div>
                      <TooltipProvider>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <Button
                              variant="ghost"
                              size="icon"
                              className="h-6 w-6 opacity-0 group-hover:opacity-100 transition-opacity"
                              onClick={() => {
                                navigator.clipboard.writeText(contact.email);
                                toast.success('Email copied!');
                              }}
                            >
                              <Copy className="h-3 w-3" />
                            </Button>
                          </TooltipTrigger>
                          <TooltipContent>Copy email</TooltipContent>
                        </Tooltip>
                      </TooltipProvider>
                    </div>
                  </TableCell>
                  <TableCell>
                    {contact.company && (
                      <div className="flex items-center gap-1.5 text-sm">
                        <Building2 className="h-3.5 w-3.5 text-muted-foreground" />
                        <span className="max-w-[150px] truncate">{contact.company}</span>
                      </div>
                    )}
                  </TableCell>
                  <TableCell>
                    <StatusBadge status={contact.status} />
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center gap-1">
                      {contact.tags.slice(0, 2).map((tag) => (
                        <span
                          key={tag.id}
                          className="inline-flex h-5 items-center rounded-full px-2 text-xs font-medium whitespace-nowrap"
                          style={{ backgroundColor: `${tag.color}20`, color: tag.color }}
                        >
                          {tag.name}
                        </span>
                      ))}
                      {contact.tags.length > 2 && (
                        <TooltipProvider>
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <span className="text-xs text-muted-foreground cursor-help">
                                +{contact.tags.length - 2}
                              </span>
                            </TooltipTrigger>
                            <TooltipContent>
                              {contact.tags.slice(2).map(t => t.name).join(', ')}
                            </TooltipContent>
                          </Tooltip>
                        </TooltipProvider>
                      )}
                    </div>
                  </TableCell>
                  <TableCell className="text-sm text-muted-foreground">
                    {formatDate(contact.created_at)}
                  </TableCell>
                  <TableCell>
                    <DropdownMenu>
                      <DropdownMenuTrigger asChild>
                        <Button 
                          variant="ghost" 
                          size="icon" 
                          className="h-8 w-8 opacity-0 group-hover:opacity-100 transition-opacity"
                        >
                          <MoreHorizontal className="h-4 w-4" />
                        </Button>
                      </DropdownMenuTrigger>
                      <DropdownMenuContent align="end" className="w-48">
                        <DropdownMenuItem onClick={() => navigate(`/contacts/${contact.id}`)}>
                          <Eye className="h-4 w-4 mr-2" />
                          View Details
                        </DropdownMenuItem>
                        <DropdownMenuItem onClick={() => handleEdit(contact)}>
                          <Pencil className="h-4 w-4 mr-2" />
                          Edit
                        </DropdownMenuItem>
                        <DropdownMenuSub>
                          <DropdownMenuSubTrigger>
                            <RefreshCcw className="h-4 w-4 mr-2" />
                            Change Status
                          </DropdownMenuSubTrigger>
                          <DropdownMenuSubContent>
                            {STATUS_OPTIONS.map(s => (
                              <DropdownMenuItem 
                                key={s} 
                                onClick={() => updateContact({ id: contact.id, status: s, previousData: contact })}
                                className="capitalize"
                              >
                                {contact.status === s && <Check className="h-4 w-4 mr-2" />}
                                {s}
                              </DropdownMenuItem>
                            ))}
                          </DropdownMenuSubContent>
                        </DropdownMenuSub>
                        <DropdownMenuSeparator />
                        <DropdownMenuItem 
                          className="text-destructive focus:text-destructive"
                          onClick={() => setDeletingContactId(contact.id)}
                        >
                          <Trash2 className="h-4 w-4 mr-2" />
                          Delete
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </TableCell>
                </motion.tr>
              ))}
            </TableBody>
          </Table>
        </div>
      )}

      {/* Pagination */}
      {filteredContacts.length > 0 && (
        <div className="flex items-center justify-between flex-wrap gap-4 pt-2">
          <div className="flex items-center gap-2 text-sm text-muted-foreground">
            <span>Show</span>
            <Select 
              value={pageSize.toString()} 
              onValueChange={(v) => { setPageSize(Number(v)); setCurrentPage(1); }}
            >
              <SelectTrigger className="w-20 h-8">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {[10, 20, 50, 100].map(size => (
                  <SelectItem key={size} value={size.toString()}>{size}</SelectItem>
                ))}
              </SelectContent>
            </Select>
            <span>per page</span>
          </div>
          
          <div className="flex items-center gap-3">
            <span className="text-sm text-muted-foreground">
              {((currentPage - 1) * pageSize) + 1} - {Math.min(currentPage * pageSize, filteredContacts.length)} of {filteredContacts.length}
            </span>
            
            <div className="flex items-center gap-1">
              <Button
                variant="outline"
                size="icon"
                className="h-8 w-8"
                onClick={() => setCurrentPage(1)}
                disabled={currentPage === 1}
              >
                <ChevronLeft className="h-4 w-4" />
                <ChevronLeft className="h-4 w-4 -ml-2" />
              </Button>
              <Button
                variant="outline"
                size="icon"
                className="h-8 w-8"
                onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
                disabled={currentPage === 1}
              >
                <ChevronLeft className="h-4 w-4" />
              </Button>
              
              {/* Page numbers */}
              <div className="flex items-center gap-1 mx-1">
                {getPageNumbers().map((page, idx) => (
                  page === 'ellipsis' ? (
                    <span key={`ellipsis-${idx}`} className="px-2 text-muted-foreground">...</span>
                  ) : (
                    <Button
                      key={page}
                      variant={currentPage === page ? 'default' : 'ghost'}
                      size="icon"
                      className={cn(
                        "h-8 w-8",
                        currentPage === page && "pointer-events-none"
                      )}
                      onClick={() => setCurrentPage(page)}
                    >
                      {page}
                    </Button>
                  )
                ))}
              </div>
              
              <Button
                variant="outline"
                size="icon"
                className="h-8 w-8"
                onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
                disabled={currentPage === totalPages}
              >
                <ChevronRight className="h-4 w-4" />
              </Button>
              <Button
                variant="outline"
                size="icon"
                className="h-8 w-8"
                onClick={() => setCurrentPage(totalPages)}
                disabled={currentPage === totalPages}
              >
                <ChevronRight className="h-4 w-4" />
                <ChevronRight className="h-4 w-4 -ml-2" />
              </Button>
            </div>
          </div>
        </div>
      )}

      {/* Filter Sheet */}
      <Sheet open={isFiltersOpen} onOpenChange={setIsFiltersOpen}>
        <SheetContent side="right" className="w-80">
          <SheetHeader>
            <SheetTitle className="flex items-center gap-2">
              <Filter className="h-5 w-5" />
              Filters
            </SheetTitle>
            <SheetDescription>
              Narrow down your contact list
            </SheetDescription>
          </SheetHeader>
          
          <div className="mt-6 space-y-6">
            <div className="space-y-3">
              <Label className="text-sm font-medium">Status</Label>
              <div className="grid grid-cols-2 gap-2">
                <Button
                  variant={statusFilter === 'all' ? 'secondary' : 'outline'}
                  size="sm"
                  onClick={() => { setStatusFilter('all'); handleFilterChange(); }}
                  className="justify-start"
                >
                  <Users className="h-4 w-4 mr-2" />
                  All
                </Button>
                {STATUS_OPTIONS.map(s => {
                  const config = statusConfig[s];
                  const Icon = config.icon;
                  return (
                    <Button
                      key={s}
                      variant={statusFilter === s ? 'secondary' : 'outline'}
                      size="sm"
                      onClick={() => { setStatusFilter(s); handleFilterChange(); }}
                      className="justify-start capitalize"
                    >
                      <Icon className={cn("h-4 w-4 mr-2", config.text)} />
                      {s}
                    </Button>
                  );
                })}
              </div>
            </div>
            
            <div className="space-y-3">
              <Label className="text-sm font-medium">Tag</Label>
              <Select value={tagFilter} onValueChange={(v) => { setTagFilter(v); handleFilterChange(); }}>
                <SelectTrigger>
                  <SelectValue placeholder="Select a tag" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All tags</SelectItem>
                  {tags.map(t => (
                    <SelectItem key={t.id} value={t.id}>
                      <div className="flex items-center gap-2">
                        <span className="h-2 w-2 rounded-full" style={{ backgroundColor: t.color }} />
                        {t.name}
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            
            {sources.length > 0 && (
              <div className="space-y-3">
                <Label className="text-sm font-medium">Source</Label>
                <Select value={sourceFilter} onValueChange={(v) => { setSourceFilter(v); handleFilterChange(); }}>
                  <SelectTrigger>
                    <SelectValue placeholder="Select a source" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">All sources</SelectItem>
                    {sources.map(s => (
                      <SelectItem key={s} value={s}>{s}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            )}

            {activeFiltersCount > 0 && (
              <Button variant="outline" className="w-full" onClick={clearFilters}>
                <X className="h-4 w-4 mr-2" />
                Clear all filters
              </Button>
            )}
          </div>
        </SheetContent>
      </Sheet>

      {/* Dialogs */}
      <ContactFormDialog
        open={isFormOpen}
        onOpenChange={handleFormClose}
        contact={editingContact}
        onSubmit={handleFormSubmit}
        isSubmitting={isCreating || isUpdating}
      />

      {/* Delete Confirmation */}
      <AlertDialog open={!!deletingContactId} onOpenChange={() => setDeletingContactId(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle className="flex items-center gap-2">
              <div className="p-2 rounded-full bg-destructive/10">
                <Trash2 className="h-5 w-5 text-destructive" />
              </div>
              Move to Trash
            </AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to move this contact to trash? You can restore them from the trash later.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDelete}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
              disabled={isSoftDeleting}
            >
              {isSoftDeleting ? (
                <>
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  Moving...
                </>
              ) : (
                'Move to Trash'
              )}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* Bulk Delete Confirmation */}
      <AlertDialog open={isBulkDeleteOpen} onOpenChange={setIsBulkDeleteOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle className="flex items-center gap-2">
              <div className="p-2 rounded-full bg-destructive/10">
                <Trash2 className="h-5 w-5 text-destructive" />
              </div>
              Delete {selectedContacts.length} contacts
            </AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to move {selectedContacts.length} contacts to trash? You can restore them later.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleBulkDelete}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              Move to Trash
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* Import Dialog */}
      <Dialog open={isImportOpen} onOpenChange={setIsImportOpen}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <div className="p-2 rounded-full bg-primary/10">
                <Upload className="h-5 w-5 text-primary" />
              </div>
              Import Contacts
            </DialogTitle>
            <DialogDescription>
              Paste CSV or JSON data below. Required fields: first_name, last_name, email.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="rounded-lg bg-muted/50 p-4 space-y-2 text-sm">
              <p className="font-medium">Supported formats:</p>
              <p className="text-muted-foreground font-mono text-xs">
                <strong>CSV:</strong> first_name,last_name,email,phone,company,status,source
              </p>
              <p className="text-muted-foreground font-mono text-xs">
                <strong>JSON:</strong> Array of objects with the same fields
              </p>
            </div>
            <textarea
              className="w-full h-64 p-4 text-sm font-mono border rounded-lg bg-background resize-none focus:outline-none focus:ring-2 focus:ring-primary"
              placeholder={'first_name,last_name,email,phone,company,status,source\nJohn,Doe,john@example.com,555-1234,Acme Inc,lead,Website'}
              value={importData}
              onChange={(e) => setImportData(e.target.value)}
            />
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setIsImportOpen(false)}>
              Cancel
            </Button>
            <Button 
              onClick={handleImport} 
              disabled={!importData.trim() || isCreating}
              className="gap-2"
            >
              {isCreating ? (
                <>
                  <Loader2 className="h-4 w-4 animate-spin" />
                  Importing...
                </>
              ) : (
                <>
                  <Upload className="h-4 w-4" />
                  Import Contacts
                </>
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}