import React, { useState, useMemo } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import {
    Plus, Search, Building2, MoreHorizontal, Edit, Trash2, Eye, Home,
    MapPin, Bed, Bath, Square, DollarSign, User, Calendar, Filter,
    LayoutGrid, List, ChevronLeft, ChevronRight, X, AlertTriangle,
    CheckCircle2, Clock, TrendingUp, ArrowUpDown, ArrowUp, ArrowDown,
    Copy, ExternalLink, Shield, Sparkles, Tag, SlidersHorizontal,
    Download, Upload, RefreshCw, Heart, Share2, Key, FileText,
    Loader2, ImageIcon, PoundSterling
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { addDays, isBefore, isAfter, format, formatDistanceToNow } from 'date-fns';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { Progress } from '@/components/ui/progress';
import { Separator } from '@/components/ui/separator';
import { Checkbox } from '@/components/ui/checkbox';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import {
    Sheet,
    SheetContent,
    SheetDescription,
    SheetHeader,
    SheetTitle,
} from '@/components/ui/sheet';
import { Label } from '@/components/ui/label';
import { useProperties, useDeleteProperty, Property } from '@/hooks/useProperties';
import { PropertyFormDialog } from '@/components/properties/PropertyFormDialog';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';

type ViewMode = 'grid' | 'table';
type SortField = 'created_at' | 'price' | 'address' | 'status' | 'bedrooms';
type SortDirection = 'asc' | 'desc';

// Status configuration with refined colors
const statusConfig = {
    available: {
        label: 'Available',
        color: 'bg-emerald-500',
        bgLight: 'bg-emerald-50 dark:bg-emerald-500/10',
        text: 'text-emerald-700 dark:text-emerald-400',
        border: 'border-emerald-200 dark:border-emerald-500/20',
        icon: CheckCircle2,
        gradient: 'from-emerald-500 to-green-600',
    },
    let: {
        label: 'Let',
        color: 'bg-blue-500',
        bgLight: 'bg-blue-50 dark:bg-blue-500/10',
        text: 'text-blue-700 dark:text-blue-400',
        border: 'border-blue-200 dark:border-blue-500/20',
        icon: Key,
        gradient: 'from-blue-500 to-cyan-500',
    },
    under_offer: {
        label: 'Under Offer',
        color: 'bg-amber-500',
        bgLight: 'bg-amber-50 dark:bg-amber-500/10',
        text: 'text-amber-700 dark:text-amber-400',
        border: 'border-amber-200 dark:border-amber-500/20',
        icon: Clock,
        gradient: 'from-amber-500 to-orange-500',
    },
    sold: {
        label: 'Sold',
        color: 'bg-violet-500',
        bgLight: 'bg-violet-50 dark:bg-violet-500/10',
        text: 'text-violet-700 dark:text-violet-400',
        border: 'border-violet-200 dark:border-violet-500/20',
        icon: Sparkles,
        gradient: 'from-violet-500 to-purple-500',
    },
};

// Elegant Stats Card Component
function StatsCard({
    title,
    value,
    icon: Icon,
    color,
    trend,
    onClick,
    isActive,
}: {
    title: string;
    value: number;
    icon: any;
    color: string;
    trend?: number;
    onClick?: () => void;
    isActive?: boolean;
}) {
    return (
        <motion.div
            whileHover={{ y: -2 }}
            whileTap={{ scale: 0.98 }}
            transition={{ type: "spring", stiffness: 400, damping: 17 }}
        >
            <Card
                className={cn(
                    'cursor-pointer transition-all duration-300 overflow-hidden relative group',
                    isActive
                        ? 'ring-2 ring-primary ring-offset-2 shadow-lg'
                        : 'hover:shadow-md border-border/50'
                )}
                onClick={onClick}
            >
                <CardContent className="p-5">
                    <div className="flex items-center justify-between">
                        <div className="space-y-1.5">
                            <p className="text-xs font-medium text-muted-foreground/80 uppercase tracking-wider">
                                {title}
                            </p>
                            <p className="text-3xl font-semibold tracking-tight">{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.5 rounded-2xl transition-transform group-hover:scale-110',
                            color
                        )}>
                            <Icon className="h-5 w-5 text-white" />
                        </div>
                    </div>
                </CardContent>
                {isActive && (
                    <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-primary" />
                )}
            </Card>
        </motion.div>
    );
}

// Refined Property Image Component
function PropertyImage({
    src,
    alt,
    className
}: {
    src?: string | null;
    alt: string;
    className?: string;
}) {
    const [hasError, setHasError] = useState(false);
    const [isLoading, setIsLoading] = useState(true);

    if (!src || hasError) {
        return (
            <div className={cn(
                "flex items-center justify-center bg-gradient-to-br from-slate-100 to-slate-50 dark:from-slate-800 dark:to-slate-900",
                className
            )}>
                <Building2 className="h-6 w-6 text-slate-300 dark:text-slate-600" />
            </div>
        );
    }

    return (
        <div className={cn("relative overflow-hidden bg-slate-100 dark:bg-slate-800", className)}>
            {isLoading && (
                <div className="absolute inset-0 flex items-center justify-center">
                    <Loader2 className="h-4 w-4 animate-spin text-muted-foreground/50" />
                </div>
            )}
            <img
                src={src}
                alt={alt}
                className={cn(
                    "w-full h-full object-cover transition-all duration-700",
                    isLoading ? "opacity-0 scale-105" : "opacity-100 scale-100"
                )}
                onLoad={() => setIsLoading(false)}
                onError={() => {
                    setHasError(true);
                    setIsLoading(false);
                }}
            />
        </div>
    );
}

