import React, { useMemo, useState, useCallback, useRef, useEffect, type ElementType } from 'react';
import { format, isToday, isYesterday } from 'date-fns';
import {
    Mail,
    Phone,
    MessageSquare,
    ArrowUpRight,
    ArrowDownLeft,
    Loader2,
    Send,
    Settings,
    Bot,
    Search,
    X,
    Copy,
    Plus,
    ChevronDown,
    Clock,
    CheckCircle2,
    MoreHorizontal,
} from 'lucide-react';

import { useActivities, type Activity, type ActivityCategory } from '@/hooks/useActivities';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
    Popover,
    PopoverContent,
    PopoverTrigger,
} from '@/components/ui/popover';
import { Separator } from '@/components/ui/separator';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';

interface ContactActivitiesTabProps {
    contactId: string;
    variant?: 'default' | 'workbench';
    maxHeight?: string;
    pageSize?: number;
}

const activityConfig: Record<string, { icon: ElementType; color: string; bg: string; label: string }> = {
    email: { icon: Mail, color: 'text-blue-600', bg: 'bg-blue-500/10', label: 'Email' },
    call: { icon: Phone, color: 'text-emerald-600', bg: 'bg-emerald-500/10', label: 'Call' },
    sms: { icon: MessageSquare, color: 'text-violet-600', bg: 'bg-violet-500/10', label: 'SMS' },
    system: { icon: Settings, color: 'text-muted-foreground', bg: 'bg-muted', label: 'System' },
};

const categoryConfig: Record<ActivityCategory, { icon: ElementType; label: string; class: string }> = {
    user: { icon: CheckCircle2, label: 'Manual', class: 'text-foreground bg-background' },
    system: { icon: Settings, label: 'System', class: 'text-muted-foreground bg-muted/50' },
    automation: { icon: Bot, label: 'Auto', class: 'text-amber-600 bg-amber-500/10' },
};

function dayLabel(date: Date): string {
    if (isToday(date)) return 'Today';
    if (isYesterday(date)) return 'Yesterday';
    return format(date, 'MMM d, yyyy');
}

type FilterType = 'all' | 'email' | 'call' | 'sms' | 'system';
type FilterDirection = 'all' | 'inbound' | 'outbound';

