import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
    Plus,
    Search,
    Eye,
    Edit,
    Trash2,
    Home,
    Calendar,
    Upload,
    MoreHorizontal,
    Building2,
    Clock,
    CheckCircle2,
    XCircle,
    ArrowUpRight,
    FileText,
    ChevronLeft,
    ChevronRight,
    ChevronsLeft,
    ChevronsRight,
    CalendarDays,
    List,
    AlertCircle,
    LogIn,
    LogOut,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { Skeleton } from '@/components/ui/skeleton';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { useTenancies, useDeleteTenancy, TenancyWithRelations } from '@/hooks/useTenancies';
import { TenancyFormDialog } from '@/components/tenancies/TenancyFormDialog';
import { TenancyImportDialog } from '@/components/tenancies/TenancyImportDialog';
import { format, startOfMonth, endOfMonth, eachDayOfInterval, isSameMonth, isSameDay, addMonths, subMonths, differenceInDays, startOfDay, endOfDay } from 'date-fns';
import { cn } from '@/lib/utils';

export default function Tenancies() {
    const navigate = useNavigate();
    const { data: tenancies, isLoading } = useTenancies();
    const deleteTenancy = useDeleteTenancy();

    const [search, setSearch] = useState('');
    const [statusFilter, setStatusFilter] = useState<string>('all');
    const [formOpen, setFormOpen] = useState(false);
    const [importOpen, setImportOpen] = useState(false);
    const [editingTenancy, setEditingTenancy] = useState<TenancyWithRelations | null>(null);
    const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
    const [tenancyToDelete, setTenancyToDelete] = useState<string | null>(null);
    const [viewMode, setViewMode] = useState<'table' | 'calendar'>('table');
    const [currentMonth, setCurrentMonth] = useState(new Date());

    // Pagination state
    const [currentPage, setCurrentPage] = useState(1);
    const [itemsPerPage, setItemsPerPage] = useState(10);

    const filteredTenancies = tenancies?.filter((tenancy) => {
        const searchLower = search.toLowerCase();
        const matchesSearch =
            !search ||
            tenancy.reference?.toLowerCase().includes(searchLower) ||
            tenancy.tenant?.first_name?.toLowerCase().includes(searchLower) ||
            tenancy.tenant?.last_name?.toLowerCase().includes(searchLower) ||
            tenancy.property?.display_address?.toLowerCase().includes(searchLower) ||
            tenancy.property?.address_line_1?.toLowerCase().includes(searchLower);

        const matchesStatus = statusFilter === 'all' || tenancy.status === statusFilter;

        return matchesSearch && matchesStatus;
    });

    // Pagination calculations
    const totalPages = Math.ceil((filteredTenancies?.length || 0) / itemsPerPage);
    const startIndex = (currentPage - 1) * itemsPerPage;
    const endIndex = startIndex + itemsPerPage;
    const paginatedTenancies = filteredTenancies?.slice(startIndex, endIndex);

    // Generate page numbers
    const getPageNumbers = () => {
        const delta = 2;
        const range: number[] = [];
        const rangeWithDots: (number | string)[] = [];
        let l: number | undefined;

        for (let i = 1; i <= totalPages; i++) {
            if (i === 1 || i === totalPages || (i >= currentPage - delta && i <= currentPage + delta)) {
                range.push(i);
            }
        }

        range.forEach((i) => {
            if (l) {
                if (i - l === 2) {
                    rangeWithDots.push(l + 1);
                } else if (i - l !== 1) {
                    rangeWithDots.push('...');
                }
            }
            rangeWithDots.push(i);
            l = i;
        });

        return rangeWithDots;
    };

    // Calendar helpers
    const getDaysInMonth = () => {
        const start = startOfMonth(currentMonth);
        const end = endOfMonth(currentMonth);
        return eachDayOfInterval({ start, end });
    };

    const getFirstDayOfWeek = () => {
        const firstDay = startOfMonth(currentMonth);
        return firstDay.getDay();
    };

    // UPDATED: Logic to only show events on Start or End dates
    const getTenancyEventsForDay = (day: Date) => {
        return filteredTenancies?.map(tenancy => {
            if (!tenancy.start_date) return null;

            const startDate = startOfDay(new Date(tenancy.start_date));
            const endDate = tenancy.end_date ? endOfDay(new Date(tenancy.end_date)) : null;

            const isStart = isSameDay(day, startDate);
            const isEnd = endDate ? isSameDay(day, endDate) : false;

            if (isStart || isEnd) {
                return {
                    ...tenancy,
                    eventType: isStart && isEnd ? 'both' : isStart ? 'start' : 'end'
                } as TenancyWithRelations & { eventType: 'start' | 'end' | 'both' };
            }
            return null;
        }).filter((item): item is TenancyWithRelations & { eventType: 'start' | 'end' | 'both' } => item !== null) || [];
    };

    const getExpiringTenancies = () => {
        return filteredTenancies?.filter((tenancy) => {
            if (!tenancy.end_date || tenancy.status !== 'active') return false;
            const endDate = new Date(tenancy.end_date);
            const daysUntilExpiry = differenceInDays(endDate, new Date());
            return daysUntilExpiry >= 0 && daysUntilExpiry <= 30;
        }) || [];
    };

    const stats = {
        total: tenancies?.length || 0,
        active: tenancies?.filter((t) => t.status === 'active').length || 0,
        pending: tenancies?.filter((t) => t.status === 'pending').length || 0,
        ended: tenancies?.filter((t) => t.status === 'ended').length || 0,
    };

    const getStatusConfig = (status: string | null) => {
        switch (status) {
            case 'active':
                return { label: 'Active', className: 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/20', icon: CheckCircle2 };
            case 'pending':
                return { label: 'Pending', className: 'bg-amber-500/10 text-amber-600 dark:text-amber-400 border-amber-500/20', icon: Clock };
            case 'ended':
                return { label: 'Ended', className: 'bg-slate-500/10 text-slate-600 dark:text-slate-400 border-slate-500/20', icon: Calendar };
            case 'cancelled':
                return { label: 'Cancelled', className: 'bg-red-500/10 text-red-600 dark:text-red-400 border-red-500/20', icon: XCircle };
            default:
                return { label: 'Unknown', className: 'bg-muted text-muted-foreground', icon: FileText };
        }
    };

    const getTenantInitials = (tenancy: TenancyWithRelations) => {
        if (!tenancy.tenant) return '?';
        return `${tenancy.tenant.first_name?.[0] || ''}${tenancy.tenant.last_name?.[0] || ''}`.toUpperCase();
    };

    const handleEdit = (tenancy: TenancyWithRelations) => {
        setEditingTenancy(tenancy);
        setFormOpen(true);
    };

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

    const confirmDelete = async () => {
        if (tenancyToDelete) {
            await deleteTenancy.mutateAsync(tenancyToDelete);
            setDeleteDialogOpen(false);
            setTenancyToDelete(null);
        }
    };

    const handleFormClose = () => {
        setFormOpen(false);
        setEditingTenancy(null);
    };

    // Reset pagination on search/filter
    const handleSearchChange = (value: string) => { setSearch(value); setCurrentPage(1); };
    const handleStatusFilterChange = (value: string) => { setStatusFilter(value); setCurrentPage(1); };

    return (
        <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-50 dark:from-slate-950 dark:via-slate-900 dark:to-slate-950">
            <div className="space-y-6 p-6 md:p-8 lg:p-10">
                {/* Header Section */}
                <div className="flex flex-col gap-6 lg:flex-row lg:items-center lg:justify-between">
                    <div className="space-y-1">
                        <div className="flex items-center gap-3">
                            <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-gradient-to-br from-violet-500 to-purple-600 shadow-lg shadow-violet-500/25">
                                <FileText className="h-5 w-5 text-white" />
                            </div>
                            <div>
                                <h1 className="text-2xl font-bold tracking-tight text-slate-900 dark:text-white md:text-3xl">
                                    Tenancies
                                </h1>
                                <p className="text-sm text-slate-500 dark:text-slate-400">
                                    Manage active lettings and track move-ins/move-outs
                                </p>
                            </div>
                        </div>
                    </div>
                    <div className="flex flex-wrap gap-3">
                        <Button
                            variant="outline"
                            onClick={() => setImportOpen(true)}
                            className="gap-2 border-slate-200 bg-white shadow-sm hover:bg-slate-50 dark:border-slate-800 dark:bg-slate-900 dark:hover:bg-slate-800"
                        >
                            <Upload className="h-4 w-4" />
                            Import
                        </Button>
                        <Button
                            onClick={() => setFormOpen(true)}
                            className="gap-2 bg-gradient-to-r from-violet-600 to-purple-600 shadow-lg shadow-violet-500/25 hover:from-violet-700 hover:to-purple-700"
                        >
                            <Plus className="h-4 w-4" />
                            Add Tenancy
                        </Button>
                    </div>
                </div>

                {/* Compact Stats Cards */}
                <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
                    <Card className="border-0 bg-white shadow-sm shadow-slate-200/50 dark:bg-slate-900 dark:shadow-slate-950/50">
                        <CardContent className="flex items-center justify-between p-4">
                            <div>
                                <p className="text-xs font-medium text-slate-500 dark:text-slate-400">Total</p>
                                <p className="text-2xl font-bold text-slate-900 dark:text-white">
                                    {isLoading ? <Skeleton className="h-8 w-12" /> : stats.total}
                                </p>
                            </div>
                            <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-violet-500/10 text-violet-600 dark:bg-violet-500/20 dark:text-violet-400">
                                <Building2 className="h-4 w-4" />
                            </div>
                        </CardContent>
                    </Card>

                    <Card className="border-0 bg-white shadow-sm shadow-slate-200/50 dark:bg-slate-900 dark:shadow-slate-950/50">
                        <CardContent className="flex items-center justify-between p-4">
                            <div>
                                <p className="text-xs font-medium text-slate-500 dark:text-slate-400">Active</p>
                                <p className="text-2xl font-bold text-emerald-600 dark:text-emerald-400">
                                    {isLoading ? <Skeleton className="h-8 w-12" /> : stats.active}
                                </p>
                            </div>
                            <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-emerald-500/10 text-emerald-600 dark:bg-emerald-500/20 dark:text-emerald-400">
                                <CheckCircle2 className="h-4 w-4" />
                            </div>
                        </CardContent>
                    </Card>

                    <Card className="border-0 bg-white shadow-sm shadow-slate-200/50 dark:bg-slate-900 dark:shadow-slate-950/50">
                        <CardContent className="flex items-center justify-between p-4">
                            <div>
                                <p className="text-xs font-medium text-slate-500 dark:text-slate-400">Pending</p>
                                <p className="text-2xl font-bold text-amber-600 dark:text-amber-400">
                                    {isLoading ? <Skeleton className="h-8 w-12" /> : stats.pending}
                                </p>
                            </div>
                            <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-amber-500/10 text-amber-600 dark:bg-amber-500/20 dark:text-amber-400">
                                <Clock className="h-4 w-4" />
                            </div>
                        </CardContent>
                    </Card>

                    <Card className="border-0 bg-white shadow-sm shadow-slate-200/50 dark:bg-slate-900 dark:shadow-slate-950/50">
                        <CardContent className="flex items-center justify-between p-4">
                            <div>
                                <p className="text-xs font-medium text-slate-500 dark:text-slate-400">Ended</p>
                                <p className="text-2xl font-bold text-slate-600 dark:text-slate-400">
                                    {isLoading ? <Skeleton className="h-8 w-12" /> : stats.ended}
                                </p>
                            </div>
                            <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-slate-500/10 text-slate-600 dark:bg-slate-500/20 dark:text-slate-400">
                                <Calendar className="h-4 w-4" />
                            </div>
                        </CardContent>
                    </Card>
                </div>

                {/* Expiring Soon Alert */}
                {getExpiringTenancies().length > 0 && (
                    <Card className="border-amber-200 bg-amber-50/50 dark:border-amber-900/50 dark:bg-amber-950/20">
                        <CardContent className="flex items-center gap-3 p-3">
                            <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-amber-100 dark:bg-amber-900/30">
                                <AlertCircle className="h-4 w-4 text-amber-600 dark:text-amber-400" />
                            </div>
                            <div className="flex-1">
                                <p className="text-sm font-medium text-amber-900 dark:text-amber-100">
                                    {getExpiringTenancies().length} {getExpiringTenancies().length === 1 ? 'tenancy expires' : 'tenancies expire'} in the next 30 days
                                </p>
                            </div>
                            <Button
                                size="sm"
                                variant="outline"
                                className="h-8 border-amber-300 bg-white hover:bg-amber-50 dark:border-amber-800 dark:bg-amber-950 dark:hover:bg-amber-900"
                                onClick={() => handleStatusFilterChange('active')}
                            >
                                Review
                            </Button>
                        </CardContent>
                    </Card>
                )}

                {/* Filters & Search with View Toggle */}
                <Card className="border-0 bg-white shadow-md shadow-slate-200/50 dark:bg-slate-900 dark:shadow-slate-950/50">
                    <CardContent className="p-4">
                        <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
                            <Tabs value={statusFilter} onValueChange={handleStatusFilterChange} className="w-full lg:w-auto">
                                <TabsList className="grid h-auto w-full grid-cols-5 gap-1 bg-slate-100 p-1 dark:bg-slate-800 lg:flex lg:w-auto">
                                    <TabsTrigger value="all" className="gap-2">All</TabsTrigger>
                                    <TabsTrigger value="active" className="gap-2">Active</TabsTrigger>
                                    <TabsTrigger value="pending" className="gap-2">Pending</TabsTrigger>
                                    <TabsTrigger value="ended" className="gap-2">Ended</TabsTrigger>
                                    <TabsTrigger value="cancelled" className="gap-2">Cancelled</TabsTrigger>
                                </TabsList>
                            </Tabs>

                            <div className="flex flex-1 items-center gap-3 lg:max-w-md">
                                <div className="relative flex-1">
                                    <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
                                    <Input
                                        placeholder="Search tenancies..."
                                        value={search}
                                        onChange={(e) => handleSearchChange(e.target.value)}
                                        className="border-slate-200 bg-slate-50 pl-10 focus:bg-white dark:border-slate-700 dark:bg-slate-800 dark:focus:bg-slate-800"
                                    />
                                </div>
                                <div className="flex rounded-lg border border-slate-200 bg-slate-50 p-1 dark:border-slate-700 dark:bg-slate-800">
                                    <TooltipProvider>
                                        <Tooltip>
                                            <TooltipTrigger asChild>
                                                <Button
                                                    variant={viewMode === 'table' ? 'secondary' : 'ghost'}
                                                    size="sm"
                                                    onClick={() => setViewMode('table')}
                                                    className="h-8 w-8 p-0"
                                                >
                                                    <List className="h-4 w-4" />
                                                </Button>
                                            </TooltipTrigger>
                                            <TooltipContent>Table View</TooltipContent>
                                        </Tooltip>
                                        <Tooltip>
                                            <TooltipTrigger asChild>
                                                <Button
                                                    variant={viewMode === 'calendar' ? 'secondary' : 'ghost'}
                                                    size="sm"
                                                    onClick={() => setViewMode('calendar')}
                                                    className="h-8 w-8 p-0"
                                                >
                                                    <CalendarDays className="h-4 w-4" />
                                                </Button>
                                            </TooltipTrigger>
                                            <TooltipContent>Calendar View</TooltipContent>
                                        </Tooltip>
                                    </TooltipProvider>
                                </div>
                            </div>
                        </div>
                    </CardContent>
                </Card>

                {/* View Content */}
                {viewMode === 'table' ? (
                    <Card className="overflow-hidden border-0 bg-white shadow-md shadow-slate-200/50 dark:bg-slate-900 dark:shadow-slate-950/50">
                        <div className="overflow-x-auto">
                            <Table>
                                <TableHeader>
                                    <TableRow className="border-slate-100 bg-slate-50/50 hover:bg-slate-50/50 dark:border-slate-800 dark:bg-slate-800/50">
                                        <TableHead>Reference</TableHead>
                                        <TableHead>Property</TableHead>
                                        <TableHead>Tenant</TableHead>
                                        <TableHead>Duration</TableHead>
                                        <TableHead>Rent</TableHead>
                                        <TableHead>Status</TableHead>
                                        <TableHead className="text-right">Actions</TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {isLoading ? (
                                        Array.from({ length: 5 }).map((_, i) => (
                                            <TableRow key={i}>
                                                <TableCell><Skeleton className="h-5 w-24" /></TableCell>
                                                <TableCell><Skeleton className="h-5 w-40" /></TableCell>
                                                <TableCell><Skeleton className="h-5 w-32" /></TableCell>
                                                <TableCell><Skeleton className="h-5 w-36" /></TableCell>
                                                <TableCell><Skeleton className="h-5 w-24" /></TableCell>
                                                <TableCell><Skeleton className="h-6 w-20" /></TableCell>
                                                <TableCell><Skeleton className="ml-auto h-8 w-8" /></TableCell>
                                            </TableRow>
                                        ))
                                    ) : paginatedTenancies?.length === 0 ? (
                                        <TableRow>
                                            <TableCell colSpan={7} className="h-60 text-center">
                                                <div className="flex flex-col items-center justify-center gap-2">
                                                    <FileText className="h-8 w-8 text-slate-300" />
                                                    <p className="text-slate-500">No tenancies found</p>
                                                </div>
                                            </TableCell>
                                        </TableRow>
                                    ) : (
                                        paginatedTenancies?.map((tenancy) => {
                                            const statusConfig = getStatusConfig(tenancy.status);
                                            const StatusIcon = statusConfig.icon;
                                            const daysUntilExpiry = tenancy.end_date
                                                ? differenceInDays(new Date(tenancy.end_date), new Date())
                                                : null;

                                            return (
                                                <TableRow
                                                    key={tenancy.id}
                                                    className="group cursor-pointer border-slate-100 hover:bg-slate-50 dark:border-slate-800 dark:hover:bg-slate-800/50"
                                                    onClick={() => navigate(`/tenancies/${tenancy.id}`)}
                                                >
                                                    <TableCell>
                                                        <div className="flex items-center gap-2">
                                                            <span className="font-mono text-sm font-medium">{tenancy.reference || '-'}</span>
                                                            <ArrowUpRight className="h-3 w-3 text-slate-400 opacity-0 transition-opacity group-hover:opacity-100" />
                                                        </div>
                                                    </TableCell>
                                                    <TableCell>
                                                        <div className="flex items-center gap-3">
                                                            <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-slate-100 dark:bg-slate-800">
                                                                <Home className="h-3.5 w-3.5 text-slate-500" />
                                                            </div>
                                                            <span className="max-w-[180px] truncate text-sm text-slate-700 dark:text-slate-300">
                                                                {tenancy.property?.display_address || '-'}
                                                            </span>
                                                        </div>
                                                    </TableCell>
                                                    <TableCell>
                                                        <div className="flex items-center gap-2">
                                                            <Avatar className="h-7 w-7">
                                                                <AvatarFallback className="text-[10px]">{getTenantInitials(tenancy)}</AvatarFallback>
                                                            </Avatar>
                                                            <span className="text-sm font-medium">
                                                                {tenancy.tenant ? `${tenancy.tenant.first_name} ${tenancy.tenant.last_name}` : '-'}
                                                            </span>
                                                        </div>
                                                    </TableCell>
                                                    <TableCell>
                                                        <div className="space-y-0.5">
                                                            <div className="text-sm">
                                                                {tenancy.start_date ? format(new Date(tenancy.start_date), 'dd MMM yyyy') : '-'}
                                                            </div>
                                                            {tenancy.end_date && (
                                                                <div className="flex items-center gap-2">
                                                                    <span className="text-xs text-slate-500">
                                                                        to {format(new Date(tenancy.end_date), 'dd MMM yyyy')}
                                                                    </span>
                                                                    {daysUntilExpiry !== null && daysUntilExpiry >= 0 && daysUntilExpiry <= 30 && (
                                                                        <Badge variant="outline" className="h-4 border-amber-200 bg-amber-50 px-1 text-[10px] text-amber-700">
                                                                            {daysUntilExpiry === 0 ? 'Today' : `${daysUntilExpiry}d`}
                                                                        </Badge>
                                                                    )}
                                                                </div>
                                                            )}
                                                        </div>
                                                    </TableCell>
                                                    <TableCell>
                                                        <span className="font-semibold">{tenancy.rent ? `£${tenancy.rent.toLocaleString()}` : '-'}</span>
                                                    </TableCell>
                                                    <TableCell>
                                                        <Badge variant="outline" className={cn('gap-1 border font-medium', statusConfig.className)}>
                                                            <StatusIcon className="h-3 w-3" />
                                                            {statusConfig.label}
                                                        </Badge>
                                                    </TableCell>
                                                    <TableCell className="text-right">
                                                        <DropdownMenu>
                                                            <DropdownMenuTrigger asChild onClick={(e) => e.stopPropagation()}>
                                                                <Button variant="ghost" size="icon" className="h-8 w-8">
                                                                    <MoreHorizontal className="h-4 w-4" />
                                                                </Button>
                                                            </DropdownMenuTrigger>
                                                            <DropdownMenuContent align="end">
                                                                <DropdownMenuItem onClick={() => navigate(`/tenancies/${tenancy.id}`)}>
                                                                    <Eye className="mr-2 h-4 w-4" /> View
                                                                </DropdownMenuItem>
                                                                <DropdownMenuItem onClick={() => handleEdit(tenancy)}>
                                                                    <Edit className="mr-2 h-4 w-4" /> Edit
                                                                </DropdownMenuItem>
                                                                <DropdownMenuSeparator />
                                                                <DropdownMenuItem onClick={() => handleDelete(tenancy.id)} className="text-red-600">
                                                                    <Trash2 className="mr-2 h-4 w-4" /> Delete
                                                                </DropdownMenuItem>
                                                            </DropdownMenuContent>
                                                        </DropdownMenu>
                                                    </TableCell>
                                                </TableRow>
                                            );
                                        })
                                    )}
                                </TableBody>
                            </Table>
                        </div>

                        {/* Pagination Controls */}
                        {filteredTenancies && filteredTenancies.length > 0 && (
                            <div className="flex items-center justify-between border-t border-slate-100 px-6 py-4 dark:border-slate-800">
                                <div className="flex items-center gap-4 text-sm text-slate-500">
                                    <span>Showing {startIndex + 1}-{Math.min(endIndex, filteredTenancies.length)} of {filteredTenancies.length}</span>
                                    <Select value={String(itemsPerPage)} onValueChange={(v) => { setItemsPerPage(Number(v)); setCurrentPage(1); }}>
                                        <SelectTrigger className="h-8 w-[70px]"><SelectValue /></SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="10">10</SelectItem>
                                            <SelectItem value="25">25</SelectItem>
                                            <SelectItem value="50">50</SelectItem>
                                            <SelectItem value="100">100</SelectItem>
                                        </SelectContent>
                                    </Select>
                                </div>

                                <div className="flex items-center gap-1">
                                    <Button variant="outline" size="icon" className="h-8 w-8" onClick={() => setCurrentPage(1)} disabled={currentPage === 1}><ChevronsLeft className="h-4 w-4" /></Button>
                                    <Button variant="outline" size="icon" className="h-8 w-8" onClick={() => setCurrentPage(currentPage - 1)} disabled={currentPage === 1}><ChevronLeft className="h-4 w-4" /></Button>

                                    {getPageNumbers().map((page, i) => (
                                        <div key={i}>
                                            {page === '...' ? <span className="px-2 text-slate-400">...</span> : (
                                                <Button
                                                    variant={currentPage === page ? 'default' : 'outline'}
                                                    size="sm"
                                                    className={cn('h-8 w-8', currentPage === page && 'bg-violet-600')}
                                                    onClick={() => setCurrentPage(page as number)}
                                                >
                                                    {page}
                                                </Button>
                                            )}
                                        </div>
                                    ))}

                                    <Button variant="outline" size="icon" className="h-8 w-8" onClick={() => setCurrentPage(currentPage + 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}><ChevronsRight className="h-4 w-4" /></Button>
                                </div>
                            </div>
                        )}
                    </Card>
                ) : (
                    /* Calendar View - Event Based Tracking */
                    <Card className="overflow-hidden border-0 bg-white shadow-md shadow-slate-200/50 dark:bg-slate-900 dark:shadow-slate-950/50">
                        <CardHeader className="border-b border-slate-100 dark:border-slate-800">
                            <div className="flex items-center justify-between">
                                <CardTitle className="text-xl font-semibold">
                                    {format(currentMonth, 'MMMM yyyy')}
                                </CardTitle>
                                <div className="flex items-center gap-2">
                                    <Button variant="outline" size="icon" onClick={() => setCurrentMonth(subMonths(currentMonth, 1))}><ChevronLeft className="h-4 w-4" /></Button>
                                    <Button variant="outline" size="sm" onClick={() => setCurrentMonth(new Date())}>Today</Button>
                                    <Button variant="outline" size="icon" onClick={() => setCurrentMonth(addMonths(currentMonth, 1))}><ChevronRight className="h-4 w-4" /></Button>
                                </div>
                            </div>
                        </CardHeader>
                        <CardContent className="p-0">
                            <div className="grid grid-cols-7">
                                {['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].map((day) => (
                                    <div key={day} className="border-b border-r border-slate-100 bg-slate-50 p-3 text-center text-sm font-medium text-slate-600 dark:border-slate-800 dark:bg-slate-800 dark:text-slate-400">{day}</div>
                                ))}
                                {Array.from({ length: getFirstDayOfWeek() }).map((_, i) => (
                                    <div key={`empty-${i}`} className="min-h-[120px] border-b border-r border-slate-100 bg-slate-50/50 p-2 dark:border-slate-800 dark:bg-slate-950/50" />
                                ))}

                                {getDaysInMonth().map((day) => {
                                    const eventsForDay = getTenancyEventsForDay(day);
                                    const isToday = isSameDay(day, new Date());

                                    return (
                                        <div
                                            key={day.toString()}
                                            className={cn(
                                                'min-h-[120px] border-b border-r border-slate-100 p-2 transition-colors dark:border-slate-800',
                                                isToday && 'bg-violet-50 dark:bg-violet-950/20',
                                                !isSameMonth(day, currentMonth) && 'bg-slate-50/50'
                                            )}
                                        >
                                            <div className="mb-2 flex items-center justify-between">
                                                <span className={cn('text-sm font-medium', isToday ? 'flex h-6 w-6 items-center justify-center rounded-full bg-violet-600 text-white' : 'text-slate-700 dark:text-slate-300')}>
                                                    {format(day, 'd')}
                                                </span>
                                            </div>
                                            <div className="space-y-1">
                                                {eventsForDay.map((tenancy) => {
                                                    const isStart = tenancy.eventType === 'start';
                                                    const isEnd = tenancy.eventType === 'end';
                                                    const isBoth = tenancy.eventType === 'both';

                                                    return (
                                                        <TooltipProvider key={tenancy.id}>
                                                            <Tooltip>
                                                                <TooltipTrigger asChild>
                                                                    <div
                                                                        className={cn(
                                                                            'cursor-pointer rounded px-2 py-1 text-xs font-medium transition-all hover:opacity-80 shadow-sm border',
                                                                            isStart && 'bg-emerald-100 text-emerald-800 border-emerald-200 dark:bg-emerald-900/40 dark:text-emerald-300 dark:border-emerald-800',
                                                                            isEnd && 'bg-red-100 text-red-800 border-red-200 dark:bg-red-900/40 dark:text-red-300 dark:border-red-800',
                                                                            isBoth && 'bg-purple-100 text-purple-800 border-purple-200 dark:bg-purple-900/40 dark:text-purple-300 dark:border-purple-800'
                                                                        )}
                                                                        onClick={() => navigate(`/tenancies/${tenancy.id}`)}
                                                                    >
                                                                        <div className="flex items-center gap-1.5">
                                                                            {isStart && <LogIn className="h-3 w-3 flex-shrink-0" />}
                                                                            {isEnd && <LogOut className="h-3 w-3 flex-shrink-0" />}
                                                                            {isBoth && <div className="flex"><LogIn className="h-3 w-3" /><LogOut className="h-3 w-3" /></div>}

                                                                            <div className="flex flex-col truncate">
                                                                                <span className="truncate leading-none">
                                                                                    {tenancy.property?.display_address?.split(',')[0] || tenancy.reference}
                                                                                </span>
                                                                                <span className="mt-0.5 text-[10px] opacity-75 leading-none">
                                                                                    {isStart && !isBoth && 'Starts'}
                                                                                    {isEnd && !isBoth && 'Ends'}
                                                                                    {isBoth && 'Start & End'}
                                                                                </span>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                </TooltipTrigger>
                                                                <TooltipContent>
                                                                    <div className="space-y-1">
                                                                        <p className="font-semibold">{tenancy.reference}</p>
                                                                        <p className="text-xs">{tenancy.tenant?.first_name} {tenancy.tenant?.last_name}</p>
                                                                        <p className="text-xs">{tenancy.property?.display_address}</p>
                                                                        <div className="mt-1 flex gap-2">
                                                                            {isStart && <Badge className="bg-emerald-500 h-5 text-[10px]">Start Date</Badge>}
                                                                            {isEnd && <Badge className="bg-red-500 h-5 text-[10px]">End Date</Badge>}
                                                                        </div>
                                                                    </div>
                                                                </TooltipContent>
                                                            </Tooltip>
                                                        </TooltipProvider>
                                                    );
                                                })}
                                            </div>
                                        </div>
                                    );
                                })}
                            </div>

                            <div className="flex items-center gap-6 border-t border-slate-100 p-4 dark:border-slate-800">
                                <div className="flex items-center gap-2">
                                    <div className="flex h-5 items-center gap-1 rounded bg-emerald-100 px-2 text-xs font-medium text-emerald-800 border border-emerald-200 dark:bg-emerald-900/40 dark:text-emerald-300 dark:border-emerald-800">
                                        <LogIn className="h-3 w-3" /> Start
                                    </div>
                                    <span className="text-sm text-slate-600 dark:text-slate-400">Move In</span>
                                </div>
                                <div className="flex items-center gap-2">
                                    <div className="flex h-5 items-center gap-1 rounded bg-red-100 px-2 text-xs font-medium text-red-800 border border-red-200 dark:bg-red-900/40 dark:text-red-300 dark:border-red-800">
                                        <LogOut className="h-3 w-3" /> End
                                    </div>
                                    <span className="text-sm text-slate-600 dark:text-slate-400">Move Out</span>
                                </div>
                            </div>
                        </CardContent>
                    </Card>
                )}
            </div>

            <TenancyFormDialog open={formOpen} onOpenChange={handleFormClose} tenancy={editingTenancy} />
            <TenancyImportDialog open={importOpen} onOpenChange={setImportOpen} />

            <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
                <AlertDialogContent>
                    <AlertDialogHeader>
                        <AlertDialogTitle>Delete Tenancy</AlertDialogTitle>
                        <AlertDialogDescription>Are you sure? This action cannot be undone.</AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel>Cancel</AlertDialogCancel>
                        <AlertDialogAction onClick={confirmDelete} className="bg-red-600">Delete</AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>
        </div>
    );
}