// Elegant Property Card for Grid View
function PropertyCard({
    property,
    isSelected,
    onSelect,
    onEdit,
    onDelete,
}: {
    property: Property;
    isSelected: boolean;
    onSelect: () => void;
    onEdit: () => void;
    onDelete: () => void;
}) {
    const navigate = useNavigate();
    const status = statusConfig[property.status as keyof typeof statusConfig] || statusConfig.available;
    const StatusIcon = status.icon;

    const hasComplianceIssues = useMemo(() => {
        const now = new Date();
        const complianceDates = [
            property.gas_certificate_expiry,
            property.electricity_certificate_expiry,
            property.epc_expiry,
        ].filter(Boolean);
        return complianceDates.some((d) => d && isBefore(new Date(d), now));
    }, [property]);

    return (
        <motion.div
            layout
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -20 }}
            whileHover={{ y: -6 }}
            transition={{ type: "spring", stiffness: 300, damping: 25 }}
            className="group"
        >
            <Card className={cn(
                "overflow-hidden bg-card border border-border/50 shadow-sm hover:shadow-xl transition-all duration-500",
                isSelected && "ring-2 ring-primary ring-offset-2"
            )}>
                {/* Property Image */}
                <div className="relative aspect-[4/3] overflow-hidden">
                    <PropertyImage
                        src={property.primary_image_url}
                        alt={property.display_address || 'Property'}
                        className="h-full w-full group-hover:scale-105 transition-transform duration-700"
                    />

                    {/* Elegant overlay gradient */}
                    <div className="absolute inset-0 bg-gradient-to-t from-black/50 via-black/0 to-black/0 opacity-0 group-hover:opacity-100 transition-all duration-500" />

                    {/* Checkbox - top left */}
                    <div className="absolute top-3 left-3 z-10">
                        <div className={cn(
                            "p-0.5 rounded-md transition-all",
                            isSelected ? "bg-primary" : "bg-white/90 dark:bg-black/50 backdrop-blur-sm"
                        )}>
                            <Checkbox
                                checked={isSelected}
                                onCheckedChange={onSelect}
                                className={cn(
                                    "border-0",
                                    isSelected && "bg-primary text-primary-foreground"
                                )}
                            />
                        </div>
                    </div>

                    {/* Status Badge - top right */}
                    <div className="absolute top-3 right-3">
                        <Badge
                            className={cn(
                                'gap-1.5 font-medium shadow-lg backdrop-blur-sm border',
                                status.bgLight,
                                status.text,
                                status.border
                            )}
                        >
                            <StatusIcon className="h-3 w-3" />
                            {status.label}
                        </Badge>
                    </div>

                    {/* Compliance Warning */}
                    {hasComplianceIssues && (
                        <div className="absolute bottom-3 left-3">
                            <TooltipProvider>
                                <Tooltip>
                                    <TooltipTrigger asChild>
                                        <div className="p-2 rounded-full bg-red-500 shadow-lg animate-pulse">
                                            <AlertTriangle className="h-3.5 w-3.5 text-white" />
                                        </div>
                                    </TooltipTrigger>
                                    <TooltipContent side="right">Compliance issues detected</TooltipContent>
                                </Tooltip>
                            </TooltipProvider>
                        </div>
                    )}

                    {/* Quick Actions - bottom right */}
                    <div className="absolute bottom-3 right-3 flex items-center gap-2 opacity-0 translate-y-2 group-hover:opacity-100 group-hover:translate-y-0 transition-all duration-300">
                        <TooltipProvider>
                            <Tooltip>
                                <TooltipTrigger asChild>
                                    <Button
                                        variant="secondary"
                                        size="icon"
                                        className="h-8 w-8 shadow-lg bg-white/95 dark:bg-slate-900/95 backdrop-blur-sm hover:bg-white dark:hover:bg-slate-900"
                                        onClick={(e) => {
                                            e.stopPropagation();
                                            navigator.clipboard.writeText(window.location.origin + `/properties/${property.id}`);
                                            toast.success('Link copied to clipboard');
                                        }}
                                    >
                                        <Share2 className="h-4 w-4" />
                                    </Button>
                                </TooltipTrigger>
                                <TooltipContent>Share property</TooltipContent>
                            </Tooltip>
                        </TooltipProvider>
                    </div>
                </div>

                {/* Property Details */}
                <CardContent className="p-5">
                    <div className="space-y-4">
                        {/* Price */}
                        <div className="flex items-baseline gap-1">
                            {property.price ? (
                                <>
                                    <span className="text-2xl font-bold tracking-tight">
                                        £{property.price.toLocaleString()}
                                    </span>
                                    <span className="text-sm text-muted-foreground font-medium">/month</span>
                                </>
                            ) : (
                                <span className="text-lg text-muted-foreground">Price on request</span>
                            )}
                        </div>

                        {/* Title & Address - Fully visible */}
                        <div className="space-y-1.5">
                            <Link
                                to={`/properties/${property.id}`}
                                className="block group/title"
                            >
                                <h3 className="font-semibold text-base leading-snug group-hover/title:text-primary transition-colors">
                                    {property.headline || property.display_address || 'Unnamed Property'}
                                </h3>
                            </Link>
                            <div className="flex items-start gap-1.5 text-sm text-muted-foreground">
                                <MapPin className="h-3.5 w-3.5 mt-0.5 flex-shrink-0" />
                                <span className="leading-snug">
                                    {[property.display_address, property.town_city, property.postcode]
                                        .filter(Boolean)
                                        .join(', ') || 'No location specified'}
                                </span>
                            </div>
                        </div>

                        {/* Property Features */}
                        <div className="flex items-center gap-4 py-3 border-y border-border/50">
                            {property.number_of_bedrooms !== null && (
                                <div className="flex items-center gap-1.5 text-sm">
                                    <Bed className="h-4 w-4 text-muted-foreground" />
                                    <span className="font-medium">{property.number_of_bedrooms}</span>
                                    <span className="text-muted-foreground text-xs">beds</span>
                                </div>
                            )}
                            {property.number_of_bathrooms !== null && (
                                <div className="flex items-center gap-1.5 text-sm">
                                    <Bath className="h-4 w-4 text-muted-foreground" />
                                    <span className="font-medium">{property.number_of_bathrooms}</span>
                                    <span className="text-muted-foreground text-xs">baths</span>
                                </div>
                            )}
                            {property.property_type && (
                                <div className="flex items-center gap-1.5 text-sm ml-auto">
                                    <Building2 className="h-4 w-4 text-muted-foreground" />
                                    <span className="text-muted-foreground">{property.property_type}</span>
                                </div>
                            )}
                        </div>

                        {/* Landlord & Actions */}
                        <div className="flex items-center justify-between">
                            {property.landlord ? (
                                <Link
                                    to={`/contacts/${property.landlord.id}`}
                                    className="flex items-center gap-2.5 group/landlord min-w-0"
                                    onClick={(e) => e.stopPropagation()}
                                >
                                    <Avatar className="h-8 w-8 ring-2 ring-background shadow-sm">
                                        <AvatarFallback className="text-xs font-medium bg-gradient-to-br from-primary/20 to-primary/10 text-primary">
                                            {property.landlord.first_name[0]}
                                            {property.landlord.last_name[0]}
                                        </AvatarFallback>
                                    </Avatar>
                                    <span className="text-sm text-muted-foreground group-hover/landlord:text-foreground transition-colors truncate">
                                        {property.landlord.first_name} {property.landlord.last_name}
                                    </span>
                                </Link>
                            ) : (
                                <span className="text-sm text-muted-foreground/60">No landlord assigned</span>
                            )}

                            <DropdownMenu>
                                <DropdownMenuTrigger asChild>
                                    <Button variant="ghost" size="icon" className="h-8 w-8 -mr-2">
                                        <MoreHorizontal className="h-4 w-4" />
                                    </Button>
                                </DropdownMenuTrigger>
                                <DropdownMenuContent align="end" className="w-48">
                                    <DropdownMenuItem asChild>
                                        <Link to={`/properties/${property.id}`}>
                                            <Eye className="mr-2 h-4 w-4" />
                                            View Details
                                        </Link>
                                    </DropdownMenuItem>
                                    <DropdownMenuItem onClick={onEdit}>
                                        <Edit className="mr-2 h-4 w-4" />
                                        Edit Property
                                    </DropdownMenuItem>
                                    <DropdownMenuItem
                                        onClick={() => {
                                            navigator.clipboard.writeText(window.location.origin + `/properties/${property.id}`);
                                            toast.success('Link copied!');
                                        }}
                                    >
                                        <Copy className="mr-2 h-4 w-4" />
                                        Copy Link
                                    </DropdownMenuItem>
                                    <DropdownMenuSeparator />
                                    <DropdownMenuItem onClick={onDelete} className="text-destructive focus:text-destructive">
                                        <Trash2 className="mr-2 h-4 w-4" />
                                        Delete
                                    </DropdownMenuItem>
                                </DropdownMenuContent>
                            </DropdownMenu>
                        </div>
                    </div>
                </CardContent>
            </Card>
        </motion.div>
    );
}