export function ContactActivitiesTab({
    contactId,
    variant = 'default',
    maxHeight = '500px',
    pageSize = 10,
}: ContactActivitiesTabProps) {
    const { activities, isLoading, logActivity, isLogging } = useActivities(contactId);

    const [isDialogOpen, setIsDialogOpen] = useState(false);
    const [activityType, setActivityType] = useState<'email' | 'call' | 'sms'>('email');
    const [expandedId, setExpandedId] = useState<string | null>(null);

    const [formData, setFormData] = useState({
        subject: '',
        body_preview: '',
        direction: 'outbound' as 'inbound' | 'outbound',
    });

    // Unified filter state
    const [query, setQuery] = useState('');
    const [typeFilter, setTypeFilter] = useState<FilterType>('all');
    const [directionFilter, setDirectionFilter] = useState<FilterDirection>('all');
    const [sortNewest, setSortNewest] = useState(true);

    // Pagination state
    const [displayCount, setDisplayCount] = useState(pageSize);
    const [isLoadingMore, setIsLoadingMore] = useState(false);
    const scrollContainerRef = useRef<HTMLDivElement>(null);
    const loadMoreTriggerRef = useRef<HTMLDivElement>(null);

    const hasActiveFilters = query || typeFilter !== 'all' || directionFilter !== 'all';

    const clearFilters = () => {
        setQuery('');
        setTypeFilter('all');
        setDirectionFilter('all');
        setDisplayCount(pageSize); // Reset pagination when clearing filters
    };

    // Reset display count when filters change
    useEffect(() => {
        setDisplayCount(pageSize);
    }, [query, typeFilter, directionFilter, sortNewest, pageSize]);

    const resetForm = () => {
        setFormData({ subject: '', body_preview: '', direction: 'outbound' });
    };

    const openLogDialog = (type: 'email' | 'call' | 'sms') => {
        setActivityType(type);
        resetForm();
        setIsDialogOpen(true);
    };

    const handleLogActivity = async () => {
        if (!formData.subject.trim()) {
            toast.error('Please enter a subject or summary');
            return;
        }

        try {
            await logActivity({
                contact_id: contactId,
                type: activityType,
                direction: formData.direction,
                subject: formData.subject,
                body_preview: formData.body_preview || undefined,
                status: 'logged',
                category: 'user',
            });

            toast.success('Activity logged successfully');
            setIsDialogOpen(false);
            resetForm();
        } catch {
            // Error handled in hook
        }
    };

    // All filtered and sorted activities
    const allFiltered = useMemo(() => {
        const q = query.trim().toLowerCase();

        const list = activities.filter((a) => {
            if (typeFilter !== 'all' && a.type !== typeFilter) return false;
            if (directionFilter !== 'all' && a.direction !== directionFilter) return false;
            if (q) {
                const searchable = `${a.subject ?? ''} ${a.body_preview ?? ''}`.toLowerCase();
                if (!searchable.includes(q)) return false;
            }
            return true;
        });

        list.sort((a, b) => {
            const da = new Date(a.created_at).getTime();
            const db = new Date(b.created_at).getTime();
            return sortNewest ? db - da : da - db;
        });

        return list;
    }, [activities, query, typeFilter, directionFilter, sortNewest]);

    // Paginated subset
    const filtered = useMemo(() => {
        return allFiltered.slice(0, displayCount);
    }, [allFiltered, displayCount]);

    const hasMore = displayCount < allFiltered.length;
    const remainingCount = allFiltered.length - displayCount;

    const loadMore = useCallback(() => {
        if (!hasMore || isLoadingMore) return;

        setIsLoadingMore(true);
        // Simulate a small delay for smooth UX
        setTimeout(() => {
            setDisplayCount((prev) => Math.min(prev + pageSize, allFiltered.length));
            setIsLoadingMore(false);
        }, 150);
    }, [hasMore, isLoadingMore, pageSize, allFiltered.length]);

    // Intersection Observer for infinite scroll
    useEffect(() => {
        const trigger = loadMoreTriggerRef.current;
        const container = scrollContainerRef.current;

        if (!trigger || !container) return;

        const observer = new IntersectionObserver(
            (entries) => {
                const [entry] = entries;
                if (entry.isIntersecting && hasMore && !isLoadingMore) {
                    loadMore();
                }
            },
            {
                root: container,
                rootMargin: '100px',
                threshold: 0.1,
            }
        );

        observer.observe(trigger);

        return () => {
            observer.disconnect();
        };
    }, [hasMore, isLoadingMore, loadMore]);

    const grouped = useMemo(() => {
        const map = new Map<string, Activity[]>();

        for (const a of filtered) {
            const key = format(new Date(a.created_at), 'yyyy-MM-dd');
            const existing = map.get(key) ?? [];
            existing.push(a);
            map.set(key, existing);
        }

        const keys = Array.from(map.keys()).sort((a, b) => {
            const ta = new Date(a).getTime();
            const tb = new Date(b).getTime();
            return sortNewest ? tb - ta : ta - tb;
        });

        return keys.map((k) => ({
            key: k,
            label: dayLabel(new Date(k)),
            items: map.get(k) ?? [],
        }));
    }, [filtered, sortNewest]);

    const copyActivity = (activity: Activity) => {
        const text = [activity.subject, activity.body_preview].filter(Boolean).join('\n\n');
        navigator.clipboard.writeText(text);
        toast.success('Copied to clipboard');
    };

    if (isLoading) {
        return (
            <div className="flex items-center justify-center h-48">
                <div className="flex flex-col items-center gap-2">
                    <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
                    <span className="text-sm text-muted-foreground">Loading timeline...</span>
                </div>
            </div>
        );
    }

    return (
        <div className="flex flex-col h-full">
            {/* Fixed Header */}
            <div className="flex-shrink-0 space-y-3 pb-3">
                {/* Header with Quick Actions */}
                <div className="flex items-center justify-between gap-4">
                    <div>
                        <h3 className="text-base font-semibold">Activity Timeline</h3>
                        <p className="text-xs text-muted-foreground mt-0.5">
                            {activities.length} total · {allFiltered.length} matched · {filtered.length} shown
                        </p>
                    </div>

                    <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                            <Button size="sm" className="gap-2">
                                <Plus className="h-4 w-4" />
                                Log Activity
                                <ChevronDown className="h-3 w-3 opacity-50" />
                            </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end" className="w-44">
                            <DropdownMenuItem onClick={() => openLogDialog('call')} className="gap-2">
                                <Phone className="h-4 w-4 text-emerald-600" />
                                Log Call
                            </DropdownMenuItem>
                            <DropdownMenuItem onClick={() => openLogDialog('email')} className="gap-2">
                                <Mail className="h-4 w-4 text-blue-600" />
                                Log Email
                            </DropdownMenuItem>
                            <DropdownMenuItem onClick={() => openLogDialog('sms')} className="gap-2">
                                <MessageSquare className="h-4 w-4 text-violet-600" />
                                Log SMS
                            </DropdownMenuItem>
                        </DropdownMenuContent>
                    </DropdownMenu>
                </div>

                {/* Compact Search & Filters Bar */}
                <div className="flex items-center gap-2 bg-muted/30 rounded-lg p-1.5">
                    {/* Search */}
                    <div className="relative flex-1 min-w-0">
                        <Search className="h-4 w-4 text-muted-foreground absolute left-2.5 top-1/2 -translate-y-1/2" />
                        <Input
                            value={query}
                            onChange={(e) => setQuery(e.target.value)}
                            placeholder="Search activities..."
                            className="pl-8 h-8 bg-background border-0 focus-visible:ring-1"
                        />
                    </div>

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

                    {/* Type Filter */}
                    <Popover>
                        <PopoverTrigger asChild>
                            <Button
                                variant="ghost"
                                size="sm"
                                className={cn(
                                    "h-8 px-2.5 gap-1.5 text-xs",
                                    typeFilter !== 'all' && "bg-primary/10 text-primary"
                                )}
                            >
                                {typeFilter !== 'all' ? (
                                    <>
                                        {React.createElement(activityConfig[typeFilter].icon, { className: "h-3.5 w-3.5" })}
                                        {activityConfig[typeFilter].label}
                                    </>
                                ) : (
                                    <>Type</>
                                )}
                                <ChevronDown className="h-3 w-3 opacity-50" />
                            </Button>
                        </PopoverTrigger>
                        <PopoverContent align="start" className="w-36 p-1">
                            {(['all', 'email', 'call', 'sms', 'system'] as const).map((type) => (
                                <Button
                                    key={type}
                                    variant="ghost"
                                    size="sm"
                                    className={cn(
                                        "w-full justify-start gap-2 h-8",
                                        typeFilter === type && "bg-accent"
                                    )}
                                    onClick={() => setTypeFilter(type)}
                                >
                                    {type !== 'all' && React.createElement(activityConfig[type].icon, {
                                        className: cn("h-4 w-4", activityConfig[type].color)
                                    })}
                                    {type === 'all' ? 'All Types' : activityConfig[type].label}
                                </Button>
                            ))}
                        </PopoverContent>
                    </Popover>

                    {/* Direction Filter */}
                    <Popover>
                        <PopoverTrigger asChild>
                            <Button
                                variant="ghost"
                                size="sm"
                                className={cn(
                                    "h-8 px-2.5 gap-1.5 text-xs",
                                    directionFilter !== 'all' && "bg-primary/10 text-primary"
                                )}
                            >
                                {directionFilter === 'outbound' ? (
                                    <><ArrowUpRight className="h-3.5 w-3.5" /> Out</>
                                ) : directionFilter === 'inbound' ? (
                                    <><ArrowDownLeft className="h-3.5 w-3.5" /> In</>
                                ) : (
                                    <>Direction</>
                                )}
                                <ChevronDown className="h-3 w-3 opacity-50" />
                            </Button>
                        </PopoverTrigger>
                        <PopoverContent align="start" className="w-36 p-1">
                            <Button
                                variant="ghost"
                                size="sm"
                                className={cn("w-full justify-start h-8", directionFilter === 'all' && "bg-accent")}
                                onClick={() => setDirectionFilter('all')}
                            >
                                All Directions
                            </Button>
                            <Button
                                variant="ghost"
                                size="sm"
                                className={cn("w-full justify-start gap-2 h-8", directionFilter === 'outbound' && "bg-accent")}
                                onClick={() => setDirectionFilter('outbound')}
                            >
                                <ArrowUpRight className="h-4 w-4" /> Outbound
                            </Button>
                            <Button
                                variant="ghost"
                                size="sm"
                                className={cn("w-full justify-start gap-2 h-8", directionFilter === 'inbound' && "bg-accent")}
                                onClick={() => setDirectionFilter('inbound')}
                            >
                                <ArrowDownLeft className="h-4 w-4" /> Inbound
                            </Button>
                        </PopoverContent>
                    </Popover>

                    {/* Sort Toggle */}
                    <Button
                        variant="ghost"
                        size="sm"
                        className="h-8 px-2.5 gap-1.5 text-xs"
                        onClick={() => setSortNewest(!sortNewest)}
                    >
                        <Clock className="h-3.5 w-3.5" />
                        {sortNewest ? 'Newest' : 'Oldest'}
                    </Button>

                    {/* Clear Filters */}
                    {hasActiveFilters && (
                        <Button
                            variant="ghost"
                            size="sm"
                            className="h-8 w-8 p-0 text-muted-foreground hover:text-foreground"
                            onClick={clearFilters}
                        >
                            <X className="h-4 w-4" />
                        </Button>
                    )}
                </div>
            </div>

            {/* Scrollable Timeline Content */}
            <div
                ref={scrollContainerRef}
                className="flex-1 overflow-y-auto"
                style={{ maxHeight }}
            >
                <div className="pr-4">
                    {filtered.length === 0 ? (
                        <Card className="border-dashed">
                            <CardContent className="py-12 text-center">
                                <div className="mx-auto mb-4 h-12 w-12 rounded-full bg-muted flex items-center justify-center">
                                    <MessageSquare className="h-6 w-6 text-muted-foreground" />
                                </div>
                                <h4 className="font-medium mb-1">No activities found</h4>
                                <p className="text-sm text-muted-foreground mb-4">
                                    {hasActiveFilters
                                        ? "Try adjusting your filters"
                                        : "Start logging your interactions"}
                                </p>
                                {hasActiveFilters ? (
                                    <Button variant="outline" size="sm" onClick={clearFilters}>
                                        Clear Filters
                                    </Button>
                                ) : (
                                    <Button size="sm" onClick={() => openLogDialog('call')} className="gap-2">
                                        <Phone className="h-4 w-4" />
                                        Log Your First Call
                                    </Button>
                                )}
                            </CardContent>
                        </Card>
                    ) : (
                        <div className="space-y-6 pb-4">
                            {grouped.map((group) => (
                                <div key={group.key}>
                                    {/* Day Header */}
                                    <div className="flex items-center gap-3 mb-3 sticky top-0 bg-background/95 backdrop-blur-sm py-1 z-10">
                                        <span className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
                                            {group.label}
                                        </span>
                                        <div className="flex-1 h-px bg-border" />
                                        <span className="text-xs text-muted-foreground">
                                            {group.items.length} {group.items.length === 1 ? 'item' : 'items'}
                                        </span>
                                    </div>

                                    {/* Activities */}
                                    <div className="space-y-2">
                                        {group.items.map((activity) => {
                                            const config = activityConfig[activity.type] || activityConfig.system;
                                            const catConfig = categoryConfig[activity.category];
                                            const isExpanded = expandedId === activity.id;
                                            const hasBody = Boolean(activity.body_preview);

                                            return (
                                                <div
                                                    key={activity.id}
                                                    className={cn(
                                                        "group relative rounded-lg border bg-card transition-all",
                                                        "hover:shadow-sm hover:border-border/80",
                                                        isExpanded && "ring-1 ring-primary/20"
                                                    )}
                                                >
                                                    <div
                                                        className="flex items-start gap-3 p-3 cursor-pointer"
                                                        onClick={() => hasBody && setExpandedId(isExpanded ? null : activity.id)}
                                                    >
                                                        {/* Icon */}
                                                        <div className={cn(
                                                            "flex h-8 w-8 shrink-0 items-center justify-center rounded-lg",
                                                            config.bg
                                                        )}>
                                                            <config.icon className={cn("h-4 w-4", config.color)} />
                                                        </div>

                                                        {/* Content */}
                                                        <div className="flex-1 min-w-0">
                                                            <div className="flex items-center gap-2 flex-wrap">
                                                                <span className="font-medium text-sm truncate">
                                                                    {activity.subject || config.label}
                                                                </span>

                                                                {activity.direction && (
                                                                    <span className={cn(
                                                                        "inline-flex items-center text-[10px] px-1.5 py-0.5 rounded",
                                                                        activity.direction === 'outbound'
                                                                            ? "bg-blue-500/10 text-blue-600"
                                                                            : "bg-green-500/10 text-green-600"
                                                                    )}>
                                                                        {activity.direction === 'outbound' ? (
                                                                            <><ArrowUpRight className="h-2.5 w-2.5 mr-0.5" />Out</>
                                                                        ) : (
                                                                            <><ArrowDownLeft className="h-2.5 w-2.5 mr-0.5" />In</>
                                                                        )}
                                                                    </span>
                                                                )}

                                                                <Badge
                                                                    variant="outline"
                                                                    className={cn("text-[10px] px-1.5 py-0 h-4", catConfig.class)}
                                                                >
                                                                    {catConfig.label}
                                                                </Badge>
                                                            </div>

                                                            {/* Preview or Expanded Body */}
                                                            {hasBody && (
                                                                <p className={cn(
                                                                    "text-xs text-muted-foreground mt-1",
                                                                    !isExpanded && "line-clamp-1"
                                                                )}>
                                                                    {activity.body_preview}
                                                                </p>
                                                            )}
                                                        </div>

                                                        {/* Time & Actions */}
                                                        <div className="flex items-center gap-1 shrink-0">
                                                            <span className="text-xs text-muted-foreground">
                                                                {format(new Date(activity.created_at), 'h:mm a')}
                                                            </span>

                                                            <DropdownMenu>
                                                                <DropdownMenuTrigger asChild>
                                                                    <Button
                                                                        variant="ghost"
                                                                        size="sm"
                                                                        className="h-6 w-6 p-0 opacity-0 group-hover:opacity-100"
                                                                        onClick={(e) => e.stopPropagation()}
                                                                    >
                                                                        <MoreHorizontal className="h-4 w-4" />
                                                                    </Button>
                                                                </DropdownMenuTrigger>
                                                                <DropdownMenuContent align="end" className="w-40">
                                                                    <DropdownMenuItem onClick={() => copyActivity(activity)}>
                                                                        <Copy className="h-4 w-4 mr-2" />
                                                                        Copy
                                                                    </DropdownMenuItem>
                                                                    <DropdownMenuSeparator />
                                                                    <DropdownMenuItem
                                                                        onClick={() => toast.info('Create a follow-up task from your Tasks panel')}
                                                                    >
                                                                        <Plus className="h-4 w-4 mr-2" />
                                                                        Add Follow-up
                                                                    </DropdownMenuItem>
                                                                </DropdownMenuContent>
                                                            </DropdownMenu>
                                                        </div>
                                                    </div>
                                                </div>
                                            );
                                        })}
                                    </div>
                                </div>
                            ))}

                            {/* Load More Trigger / Indicator */}
                            <div ref={loadMoreTriggerRef} className="py-4">
                                {isLoadingMore && (
                                    <div className="flex items-center justify-center gap-2">
                                        <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
                                        <span className="text-sm text-muted-foreground">Loading more...</span>
                                    </div>
                                )}
                                {hasMore && !isLoadingMore && (
                                    <div className="flex items-center justify-center">
                                        <Button
                                            variant="ghost"
                                            size="sm"
                                            onClick={loadMore}
                                            className="text-muted-foreground"
                                        >
                                            Load {Math.min(pageSize, remainingCount)} more
                                            <span className="ml-1 text-xs">
                                                ({remainingCount} remaining)
                                            </span>
                                        </Button>
                                    </div>
                                )}
                                {!hasMore && filtered.length > pageSize && (
                                    <div className="text-center text-xs text-muted-foreground">
                                        All {allFiltered.length} activities loaded
                                    </div>
                                )}
                            </div>
                        </div>
                    )}
                </div>
            </div>

            {/* Log Activity Dialog */}
            <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
                <DialogContent className="sm:max-w-md">
                    <DialogHeader>
                        <DialogTitle className="flex items-center gap-2">
                            {React.createElement(activityConfig[activityType].icon, {
                                className: cn("h-5 w-5", activityConfig[activityType].color)
                            })}
                            Log {activityConfig[activityType].label}
                        </DialogTitle>
                        <DialogDescription>
                            Record this touchpoint for your team
                        </DialogDescription>
                    </DialogHeader>

                    <div className="space-y-4 py-2">
                        {/* Direction Pills */}
                        <div className="space-y-2">
                            <Label className="text-xs">Direction</Label>
                            <div className="flex gap-2">
                                <Button
                                    type="button"
                                    variant={formData.direction === 'outbound' ? 'default' : 'outline'}
                                    size="sm"
                                    className="flex-1 gap-2"
                                    onClick={() => setFormData(prev => ({ ...prev, direction: 'outbound' }))}
                                >
                                    <ArrowUpRight className="h-4 w-4" />
                                    Outbound
                                </Button>
                                <Button
                                    type="button"
                                    variant={formData.direction === 'inbound' ? 'default' : 'outline'}
                                    size="sm"
                                    className="flex-1 gap-2"
                                    onClick={() => setFormData(prev => ({ ...prev, direction: 'inbound' }))}
                                >
                                    <ArrowDownLeft className="h-4 w-4" />
                                    Inbound
                                </Button>
                            </div>
                        </div>

                        <div className="space-y-2">
                            <Label htmlFor="subject" className="text-xs">
                                {activityType === 'email' ? 'Subject' : 'Summary'} *
                            </Label>
                            <Input
                                id="subject"
                                value={formData.subject}
                                onChange={(e) => setFormData(prev => ({ ...prev, subject: e.target.value }))}
                                placeholder={
                                    activityType === 'email'
                                        ? 'Email subject line'
                                        : activityType === 'call'
                                            ? 'e.g., Discussed pricing, sending proposal'
                                            : 'SMS content or summary'
                                }
                                autoFocus
                            />
                        </div>

                        <div className="space-y-2">
                            <Label htmlFor="body_preview" className="text-xs">
                                Notes <span className="text-muted-foreground">(optional)</span>
                            </Label>
                            <Textarea
                                id="body_preview"
                                value={formData.body_preview}
                                onChange={(e) => setFormData(prev => ({ ...prev, body_preview: e.target.value }))}
                                placeholder="Key points, outcomes, next steps..."
                                rows={3}
                                className="resize-none"
                            />
                        </div>
                    </div>

                    <DialogFooter className="gap-2 sm:gap-0">
                        <Button variant="ghost" onClick={() => setIsDialogOpen(false)}>
                            Cancel
                        </Button>
                        <Button onClick={handleLogActivity} disabled={isLogging || !formData.subject.trim()}>
                            {isLogging ? (
                                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                            ) : (
                                <Send className="mr-2 h-4 w-4" />
                            )}
                            Save Activity
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </div>
    );
}