// Empty State Component
function EmptyState({ hasFilters, onAddProperty }: { hasFilters: boolean; onAddProperty: () => void }) {
    return (
        <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            className="flex flex-col items-center justify-center py-20 px-4"
        >
            <div className="relative mb-8">
                <div className="absolute inset-0 bg-gradient-to-r from-primary/20 to-violet-500/20 rounded-full blur-3xl opacity-50" />
                <div className="relative bg-gradient-to-br from-primary/5 to-violet-500/5 rounded-full p-8 border border-border/50">
                    <Building2 className="h-12 w-12 text-primary/60" />
                </div>
            </div>
            <h3 className="text-xl font-semibold mb-2">
                {hasFilters ? 'No properties match your filters' : 'No properties yet'}
            </h3>
            <p className="text-muted-foreground text-center max-w-md mb-8">
                {hasFilters
                    ? "Try adjusting your filters or search terms to find what you're looking for."
                    : 'Get started by adding your first property to your portfolio.'}
            </p>
            {!hasFilters && (
                <Button onClick={onAddProperty} size="lg" className="gap-2">
                    <Plus className="h-4 w-4" />
                    Add Your First Property
                </Button>
            )}
        </motion.div>
    );
}

export default function Properties() {
    const navigate = useNavigate();
    const { data: properties = [], isLoading } = useProperties();
    const deleteProperty = useDeleteProperty();

    // View Mode - Default to table/list
    const [viewMode, setViewMode] = useState<ViewMode>('table');

    // Search & Filters
    const [search, setSearch] = useState('');
    const [sortField, setSortField] = useState<SortField>('created_at');
    const [sortDirection, setSortDirection] = useState<SortDirection>('desc');
    const [isFiltersOpen, setIsFiltersOpen] = useState(false);

    // Selection
    const [selectedProperties, setSelectedProperties] = useState<string[]>([]);

    // Pagination
    const [perPage, setPerPage] = useState(20);
    const [currentPage, setCurrentPage] = useState(1);

    // Dialogs
    const [formOpen, setFormOpen] = useState(false);
    const [editingProperty, setEditingProperty] = useState<string | null>(null);
    const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
    const [propertyToDelete, setPropertyToDelete] = useState<string | null>(null);
    const [isBulkDeleteOpen, setIsBulkDeleteOpen] = useState(false);

    // Filters
    const [filters, setFilters] = useState({
        status: 'all',
        landlordId: 'all',
        minBedrooms: '',
        maxBedrooms: '',
        minPrice: '',
        maxPrice: '',
        complianceExpiring: 'all',
        propertyType: 'all',
    });

    // Stats
    const stats = useMemo(() => {
        const total = properties.length;
        const available = properties.filter((p) => p.status === 'available').length;
        const letProperties = properties.filter((p) => p.status === 'let').length;
        const underOffer = properties.filter((p) => p.status === 'under_offer').length;
        const sold = properties.filter((p) => p.status === 'sold').length;

        return { total, available, let: letProperties, underOffer, sold };
    }, [properties]);

    // Get unique landlords for filter dropdown
    const landlords = useMemo(() => {
        const uniqueLandlords = new Map<string, { id: string; first_name: string; last_name: string }>();
        properties.forEach((p) => {
            if (p.landlord) {
                uniqueLandlords.set(p.landlord.id, {
                    id: p.landlord.id,
                    first_name: p.landlord.first_name,
                    last_name: p.landlord.last_name,
                });
            }
        });
        return Array.from(uniqueLandlords.values());
    }, [properties]);

    // Get unique property types
    const propertyTypes = useMemo(() => {
        const types = new Set(properties.map((p) => p.property_type).filter(Boolean));
        return Array.from(types) as string[];
    }, [properties]);

    // Check if any compliance dates are expiring
    const checkComplianceExpiry = (property: Property, days: string) => {
        const now = new Date();
        const complianceDates = [
            property.gas_certificate_expiry,
            property.electricity_certificate_expiry,
            property.epc_expiry,
            property.pat_test_expiry,
            property.insurance_expiry,
            property.smoke_co_alarm_expiry,
            property.property_licence_expiry,
        ].filter(Boolean);

        if (days === 'expired') {
            return complianceDates.some((d) => d && isBefore(new Date(d), now));
        }

        const daysNum = parseInt(days, 10);
        const futureDate = addDays(now, daysNum);

        return complianceDates.some((d) => {
            if (!d) return false;
            const date = new Date(d);
            return isAfter(date, now) && isBefore(date, futureDate);
        });
    };

    // Filter and sort properties
    const filteredProperties = useMemo(() => {
        return properties
            .filter((p) => {
                const matchesSearch =
                    !search ||
                    p.display_address?.toLowerCase().includes(search.toLowerCase()) ||
                    p.reference?.toLowerCase().includes(search.toLowerCase()) ||
                    p.headline?.toLowerCase().includes(search.toLowerCase()) ||
                    p.postcode?.toLowerCase().includes(search.toLowerCase()) ||
                    p.town_city?.toLowerCase().includes(search.toLowerCase());

                const matchesStatus = filters.status === 'all' || p.status === filters.status;
                const matchesLandlord = filters.landlordId === 'all' || p.landlord_id === filters.landlordId;
                const matchesPropertyType = filters.propertyType === 'all' || p.property_type === filters.propertyType;

                const minBeds = filters.minBedrooms ? parseInt(filters.minBedrooms, 10) : null;
                const maxBeds = filters.maxBedrooms ? parseInt(filters.maxBedrooms, 10) : null;
                const matchesBedrooms =
                    (minBeds === null || (p.number_of_bedrooms !== null && p.number_of_bedrooms >= minBeds)) &&
                    (maxBeds === null || (p.number_of_bedrooms !== null && p.number_of_bedrooms <= maxBeds));

                const minPrice = filters.minPrice ? parseFloat(filters.minPrice) : null;
                const maxPrice = filters.maxPrice ? parseFloat(filters.maxPrice) : null;
                const matchesPrice =
                    (minPrice === null || (p.price !== null && p.price >= minPrice)) &&
                    (maxPrice === null || (p.price !== null && p.price <= maxPrice));

                const matchesCompliance =
                    filters.complianceExpiring === 'all' || checkComplianceExpiry(p, filters.complianceExpiring);

                return (
                    matchesSearch &&
                    matchesStatus &&
                    matchesLandlord &&
                    matchesBedrooms &&
                    matchesPrice &&
                    matchesCompliance &&
                    matchesPropertyType
                );
            })
            .sort((a, b) => {
                let aVal: any, bVal: any;

                switch (sortField) {
                    case 'price':
                        aVal = a.price || 0;
                        bVal = b.price || 0;
                        break;
                    case 'address':
                        aVal = (a.display_address || '').toLowerCase();
                        bVal = (b.display_address || '').toLowerCase();
                        break;
                    case 'status':
                        aVal = a.status || '';
                        bVal = b.status || '';
                        break;
                    case 'bedrooms':
                        aVal = a.number_of_bedrooms || 0;
                        bVal = b.number_of_bedrooms || 0;
                        break;
                    default:
                        aVal = new Date(a.created_at).getTime();
                        bVal = new Date(b.created_at).getTime();
                }

                if (aVal < bVal) return sortDirection === 'asc' ? -1 : 1;
                if (aVal > bVal) return sortDirection === 'asc' ? 1 : -1;
                return 0;
            });
    }, [properties, search, filters, sortField, sortDirection]);

    // Pagination
    const totalPages = Math.ceil(filteredProperties.length / perPage);
    const paginatedProperties = filteredProperties.slice(
        (currentPage - 1) * perPage,
        currentPage * perPage
    );

    // Reset to page 1 when filters change
    React.useEffect(() => {
        setCurrentPage(1);
    }, [filters, search]);

    // Selection handlers
    const toggleProperty = (id: string) => {
        setSelectedProperties((prev) =>
            prev.includes(id) ? prev.filter((p) => p !== id) : [...prev, id]
        );
    };

    const toggleAll = () => {
        if (selectedProperties.length === paginatedProperties.length) {
            setSelectedProperties([]);
        } else {
            setSelectedProperties(paginatedProperties.map((p) => p.id));
        }
    };

    const handleDelete = (id: string) => {
        setPropertyToDelete(id);
        setDeleteDialogOpen(true);
    };

    const confirmDelete = async () => {
        if (propertyToDelete) {
            await deleteProperty.mutateAsync(propertyToDelete);
            setDeleteDialogOpen(false);
            setPropertyToDelete(null);
            toast.success('Property deleted successfully');
        }
    };

    const handleBulkDelete = async () => {
        for (const id of selectedProperties) {
            await deleteProperty.mutateAsync(id);
        }
        setSelectedProperties([]);
        setIsBulkDeleteOpen(false);
        toast.success(`${selectedProperties.length} properties deleted`);
    };

    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.5 w-3.5 opacity-40" />;
        return sortDirection === 'asc'
            ? <ArrowUp className="h-3.5 w-3.5 text-primary" />
            : <ArrowDown className="h-3.5 w-3.5 text-primary" />;
    };

    const clearFilters = () => {
        setFilters({
            status: 'all',
            landlordId: 'all',
            minBedrooms: '',
            maxBedrooms: '',
            minPrice: '',
            maxPrice: '',
            complianceExpiring: 'all',
            propertyType: 'all',
        });
        setSearch('');
    };

    const activeFiltersCount = [
        filters.status !== 'all',
        filters.landlordId !== 'all',
        filters.minBedrooms !== '',
        filters.maxBedrooms !== '',
        filters.minPrice !== '',
        filters.maxPrice !== '',
        filters.complianceExpiring !== 'all',
        filters.propertyType !== 'all',
    ].filter(Boolean).length;

    const getStatusBadgeClasses = (status: string | null) => {
        const config = statusConfig[status as keyof typeof statusConfig];
        return config ? cn(config.bgLight, config.text, config.border, 'border') : 'bg-muted text-muted-foreground';
    };

    // Generate page numbers
    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-[60vh]">
                <div className="text-center space-y-4">
                    <div className="relative">
                        <div className="absolute inset-0 bg-gradient-to-r from-primary/20 to-violet-500/20 rounded-full blur-3xl animate-pulse" />
                        <Loader2 className="h-10 w-10 animate-spin text-primary relative" />
                    </div>
                    <p className="text-sm text-muted-foreground">Loading properties...</p>
                </div>
            </div>
        );
    }

    return (
        <div className="p-6 lg:p-8 space-y-8 max-w-[1800px] mx-auto animate-fade-in">
            {/* Header */}
            <div className="flex items-start justify-between flex-wrap gap-4">
                <div className="space-y-1">
                    <h1 className="text-3xl font-bold tracking-tight">
                        Properties
                    </h1>
                    <p className="text-muted-foreground">
                        Manage and track your property portfolio
                    </p>
                </div>
                <div className="flex items-center gap-3">
                    <Button variant="outline" size="sm" className="gap-2 h-9">
                        <Upload className="h-4 w-4" />
                        <span className="hidden sm:inline">Import</span>
                    </Button>
                    <Button variant="outline" size="sm" className="gap-2 h-9">
                        <Download className="h-4 w-4" />
                        <span className="hidden sm:inline">Export</span>
                    </Button>
                    <Button
                        size="sm"
                        className="gap-2 h-9 shadow-md"
                        onClick={() => setFormOpen(true)}
                    >
                        <Plus className="h-4 w-4" />
                        Add Property
                    </Button>
                </div>
            </div>

            {/* Stats Cards */}
            <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
                <StatsCard
                    title="Total"
                    value={stats.total}
                    icon={Building2}
                    color="bg-gradient-to-br from-slate-600 to-slate-700"
                    onClick={() => setFilters((f) => ({ ...f, status: 'all' }))}
                    isActive={filters.status === 'all'}
                />
                <StatsCard
                    title="Available"
                    value={stats.available}
                    icon={CheckCircle2}
                    color="bg-gradient-to-br from-emerald-500 to-emerald-600"
                    onClick={() => setFilters((f) => ({ ...f, status: 'available' }))}
                    isActive={filters.status === 'available'}
                />
                <StatsCard
                    title="Let"
                    value={stats.let}
                    icon={Key}
                    color="bg-gradient-to-br from-blue-500 to-blue-600"
                    onClick={() => setFilters((f) => ({ ...f, status: 'let' }))}
                    isActive={filters.status === 'let'}
                />
                <StatsCard
                    title="Under Offer"
                    value={stats.underOffer}
                    icon={Clock}
                    color="bg-gradient-to-br from-amber-500 to-amber-600"
                    onClick={() => setFilters((f) => ({ ...f, status: 'under_offer' }))}
                    isActive={filters.status === 'under_offer'}
                />
                <StatsCard
                    title="Sold"
                    value={stats.sold}
                    icon={Sparkles}
                    color="bg-gradient-to-br from-violet-500 to-violet-600"
                    onClick={() => setFilters((f) => ({ ...f, status: 'sold' }))}
                    isActive={filters.status === 'sold'}
                />
            </div>

            {/* Search, Filters & View Toggle */}
            <div className="flex items-center gap-3 flex-wrap">
                <div className="relative flex-1 min-w-[240px] max-w-md">
                    <Search className="absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground/60" />
                    <Input
                        placeholder="Search properties..."
                        value={search}
                        onChange={(e) => setSearch(e.target.value)}
                        className="pl-10 h-10 bg-background border-border/50 focus-visible:border-primary"
                    />
                    {search && (
                        <Button
                            variant="ghost"
                            size="icon"
                            className="absolute right-1.5 top-1/2 -translate-y-1/2 h-7 w-7 hover:bg-muted"
                            onClick={() => setSearch('')}
                        >
                            <X className="h-3.5 w-3.5" />
                        </Button>
                    )}
                </div>

                {/* Sort */}
                <Select value={sortField} onValueChange={(v) => setSortField(v as SortField)}>
                    <SelectTrigger className="w-[150px] h-10 border-border/50">
                        <SelectValue placeholder="Sort by" />
                    </SelectTrigger>
                    <SelectContent>
                        <SelectItem value="created_at">Date Added</SelectItem>
                        <SelectItem value="price">Price</SelectItem>
                        <SelectItem value="address">Address</SelectItem>
                        <SelectItem value="status">Status</SelectItem>
                        <SelectItem value="bedrooms">Bedrooms</SelectItem>
                    </SelectContent>
                </Select>

                <TooltipProvider>
                    <Tooltip>
                        <TooltipTrigger asChild>
                            <Button
                                variant="outline"
                                size="icon"
                                className="h-10 w-10 border-border/50"
                                onClick={() => setSortDirection((d) => (d === 'asc' ? 'desc' : 'asc'))}
                            >
                                {sortDirection === 'asc' ? <ArrowUp className="h-4 w-4" /> : <ArrowDown className="h-4 w-4" />}
                            </Button>
                        </TooltipTrigger>
                        <TooltipContent>
                            {sortDirection === 'asc' ? 'Ascending' : 'Descending'}
                        </TooltipContent>
                    </Tooltip>
                </TooltipProvider>

                {/* Filter Button */}
                <Button
                    variant={activeFiltersCount > 0 ? 'default' : 'outline'}
                    className={cn(
                        "gap-2 h-10",
                        activeFiltersCount > 0
                            ? "bg-primary/10 text-primary hover:bg-primary/20 border-primary/20"
                            : "border-border/50"
                    )}
                    onClick={() => setIsFiltersOpen(true)}
                >
                    <SlidersHorizontal className="h-4 w-4" />
                    Filters
                    {activeFiltersCount > 0 && (
                        <Badge
                            className="ml-1 h-5 min-w-[20px] px-1.5 flex items-center justify-center rounded-full bg-primary text-primary-foreground text-xs"
                        >
                            {activeFiltersCount}
                        </Badge>
                    )}
                </Button>

                <div className="flex-1" />

                {/* View Toggle */}
                <div className="flex items-center border border-border/50 rounded-lg p-1 bg-muted/30">
                    <TooltipProvider>
                        <Tooltip>
                            <TooltipTrigger asChild>
                                <Button
                                    variant={viewMode === 'table' ? 'default' : 'ghost'}
                                    size="sm"
                                    className={cn(
                                        "h-8 px-3 rounded-md",
                                        viewMode === 'table' && "shadow-sm"
                                    )}
                                    onClick={() => setViewMode('table')}
                                >
                                    <List className="h-4 w-4" />
                                </Button>
                            </TooltipTrigger>
                            <TooltipContent>List View</TooltipContent>
                        </Tooltip>
                    </TooltipProvider>
                    <TooltipProvider>
                        <Tooltip>
                            <TooltipTrigger asChild>
                                <Button
                                    variant={viewMode === 'grid' ? 'default' : 'ghost'}
                                    size="sm"
                                    className={cn(
                                        "h-8 px-3 rounded-md",
                                        viewMode === 'grid' && "shadow-sm"
                                    )}
                                    onClick={() => setViewMode('grid')}
                                >
                                    <LayoutGrid className="h-4 w-4" />
                                </Button>
                            </TooltipTrigger>
                            <TooltipContent>Grid View</TooltipContent>
                        </Tooltip>
                    </TooltipProvider>
                </div>

                {/* Results count */}
                <div className="text-sm text-muted-foreground hidden lg:block">
                    {filteredProperties.length} {filteredProperties.length === 1 ? 'property' : 'properties'}
                </div>
            </div>

            {/* Bulk Actions */}
            <AnimatePresence>
                {selectedProperties.length > 0 && (
                    <motion.div
                        initial={{ opacity: 0, y: -10 }}
                        animate={{ opacity: 1, y: 0 }}
                        exit={{ opacity: 0, y: -10 }}
                        className="flex items-center gap-3 p-3 rounded-xl bg-primary/5 border border-primary/10"
                    >
                        <Badge variant="secondary" className="font-medium bg-primary/10 text-primary border-0">
                            {selectedProperties.length} selected
                        </Badge>

                        <Separator orientation="vertical" className="h-5" />

                        <Button
                            variant="ghost"
                            size="sm"
                            className="text-destructive hover:text-destructive hover:bg-destructive/10"
                            onClick={() => setIsBulkDeleteOpen(true)}
                        >
                            <Trash2 className="h-4 w-4 mr-1.5" />
                            Delete
                        </Button>

                        <div className="flex-1" />

                        <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => setSelectedProperties([])}
                            className="text-muted-foreground"
                        >
                            <X className="h-4 w-4 mr-1.5" />
                            Clear
                        </Button>
                    </motion.div>
                )}
            </AnimatePresence>

            {/* 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">Filters:</span>
                        {filters.status !== 'all' && (
                            <Badge variant="secondary" className="gap-1.5 pr-1.5 capitalize font-normal">
                                {filters.status.replace('_', ' ')}
                                <button
                                    className="ml-0.5 hover:bg-foreground/10 rounded-full p-0.5"
                                    onClick={() => setFilters((f) => ({ ...f, status: 'all' }))}
                                >
                                    <X className="h-3 w-3" />
                                </button>
                            </Badge>
                        )}
                        {filters.propertyType !== 'all' && (
                            <Badge variant="secondary" className="gap-1.5 pr-1.5 font-normal">
                                {filters.propertyType}
                                <button
                                    className="ml-0.5 hover:bg-foreground/10 rounded-full p-0.5"
                                    onClick={() => setFilters((f) => ({ ...f, propertyType: 'all' }))}
                                >
                                    <X className="h-3 w-3" />
                                </button>
                            </Badge>
                        )}
                        {filters.landlordId !== 'all' && (
                            <Badge variant="secondary" className="gap-1.5 pr-1.5 font-normal">
                                {landlords.find((l) => l.id === filters.landlordId)?.first_name} {landlords.find((l) => l.id === filters.landlordId)?.last_name}
                                <button
                                    className="ml-0.5 hover:bg-foreground/10 rounded-full p-0.5"
                                    onClick={() => setFilters((f) => ({ ...f, landlordId: 'all' }))}
                                >
                                    <X className="h-3 w-3" />
                                </button>
                            </Badge>
                        )}
                        {(filters.minBedrooms || filters.maxBedrooms) && (
                            <Badge variant="secondary" className="gap-1.5 pr-1.5 font-normal">
                                {filters.minBedrooms || '0'}-{filters.maxBedrooms || '∞'} beds
                                <button
                                    className="ml-0.5 hover:bg-foreground/10 rounded-full p-0.5"
                                    onClick={() => setFilters((f) => ({ ...f, minBedrooms: '', maxBedrooms: '' }))}
                                >
                                    <X className="h-3 w-3" />
                                </button>
                            </Badge>
                        )}
                        {(filters.minPrice || filters.maxPrice) && (
                            <Badge variant="secondary" className="gap-1.5 pr-1.5 font-normal">
                                £{filters.minPrice || '0'}-£{filters.maxPrice || '∞'}
                                <button
                                    className="ml-0.5 hover:bg-foreground/10 rounded-full p-0.5"
                                    onClick={() => setFilters((f) => ({ ...f, minPrice: '', maxPrice: '' }))}
                                >
                                    <X className="h-3 w-3" />
                                </button>
                            </Badge>
                        )}
                        {filters.complianceExpiring !== 'all' && (
                            <Badge variant="secondary" className="gap-1.5 pr-1.5 font-normal">
                                {filters.complianceExpiring === 'expired' ? 'Expired' : `${filters.complianceExpiring}d`}
                                <button
                                    className="ml-0.5 hover:bg-foreground/10 rounded-full p-0.5"
                                    onClick={() => setFilters((f) => ({ ...f, complianceExpiring: 'all' }))}
                                >
                                    <X className="h-3 w-3" />
                                </button>
                            </Badge>
                        )}
                        <Button variant="ghost" size="sm" onClick={clearFilters} className="text-xs h-6 px-2">
                            Clear all
                        </Button>
                    </motion.div>
                )}
            </AnimatePresence>

            {/* Content */}
            {paginatedProperties.length === 0 ? (
                <EmptyState
                    hasFilters={search !== '' || activeFiltersCount > 0}
                    onAddProperty={() => setFormOpen(true)}
                />
            ) : viewMode === 'grid' ? (
                /* Grid View */
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
                    <AnimatePresence mode="popLayout">
                        {paginatedProperties.map((property) => (
                            <PropertyCard
                                key={property.id}
                                property={property}
                                isSelected={selectedProperties.includes(property.id)}
                                onSelect={() => toggleProperty(property.id)}
                                onEdit={() => setEditingProperty(property.id)}
                                onDelete={() => handleDelete(property.id)}
                            />
                        ))}
                    </AnimatePresence>
                </div>
            ) : (
                /* Table View - Elegant Design */
                <Card className="border-border/50 shadow-sm overflow-hidden">
                    <div className="overflow-x-auto">
                        <Table>
                            <TableHeader>
                                <TableRow className="bg-muted/30 hover:bg-muted/30 border-border/50">
                                    <TableHead className="w-12 pl-4">
                                        <Checkbox
                                            checked={selectedProperties.length === paginatedProperties.length && paginatedProperties.length > 0}
                                            onCheckedChange={toggleAll}
                                        />
                                    </TableHead>
                                    <TableHead className="min-w-[400px]">
                                        <button
                                            onClick={() => handleSort('address')}
                                            className="flex items-center gap-2 hover:text-foreground transition-colors font-medium"
                                        >
                                            Property
                                            <SortIcon field="address" />
                                        </button>
                                    </TableHead>
                                    <TableHead className="w-[100px]">
                                        <button
                                            onClick={() => handleSort('bedrooms')}
                                            className="flex items-center gap-2 hover:text-foreground transition-colors font-medium"
                                        >
                                            Beds
                                            <SortIcon field="bedrooms" />
                                        </button>
                                    </TableHead>
                                    <TableHead className="w-[140px]">
                                        <button
                                            onClick={() => handleSort('price')}
                                            className="flex items-center gap-2 hover:text-foreground transition-colors font-medium"
                                        >
                                            Price
                                            <SortIcon field="price" />
                                        </button>
                                    </TableHead>
                                    <TableHead className="w-[130px]">
                                        <button
                                            onClick={() => handleSort('status')}
                                            className="flex items-center gap-2 hover:text-foreground transition-colors font-medium"
                                        >
                                            Status
                                            <SortIcon field="status" />
                                        </button>
                                    </TableHead>
                                    <TableHead className="w-[180px]">Landlord</TableHead>
                                    <TableHead className="w-[100px]">Compliance</TableHead>
                                    <TableHead className="w-[60px] pr-4" />
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {paginatedProperties.map((property, index) => {
                                    const hasComplianceIssues = checkComplianceExpiry(property, 'expired');
                                    const hasUpcomingCompliance = checkComplianceExpiry(property, '30');
                                    const isSelected = selectedProperties.includes(property.id);
                                    const status = statusConfig[property.status as keyof typeof statusConfig];
                                    const StatusIcon = status?.icon;

                                    return (
                                        <motion.tr
                                            key={property.id}
                                            initial={{ opacity: 0 }}
                                            animate={{ opacity: 1 }}
                                            transition={{ delay: index * 0.015 }}
                                            className={cn(
                                                "group border-b border-border/30 last:border-0 transition-colors",
                                                isSelected
                                                    ? "bg-primary/5 hover:bg-primary/8"
                                                    : "hover:bg-muted/50"
                                            )}
                                        >
                                            <TableCell className="pl-4">
                                                <Checkbox
                                                    checked={isSelected}
                                                    onCheckedChange={() => toggleProperty(property.id)}
                                                />
                                            </TableCell>
                                            <TableCell className="py-4">
                                                <Link
                                                    to={`/properties/${property.id}`}
                                                    className="flex items-start gap-4 group/link"
                                                >
                                                    {/* Property Image */}
                                                    <div className="h-20 w-28 rounded-lg overflow-hidden flex-shrink-0 ring-1 ring-border/50 shadow-sm">
                                                        <PropertyImage
                                                            src={property.primary_image_url}
                                                            alt={property.display_address || 'Property'}
                                                            className="h-full w-full group-hover/link:scale-105 transition-transform duration-500"
                                                        />
                                                    </div>
                                                    {/* Property Info - Full visibility */}
                                                    <div className="min-w-0 flex-1 py-0.5">
                                                        <div className="flex items-start gap-2 mb-1.5">
                                                            <h3 className="font-semibold text-[15px] leading-snug group-hover/link:text-primary transition-colors">
                                                                {property.headline || property.display_address || 'Unnamed Property'}
                                                            </h3>
                                                            {property.reference && (
                                                                <Badge
                                                                    variant="outline"
                                                                    className="font-mono text-[10px] px-1.5 py-0 h-5 flex-shrink-0 border-border/50 text-muted-foreground"
                                                                >
                                                                    {property.reference}
                                                                </Badge>
                                                            )}
                                                        </div>
                                                        <div className="flex items-start gap-1.5 text-sm text-muted-foreground">
                                                            <MapPin className="h-3.5 w-3.5 mt-0.5 flex-shrink-0" />
                                                            <span className="leading-relaxed">
                                                                {[property.display_address, property.town_city, property.postcode]
                                                                    .filter(Boolean)
                                                                    .join(', ') || 'No location specified'}
                                                            </span>
                                                        </div>
                                                        {property.property_type && (
                                                            <div className="flex items-center gap-1.5 mt-2 text-xs text-muted-foreground/70">
                                                                <Building2 className="h-3 w-3" />
                                                                {property.property_type}
                                                            </div>
                                                        )}
                                                    </div>
                                                </Link>
                                            </TableCell>
                                            <TableCell>
                                                <div className="flex items-center gap-1.5">
                                                    <Bed className="h-4 w-4 text-muted-foreground/60" />
                                                    <span className="font-medium">{property.number_of_bedrooms ?? '-'}</span>
                                                </div>
                                            </TableCell>
                                            <TableCell>
                                                <div className="flex items-center gap-1">
                                                    <span className="text-base font-semibold">
                                                        {property.price ? (
                                                            <>£{property.price.toLocaleString()}</>
                                                        ) : (
                                                            <span className="text-sm text-muted-foreground font-normal">-</span>
                                                        )}
                                                    </span>
                                                    {property.price && (
                                                        <span className="text-xs text-muted-foreground">/mo</span>
                                                    )}
                                                </div>
                                            </TableCell>
                                            <TableCell>
                                                <Badge
                                                    className={cn(
                                                        "gap-1.5 font-medium",
                                                        getStatusBadgeClasses(property.status)
                                                    )}
                                                >
                                                    {StatusIcon && <StatusIcon className="h-3 w-3" />}
                                                    {status?.label || 'Unknown'}
                                                </Badge>
                                            </TableCell>
                                            <TableCell>
                                                {property.landlord ? (
                                                    <Link
                                                        to={`/contacts/${property.landlord.id}`}
                                                        className="flex items-center gap-2.5 group/landlord"
                                                    >
                                                        <Avatar className="h-8 w-8 ring-2 ring-background shadow-sm">
                                                            <AvatarFallback className="text-xs font-medium bg-gradient-to-br from-slate-100 to-slate-50 dark:from-slate-700 dark:to-slate-800 text-slate-600 dark:text-slate-300">
                                                                {property.landlord.first_name[0]}
                                                                {property.landlord.last_name[0]}
                                                            </AvatarFallback>
                                                        </Avatar>
                                                        <span className="text-sm group-hover/landlord:text-primary transition-colors truncate max-w-[100px]">
                                                            {property.landlord.first_name} {property.landlord.last_name}
                                                        </span>
                                                    </Link>
                                                ) : (
                                                    <span className="text-sm text-muted-foreground/50">—</span>
                                                )}
                                            </TableCell>
                                            <TableCell>
                                                {hasComplianceIssues ? (
                                                    <TooltipProvider>
                                                        <Tooltip>
                                                            <TooltipTrigger>
                                                                <Badge variant="destructive" className="gap-1 font-medium">
                                                                    <AlertTriangle className="h-3 w-3" />
                                                                    Issues
                                                                </Badge>
                                                            </TooltipTrigger>
                                                            <TooltipContent>Compliance certificates expired</TooltipContent>
                                                        </Tooltip>
                                                    </TooltipProvider>
                                                ) : hasUpcomingCompliance ? (
                                                    <TooltipProvider>
                                                        <Tooltip>
                                                            <TooltipTrigger>
                                                                <Badge className="gap-1 font-medium bg-amber-50 text-amber-700 border border-amber-200 dark:bg-amber-500/10 dark:text-amber-400 dark:border-amber-500/20">
                                                                    <Clock className="h-3 w-3" />
                                                                    Soon
                                                                </Badge>
                                                            </TooltipTrigger>
                                                            <TooltipContent>Expiring within 30 days</TooltipContent>
                                                        </Tooltip>
                                                    </TooltipProvider>
                                                ) : (
                                                    <Badge className="gap-1 font-medium bg-emerald-50 text-emerald-700 border border-emerald-200 dark:bg-emerald-500/10 dark:text-emerald-400 dark:border-emerald-500/20">
                                                        <Shield className="h-3 w-3" />
                                                        Valid
                                                    </Badge>
                                                )}
                                            </TableCell>
                                            <TableCell className="pr-4">
                                                <DropdownMenu>
                                                    <DropdownMenuTrigger asChild>
                                                        <Button
                                                            variant="ghost"
                                                            size="icon"
                                                            className="h-8 w-8 opacity-0 group-hover:opacity-100 focus:opacity-100 transition-opacity"
                                                        >
                                                            <MoreHorizontal className="h-4 w-4" />
                                                        </Button>
                                                    </DropdownMenuTrigger>
                                                    <DropdownMenuContent align="end" className="w-48">
                                                        <DropdownMenuItem asChild>
                                                            <Link to={`/properties/${property.id}`}>
                                                                <Eye className="mr-2 h-4 w-4" />
                                                                View Details
                                                            </Link>
                                                        </DropdownMenuItem>
                                                        <DropdownMenuItem onClick={() => setEditingProperty(property.id)}>
                                                            <Edit className="mr-2 h-4 w-4" />
                                                            Edit
                                                        </DropdownMenuItem>
                                                        <DropdownMenuItem
                                                            onClick={() => {
                                                                navigator.clipboard.writeText(
                                                                    window.location.origin + `/properties/${property.id}`
                                                                );
                                                                toast.success('Link copied!');
                                                            }}
                                                        >
                                                            <Copy className="mr-2 h-4 w-4" />
                                                            Copy Link
                                                        </DropdownMenuItem>
                                                        <DropdownMenuSeparator />
                                                        <DropdownMenuItem
                                                            onClick={() => handleDelete(property.id)}
                                                            className="text-destructive focus:text-destructive focus:bg-destructive/10"
                                                        >
                                                            <Trash2 className="mr-2 h-4 w-4" />
                                                            Delete
                                                        </DropdownMenuItem>
                                                    </DropdownMenuContent>
                                                </DropdownMenu>
                                            </TableCell>
                                        </motion.tr>
                                    );
                                })}
                            </TableBody>
                        </Table>
                    </div>
                </Card>
            )}

            {/* Pagination - Refined */}
            {filteredProperties.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={String(perPage)}
                            onValueChange={(v) => {
                                setPerPage(Number(v));
                                setCurrentPage(1);
                            }}
                        >
                            <SelectTrigger className="w-[70px] h-8 border-border/50">
                                <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-4">
                        <span className="text-sm text-muted-foreground hidden sm:inline">
                            {(currentPage - 1) * perPage + 1}–{Math.min(currentPage * perPage, filteredProperties.length)} of{' '}
                            {filteredProperties.length}
                        </span>

                        <div className="flex items-center gap-1">
                            <Button
                                variant="outline"
                                size="icon"
                                className="h-8 w-8 border-border/50"
                                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 border-border/50"
                                onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
                                disabled={currentPage === 1}
                            >
                                <ChevronLeft className="h-4 w-4" />
                            </Button>

                            {/* Page numbers */}
                            <div className="hidden sm:flex items-center gap-1 mx-2">
                                {getPageNumbers().map((page, idx) =>
                                    page === 'ellipsis' ? (
                                        <span key={`ellipsis-${idx}`} className="px-1.5 text-muted-foreground/50">
                                            ···
                                        </span>
                                    ) : (
                                        <Button
                                            key={page}
                                            variant={currentPage === page ? 'default' : 'ghost'}
                                            size="icon"
                                            className={cn(
                                                'h-8 w-8 text-sm',
                                                currentPage === page && 'pointer-events-none shadow-sm'
                                            )}
                                            onClick={() => setCurrentPage(page)}
                                        >
                                            {page}
                                        </Button>
                                    )
                                )}
                            </div>

                            <Button
                                variant="outline"
                                size="icon"
                                className="h-8 w-8 border-border/50"
                                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 border-border/50"
                                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 - Refined */}
            <Sheet open={isFiltersOpen} onOpenChange={setIsFiltersOpen}>
                <SheetContent side="right" className="w-80 sm:w-96 border-l-border/50">
                    <SheetHeader className="pb-6">
                        <SheetTitle className="flex items-center gap-2.5 text-lg">
                            <div className="p-2 rounded-lg bg-primary/10">
                                <SlidersHorizontal className="h-4 w-4 text-primary" />
                            </div>
                            Filters
                        </SheetTitle>
                        <SheetDescription>Refine your property search</SheetDescription>
                    </SheetHeader>

                    <div className="space-y-6">
                        {/* Status */}
                        <div className="space-y-3">
                            <Label className="text-sm font-medium text-foreground">Status</Label>
                            <Select
                                value={filters.status}
                                onValueChange={(v) => setFilters((f) => ({ ...f, status: v }))}
                            >
                                <SelectTrigger className="border-border/50">
                                    <SelectValue placeholder="All statuses" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="all">All statuses</SelectItem>
                                    {Object.entries(statusConfig).map(([key, config]) => (
                                        <SelectItem key={key} value={key}>
                                            <div className="flex items-center gap-2">
                                                <div className={cn('h-2 w-2 rounded-full', config.color)} />
                                                {config.label}
                                            </div>
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                        </div>

                        {/* Property Type */}
                        {propertyTypes.length > 0 && (
                            <div className="space-y-3">
                                <Label className="text-sm font-medium text-foreground">Property Type</Label>
                                <Select
                                    value={filters.propertyType}
                                    onValueChange={(v) => setFilters((f) => ({ ...f, propertyType: v }))}
                                >
                                    <SelectTrigger className="border-border/50">
                                        <SelectValue placeholder="All types" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="all">All types</SelectItem>
                                        {propertyTypes.map((type) => (
                                            <SelectItem key={type} value={type}>
                                                {type}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </div>
                        )}

                        {/* Landlord */}
                        {landlords.length > 0 && (
                            <div className="space-y-3">
                                <Label className="text-sm font-medium text-foreground">Landlord</Label>
                                <Select
                                    value={filters.landlordId}
                                    onValueChange={(v) => setFilters((f) => ({ ...f, landlordId: v }))}
                                >
                                    <SelectTrigger className="border-border/50">
                                        <SelectValue placeholder="All landlords" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="all">All landlords</SelectItem>
                                        {landlords.map((landlord) => (
                                            <SelectItem key={landlord.id} value={landlord.id}>
                                                {landlord.first_name} {landlord.last_name}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </div>
                        )}

                        {/* Bedrooms */}
                        <div className="space-y-3">
                            <Label className="text-sm font-medium text-foreground">Bedrooms</Label>
                            <div className="grid grid-cols-2 gap-3">
                                <div>
                                    <Input
                                        type="number"
                                        placeholder="Min"
                                        value={filters.minBedrooms}
                                        onChange={(e) => setFilters((f) => ({ ...f, minBedrooms: e.target.value }))}
                                        min={0}
                                        className="border-border/50"
                                    />
                                </div>
                                <div>
                                    <Input
                                        type="number"
                                        placeholder="Max"
                                        value={filters.maxBedrooms}
                                        onChange={(e) => setFilters((f) => ({ ...f, maxBedrooms: e.target.value }))}
                                        min={0}
                                        className="border-border/50"
                                    />
                                </div>
                            </div>
                        </div>

                        {/* Price */}
                        <div className="space-y-3">
                            <Label className="text-sm font-medium text-foreground">Monthly Price (£)</Label>
                            <div className="grid grid-cols-2 gap-3">
                                <div>
                                    <Input
                                        type="number"
                                        placeholder="Min"
                                        value={filters.minPrice}
                                        onChange={(e) => setFilters((f) => ({ ...f, minPrice: e.target.value }))}
                                        min={0}
                                        className="border-border/50"
                                    />
                                </div>
                                <div>
                                    <Input
                                        type="number"
                                        placeholder="Max"
                                        value={filters.maxPrice}
                                        onChange={(e) => setFilters((f) => ({ ...f, maxPrice: e.target.value }))}
                                        min={0}
                                        className="border-border/50"
                                    />
                                </div>
                            </div>
                        </div>

                        {/* Compliance */}
                        <div className="space-y-3">
                            <Label className="text-sm font-medium text-foreground">Compliance Status</Label>
                            <Select
                                value={filters.complianceExpiring}
                                onValueChange={(v) => setFilters((f) => ({ ...f, complianceExpiring: v }))}
                            >
                                <SelectTrigger className="border-border/50">
                                    <SelectValue placeholder="All" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="all">All</SelectItem>
                                    <SelectItem value="expired">
                                        <div className="flex items-center gap-2">
                                            <AlertTriangle className="h-4 w-4 text-destructive" />
                                            Expired
                                        </div>
                                    </SelectItem>
                                    <SelectItem value="30">Expiring in 30 days</SelectItem>
                                    <SelectItem value="60">Expiring in 60 days</SelectItem>
                                    <SelectItem value="90">Expiring in 90 days</SelectItem>
                                </SelectContent>
                            </Select>
                        </div>

                        <Separator className="bg-border/50" />

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

            {/* Form Dialog */}
            <PropertyFormDialog
                open={formOpen || !!editingProperty}
                onOpenChange={(open) => {
                    setFormOpen(open);
                    if (!open) setEditingProperty(null);
                }}
                propertyId={editingProperty || undefined}
            />

            {/* Delete Confirmation - Refined */}
            <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
                <AlertDialogContent className="border-border/50">
                    <AlertDialogHeader>
                        <AlertDialogTitle className="flex items-center gap-3">
                            <div className="p-2.5 rounded-full bg-destructive/10">
                                <Trash2 className="h-5 w-5 text-destructive" />
                            </div>
                            Delete Property
                        </AlertDialogTitle>
                        <AlertDialogDescription className="text-muted-foreground">
                            Are you sure you want to delete this property? This action can be undone from the
                            trash within 30 days.
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel className="border-border/50">Cancel</AlertDialogCancel>
                        <AlertDialogAction
                            onClick={confirmDelete}
                            className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                        >
                            {deleteProperty.isPending ? (
                                <>
                                    <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                                    Deleting...
                                </>
                            ) : (
                                'Delete Property'
                            )}
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>

            {/* Bulk Delete Confirmation */}
            <AlertDialog open={isBulkDeleteOpen} onOpenChange={setIsBulkDeleteOpen}>
                <AlertDialogContent className="border-border/50">
                    <AlertDialogHeader>
                        <AlertDialogTitle className="flex items-center gap-3">
                            <div className="p-2.5 rounded-full bg-destructive/10">
                                <Trash2 className="h-5 w-5 text-destructive" />
                            </div>
                            Delete {selectedProperties.length} Properties
                        </AlertDialogTitle>
                        <AlertDialogDescription className="text-muted-foreground">
                            Are you sure you want to delete {selectedProperties.length} properties? This action can be undone from the trash within 30 days.
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel className="border-border/50">Cancel</AlertDialogCancel>
                        <AlertDialogAction
                            onClick={handleBulkDelete}
                            className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                        >
                            Delete All
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>
        </div>
    );
}