// ContactTasksTab.tsx
import React, { useState, useMemo } from 'react';
import { format, formatDistanceToNow, isToday, isTomorrow, isPast, addDays } from 'date-fns';
import {
    Plus,
    Phone,
    Mail,
    Calendar,
    MoreHorizontal,
    CheckCircle2,
    Circle,
    Clock,
    Trash2,
    Loader2,
    AlertTriangle,
    Filter,
    SortAsc,
    SortDesc,
    ListTodo,
    Target,
    Zap,
    Edit3,
    Flag,
    CalendarClock,
    ChevronDown,
    Sparkles,
    ArrowRight,
    RotateCcw,
    GripVertical,
    X,
    MessageSquare,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Checkbox } from '@/components/ui/checkbox';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Separator } from '@/components/ui/separator';
import { Progress } from '@/components/ui/progress';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogHeader,
    DialogTitle,
    DialogFooter,
} from '@/components/ui/dialog';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
    DropdownMenuRadioGroup,
    DropdownMenuRadioItem,
    DropdownMenuLabel,
} from '@/components/ui/dropdown-menu';
import {
    Popover,
    PopoverContent,
    PopoverTrigger,
} from '@/components/ui/popover';
import {
    Tooltip,
    TooltipContent,
    TooltipProvider,
    TooltipTrigger,
} from '@/components/ui/tooltip';
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { useTasks, Task } from '@/hooks/useTasks';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';

interface ContactTasksTabProps {
    contactId: string;
    maxHeight?: string;
}

type TaskType = Task['type'];
type TaskPriority = Task['priority'];
type FilterStatus = 'all' | 'pending' | 'completed' | 'overdue';
type SortOption = 'due_date' | 'priority' | 'created_at' | 'title';

const taskTypeConfig: Record<TaskType, { icon: React.ElementType; label: string; color: string; bg: string }> = {
    call: { icon: Phone, label: 'Call', color: 'text-emerald-600', bg: 'bg-emerald-500/10' },
    email: { icon: Mail, label: 'Email', color: 'text-blue-600', bg: 'bg-blue-500/10' },
    meeting: { icon: Calendar, label: 'Meeting', color: 'text-purple-600', bg: 'bg-purple-500/10' },
    'follow-up': { icon: RotateCcw, label: 'Follow-up', color: 'text-amber-600', bg: 'bg-amber-500/10' },
    other: { icon: ListTodo, label: 'Other', color: 'text-slate-600', bg: 'bg-slate-500/10' },
};

const priorityConfig: Record<TaskPriority, { label: string; color: string; bg: string; icon: React.ElementType }> = {
    high: { label: 'High', color: 'text-red-600', bg: 'bg-red-500/10', icon: AlertTriangle },
    medium: { label: 'Medium', color: 'text-amber-600', bg: 'bg-amber-500/10', icon: Flag },
    low: { label: 'Low', color: 'text-slate-500', bg: 'bg-slate-500/10', icon: ArrowRight },
};

const quickDueDates = [
    { label: 'Today', getValue: () => new Date() },
    { label: 'Tomorrow', getValue: () => addDays(new Date(), 1) },
    { label: 'In 3 days', getValue: () => addDays(new Date(), 3) },
    { label: 'In a week', getValue: () => addDays(new Date(), 7) },
];

function getDueDateStatus(dueDate: string | null, isCompleted: boolean) {
    if (!dueDate || isCompleted) return null;

    const date = new Date(dueDate);
    const now = new Date();

    if (isPast(date) && !isToday(date)) {
        return { status: 'overdue', label: 'Overdue', class: 'text-red-600 bg-red-500/10' };
    }
    if (isToday(date)) {
        return { status: 'today', label: 'Due today', class: 'text-amber-600 bg-amber-500/10' };
    }
    if (isTomorrow(date)) {
        return { status: 'tomorrow', label: 'Due tomorrow', class: 'text-blue-600 bg-blue-500/10' };
    }
    return { status: 'upcoming', label: format(date, 'MMM d'), class: 'text-muted-foreground bg-muted' };
}

export function ContactTasksTab({ contactId, maxHeight = '500px' }: ContactTasksTabProps) {
    const { tasks, isLoading, createTask, updateTask, toggleComplete, deleteTask, isCreating, isDeleting } = useTasks(contactId);

    // Dialog states
    const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
    const [editingTask, setEditingTask] = useState<Task | null>(null);
    const [deletingTask, setDeletingTask] = useState<Task | null>(null);

    // Filter & sort states
    const [filterStatus, setFilterStatus] = useState<FilterStatus>('all');
    const [filterType, setFilterType] = useState<TaskType | 'all'>('all');
    const [sortBy, setSortBy] = useState<SortOption>('due_date');
    const [sortDesc, setSortDesc] = useState(false);
    const [showCompleted, setShowCompleted] = useState(true);

    // Form state
    const [formData, setFormData] = useState({
        title: '',
        description: '',
        type: 'other' as TaskType,
        priority: 'medium' as TaskPriority,
        due_date: '',
    });

    // Reset form
    const resetForm = () => {
        setFormData({
            title: '',
            description: '',
            type: 'other',
            priority: 'medium',
            due_date: '',
        });
    };

    // Open create dialog
    const openCreateDialog = (type?: TaskType) => {
        resetForm();
        if (type) {
            setFormData(prev => ({ ...prev, type }));
        }
        setIsCreateDialogOpen(true);
    };

    // Open edit dialog
    const openEditDialog = (task: Task) => {
        setFormData({
            title: task.title,
            description: task.description || '',
            type: task.type,
            priority: task.priority,
            due_date: task.due_date ? format(new Date(task.due_date), "yyyy-MM-dd'T'HH:mm") : '',
        });
        setEditingTask(task);
    };

    // Handle create
    const handleCreate = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!formData.title.trim()) return;

        await createTask({
            ...formData,
            contact_id: contactId,
            status: 'pending',
            completed_at: null,
            due_date: formData.due_date || null,
        });

        toast.success('Task created successfully');
        setIsCreateDialogOpen(false);
        resetForm();
    };

    // Handle update
    const handleUpdate = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!editingTask || !formData.title.trim()) return;

        await updateTask({
            ...editingTask,
            ...formData,
            due_date: formData.due_date || null,
        });

        toast.success('Task updated');
        setEditingTask(null);
        resetForm();
    };

    // Handle delete
    const handleDelete = async () => {
        if (deletingTask) {
            await deleteTask(deletingTask);
            toast.success('Task deleted');
            setDeletingTask(null);
        }
    };

    // Quick complete with undo
    const handleToggleComplete = async (task: Task) => {
        const wasCompleted = task.status === 'completed';
        await toggleComplete(task);

        toast.success(wasCompleted ? 'Task reopened' : 'Task completed!', {
            action: {
                label: 'Undo',
                onClick: () => toggleComplete({ ...task, status: wasCompleted ? 'pending' : 'completed' }),
            },
        });
    };

    // Set quick due date
    const setQuickDueDate = (date: Date) => {
        const formatted = format(date, "yyyy-MM-dd'T'HH:mm");
        setFormData(prev => ({ ...prev, due_date: formatted }));
    };

    // Statistics
    const stats = useMemo(() => {
        const total = tasks.length;
        const completed = tasks.filter(t => t.status === 'completed').length;
        const pending = total - completed;
        const overdue = tasks.filter(t => {
            if (t.status === 'completed' || !t.due_date) return false;
            return isPast(new Date(t.due_date)) && !isToday(new Date(t.due_date));
        }).length;
        const dueToday = tasks.filter(t => {
            if (t.status === 'completed' || !t.due_date) return false;
            return isToday(new Date(t.due_date));
        }).length;

        const completionRate = total > 0 ? Math.round((completed / total) * 100) : 0;

        return { total, completed, pending, overdue, dueToday, completionRate };
    }, [tasks]);

    // Filtered and sorted tasks
    const filteredTasks = useMemo(() => {
        let result = [...tasks];

        // Filter by status
        if (filterStatus === 'pending') {
            result = result.filter(t => t.status === 'pending');
        } else if (filterStatus === 'completed') {
            result = result.filter(t => t.status === 'completed');
        } else if (filterStatus === 'overdue') {
            result = result.filter(t => {
                if (t.status === 'completed' || !t.due_date) return false;
                return isPast(new Date(t.due_date)) && !isToday(new Date(t.due_date));
            });
        }

        // Filter by type
        if (filterType !== 'all') {
            result = result.filter(t => t.type === filterType);
        }

        // Hide completed if toggled
        if (!showCompleted && filterStatus !== 'completed') {
            result = result.filter(t => t.status !== 'completed');
        }

        // Sort
        result.sort((a, b) => {
            let comparison = 0;

            switch (sortBy) {
                case 'due_date':
                    const aDate = a.due_date ? new Date(a.due_date).getTime() : Infinity;
                    const bDate = b.due_date ? new Date(b.due_date).getTime() : Infinity;
                    comparison = aDate - bDate;
                    break;
                case 'priority':
                    const priorityOrder = { high: 0, medium: 1, low: 2 };
                    comparison = priorityOrder[a.priority] - priorityOrder[b.priority];
                    break;
                case 'created_at':
                    comparison = new Date(a.created_at).getTime() - new Date(b.created_at).getTime();
                    break;
                case 'title':
                    comparison = a.title.localeCompare(b.title);
                    break;
            }

            return sortDesc ? -comparison : comparison;
        });

        // Always show pending before completed (unless specifically filtering)
        if (filterStatus === 'all' && showCompleted) {
            const pending = result.filter(t => t.status === 'pending');
            const completed = result.filter(t => t.status === 'completed');
            result = [...pending, ...completed];
        }

        return result;
    }, [tasks, filterStatus, filterType, sortBy, sortDesc, showCompleted]);

    const hasActiveFilters = filterStatus !== 'all' || filterType !== 'all' || !showCompleted;

    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 tasks...</span>
                </div>
            </div>
        );
    }

    return (
        <div className="flex flex-col h-full">
            {/* Header with Stats */}
            <div className="flex-shrink-0 space-y-4 pb-4">
                {/* Title Row */}
                <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                        <div className="h-9 w-9 rounded-lg bg-primary/10 flex items-center justify-center">
                            <Target className="h-5 w-5 text-primary" />
                        </div>
                        <div>
                            <h3 className="text-base font-semibold">Tasks</h3>
                            <p className="text-xs text-muted-foreground">
                                {stats.pending} pending · {stats.completed} done
                            </p>
                        </div>
                    </div>

                    <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                            <Button size="sm" className="gap-2">
                                <Plus className="h-4 w-4" />
                                New Task
                                <ChevronDown className="h-3 w-3 opacity-50" />
                            </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end" className="w-48">
                            <DropdownMenuItem onClick={() => openCreateDialog()}>
                                <ListTodo className="h-4 w-4 mr-2" />
                                General Task
                            </DropdownMenuItem>
                            <DropdownMenuSeparator />
                            <DropdownMenuLabel className="text-xs">Quick Create</DropdownMenuLabel>
                            {Object.entries(taskTypeConfig).map(([type, config]) => (
                                <DropdownMenuItem
                                    key={type}
                                    onClick={() => openCreateDialog(type as TaskType)}
                                    className="gap-2"
                                >
                                    <config.icon className={cn("h-4 w-4", config.color)} />
                                    {config.label}
                                </DropdownMenuItem>
                            ))}
                        </DropdownMenuContent>
                    </DropdownMenu>
                </div>

                {/* Progress & Quick Stats */}
                {stats.total > 0 && (
                    <div className="space-y-2">
                        <div className="flex items-center justify-between text-xs">
                            <span className="text-muted-foreground">Completion</span>
                            <span className="font-medium">{stats.completionRate}%</span>
                        </div>
                        <Progress value={stats.completionRate} className="h-1.5" />

                        {/* Alert badges */}
                        <div className="flex items-center gap-2 flex-wrap">
                            {stats.overdue > 0 && (
                                <Badge
                                    variant="outline"
                                    className="text-red-600 border-red-200 bg-red-50 gap-1 cursor-pointer hover:bg-red-100"
                                    onClick={() => setFilterStatus('overdue')}
                                >
                                    <AlertTriangle className="h-3 w-3" />
                                    {stats.overdue} overdue
                                </Badge>
                            )}
                            {stats.dueToday > 0 && (
                                <Badge
                                    variant="outline"
                                    className="text-amber-600 border-amber-200 bg-amber-50 gap-1"
                                >
                                    <Clock className="h-3 w-3" />
                                    {stats.dueToday} due today
                                </Badge>
                            )}
                        </div>
                    </div>
                )}

                {/* Filters Bar */}
                <div className="flex items-center gap-2 flex-wrap">
                    {/* Status Filter */}
                    <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                            <Button
                                variant="outline"
                                size="sm"
                                className={cn(
                                    "h-8 gap-1.5 text-xs",
                                    filterStatus !== 'all' && "bg-primary/10 border-primary/20"
                                )}
                            >
                                <Filter className="h-3.5 w-3.5" />
                                {filterStatus === 'all' ? 'All Status' : filterStatus.charAt(0).toUpperCase() + filterStatus.slice(1)}
                            </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="start">
                            <DropdownMenuRadioGroup value={filterStatus} onValueChange={(v) => setFilterStatus(v as FilterStatus)}>
                                <DropdownMenuRadioItem value="all">All Tasks</DropdownMenuRadioItem>
                                <DropdownMenuRadioItem value="pending">Pending</DropdownMenuRadioItem>
                                <DropdownMenuRadioItem value="completed">Completed</DropdownMenuRadioItem>
                                <DropdownMenuRadioItem value="overdue">Overdue</DropdownMenuRadioItem>
                            </DropdownMenuRadioGroup>
                        </DropdownMenuContent>
                    </DropdownMenu>

                    {/* Type Filter */}
                    <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                            <Button
                                variant="outline"
                                size="sm"
                                className={cn(
                                    "h-8 gap-1.5 text-xs",
                                    filterType !== 'all' && "bg-primary/10 border-primary/20"
                                )}
                            >
                                {filterType !== 'all' ? (
                                    <>
                                        {React.createElement(taskTypeConfig[filterType].icon, {
                                            className: cn("h-3.5 w-3.5", taskTypeConfig[filterType].color)
                                        })}
                                        {taskTypeConfig[filterType].label}
                                    </>
                                ) : (
                                    <>
                                        <ListTodo className="h-3.5 w-3.5" />
                                        All Types
                                    </>
                                )}
                            </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="start">
                            <DropdownMenuRadioGroup value={filterType} onValueChange={(v) => setFilterType(v as TaskType | 'all')}>
                                <DropdownMenuRadioItem value="all">All Types</DropdownMenuRadioItem>
                                <DropdownMenuSeparator />
                                {Object.entries(taskTypeConfig).map(([type, config]) => (
                                    <DropdownMenuRadioItem key={type} value={type} className="gap-2">
                                        <config.icon className={cn("h-4 w-4", config.color)} />
                                        {config.label}
                                    </DropdownMenuRadioItem>
                                ))}
                            </DropdownMenuRadioGroup>
                        </DropdownMenuContent>
                    </DropdownMenu>

                    {/* Sort */}
                    <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                            <Button variant="outline" size="sm" className="h-8 gap-1.5 text-xs">
                                {sortDesc ? <SortDesc className="h-3.5 w-3.5" /> : <SortAsc className="h-3.5 w-3.5" />}
                                Sort
                            </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="start">
                            <DropdownMenuRadioGroup value={sortBy} onValueChange={(v) => setSortBy(v as SortOption)}>
                                <DropdownMenuRadioItem value="due_date">Due Date</DropdownMenuRadioItem>
                                <DropdownMenuRadioItem value="priority">Priority</DropdownMenuRadioItem>
                                <DropdownMenuRadioItem value="created_at">Created</DropdownMenuRadioItem>
                                <DropdownMenuRadioItem value="title">Title</DropdownMenuRadioItem>
                            </DropdownMenuRadioGroup>
                            <DropdownMenuSeparator />
                            <DropdownMenuItem onClick={() => setSortDesc(!sortDesc)}>
                                {sortDesc ? (
                                    <><SortAsc className="h-4 w-4 mr-2" /> Ascending</>
                                ) : (
                                    <><SortDesc className="h-4 w-4 mr-2" /> Descending</>
                                )}
                            </DropdownMenuItem>
                        </DropdownMenuContent>
                    </DropdownMenu>

                    {/* Show Completed Toggle */}
                    <div className="flex items-center gap-2 ml-auto">
                        <Checkbox
                            id="show-completed"
                            checked={showCompleted}
                            onCheckedChange={(checked) => setShowCompleted(!!checked)}
                        />
                        <Label htmlFor="show-completed" className="text-xs text-muted-foreground cursor-pointer">
                            Show completed
                        </Label>
                    </div>

                    {/* Clear Filters */}
                    {hasActiveFilters && (
                        <Button
                            variant="ghost"
                            size="sm"
                            className="h-8 px-2 text-xs"
                            onClick={() => {
                                setFilterStatus('all');
                                setFilterType('all');
                                setShowCompleted(true);
                            }}
                        >
                            <X className="h-3.5 w-3.5 mr-1" />
                            Clear
                        </Button>
                    )}
                </div>
            </div>

            {/* Scrollable Task List */}
            <ScrollArea className="flex-1" style={{ maxHeight }}>
                <div className="pr-4 space-y-2 pb-4">
                    {filteredTasks.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">
                                    {hasActiveFilters ? (
                                        <Filter className="h-6 w-6 text-muted-foreground" />
                                    ) : (
                                        <Sparkles className="h-6 w-6 text-muted-foreground" />
                                    )}
                                </div>
                                <h4 className="font-medium mb-1">
                                    {hasActiveFilters ? 'No matching tasks' : 'No tasks yet'}
                                </h4>
                                <p className="text-sm text-muted-foreground mb-4">
                                    {hasActiveFilters
                                        ? 'Try adjusting your filters'
                                        : 'Create a task to track follow-ups and actions'}
                                </p>
                                {hasActiveFilters ? (
                                    <Button
                                        variant="outline"
                                        size="sm"
                                        onClick={() => {
                                            setFilterStatus('all');
                                            setFilterType('all');
                                            setShowCompleted(true);
                                        }}
                                    >
                                        Clear Filters
                                    </Button>
                                ) : (
                                    <Button size="sm" onClick={() => openCreateDialog('call')} className="gap-2">
                                        <Phone className="h-4 w-4" />
                                        Schedule a Call
                                    </Button>
                                )}
                            </CardContent>
                        </Card>
                    ) : (
                        filteredTasks.map((task) => {
                            const typeConfig = taskTypeConfig[task.type];
                            const prioConfig = priorityConfig[task.priority];
                            const isCompleted = task.status === 'completed';
                            const dueStatus = getDueDateStatus(task.due_date, isCompleted);

                            return (
                                <div
                                    key={task.id}
                                    className={cn(
                                        "group relative rounded-lg border bg-card transition-all",
                                        "hover:shadow-sm hover:border-border/80",
                                        isCompleted && "opacity-60"
                                    )}
                                >
                                    <div className="flex items-start gap-3 p-3">
                                        {/* Checkbox */}
                                        <TooltipProvider>
                                            <Tooltip>
                                                <TooltipTrigger asChild>
                                                    <button
                                                        className="mt-0.5 shrink-0 transition-colors"
                                                        onClick={() => handleToggleComplete(task)}
                                                    >
                                                        {isCompleted ? (
                                                            <CheckCircle2 className="h-5 w-5 text-green-500" />
                                                        ) : (
                                                            <Circle className="h-5 w-5 text-muted-foreground hover:text-primary" />
                                                        )}
                                                    </button>
                                                </TooltipTrigger>
                                                <TooltipContent>
                                                    {isCompleted ? 'Mark as pending' : 'Mark as complete'}
                                                </TooltipContent>
                                            </Tooltip>
                                        </TooltipProvider>

                                        {/* Content */}
                                        <div className="flex-1 min-w-0">
                                            <div className="flex items-center gap-2 flex-wrap">
                                                {/* Type Icon */}
                                                <div className={cn(
                                                    "h-5 w-5 rounded flex items-center justify-center shrink-0",
                                                    typeConfig.bg
                                                )}>
                                                    <typeConfig.icon className={cn("h-3 w-3", typeConfig.color)} />
                                                </div>

                                                {/* Title */}
                                                <span className={cn(
                                                    "font-medium text-sm",
                                                    isCompleted && "line-through text-muted-foreground"
                                                )}>
                                                    {task.title}
                                                </span>

                                                {/* Priority Badge */}
                                                <Badge
                                                    variant="outline"
                                                    className={cn(
                                                        "text-[10px] px-1.5 py-0 h-4 gap-0.5",
                                                        prioConfig.bg,
                                                        prioConfig.color,
                                                        "border-transparent"
                                                    )}
                                                >
                                                    <prioConfig.icon className="h-2.5 w-2.5" />
                                                    {prioConfig.label}
                                                </Badge>
                                            </div>

                                            {/* Description */}
                                            {task.description && (
                                                <p className="text-xs text-muted-foreground mt-1 line-clamp-2">
                                                    {task.description}
                                                </p>
                                            )}

                                            {/* Meta Row */}
                                            <div className="flex items-center gap-3 mt-2">
                                                {/* Due Date */}
                                                {dueStatus && (
                                                    <Badge
                                                        variant="outline"
                                                        className={cn(
                                                            "text-[10px] px-1.5 py-0 h-4 gap-1 border-transparent",
                                                            dueStatus.class
                                                        )}
                                                    >
                                                        <Clock className="h-2.5 w-2.5" />
                                                        {dueStatus.label}
                                                    </Badge>
                                                )}

                                                {/* Completed Time */}
                                                {isCompleted && task.completed_at && (
                                                    <span className="text-[10px] text-muted-foreground flex items-center gap-1">
                                                        <CheckCircle2 className="h-3 w-3" />
                                                        Completed {formatDistanceToNow(new Date(task.completed_at), { addSuffix: true })}
                                                    </span>
                                                )}
                                            </div>
                                        </div>

                                        {/* Actions */}
                                        <div className="flex items-center gap-1 shrink-0 opacity-0 group-hover:opacity-100 transition-opacity">
                                            <TooltipProvider>
                                                <Tooltip>
                                                    <TooltipTrigger asChild>
                                                        <Button
                                                            variant="ghost"
                                                            size="sm"
                                                            className="h-7 w-7 p-0"
                                                            onClick={() => openEditDialog(task)}
                                                        >
                                                            <Edit3 className="h-3.5 w-3.5" />
                                                        </Button>
                                                    </TooltipTrigger>
                                                    <TooltipContent>Edit</TooltipContent>
                                                </Tooltip>
                                            </TooltipProvider>

                                            <TooltipProvider>
                                                <Tooltip>
                                                    <TooltipTrigger asChild>
                                                        <Button
                                                            variant="ghost"
                                                            size="sm"
                                                            className="h-7 w-7 p-0 text-muted-foreground hover:text-destructive"
                                                            onClick={() => setDeletingTask(task)}
                                                        >
                                                            <Trash2 className="h-3.5 w-3.5" />
                                                        </Button>
                                                    </TooltipTrigger>
                                                    <TooltipContent>Delete</TooltipContent>
                                                </Tooltip>
                                            </TooltipProvider>
                                        </div>
                                    </div>
                                </div>
                            );
                        })
                    )}
                </div>
            </ScrollArea>

            {/* Create Task Dialog */}
            <Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
                <DialogContent className="sm:max-w-lg">
                    <DialogHeader>
                        <DialogTitle className="flex items-center gap-2">
                            <div className={cn(
                                "h-8 w-8 rounded-lg flex items-center justify-center",
                                taskTypeConfig[formData.type].bg
                            )}>
                                {React.createElement(taskTypeConfig[formData.type].icon, {
                                    className: cn("h-4 w-4", taskTypeConfig[formData.type].color)
                                })}
                            </div>
                            Create New Task
                        </DialogTitle>
                        <DialogDescription>
                            Add a task for this contact
                        </DialogDescription>
                    </DialogHeader>

                    <form onSubmit={handleCreate} className="space-y-4">
                        {/* Title */}
                        <div className="space-y-2">
                            <Label htmlFor="title">Title *</Label>
                            <Input
                                id="title"
                                value={formData.title}
                                onChange={(e) => setFormData(prev => ({ ...prev, title: e.target.value }))}
                                placeholder="e.g., Follow up on proposal"
                                autoFocus
                            />
                        </div>

                        {/* Description */}
                        <div className="space-y-2">
                            <Label htmlFor="description">
                                Description <span className="text-muted-foreground">(optional)</span>
                            </Label>
                            <Textarea
                                id="description"
                                value={formData.description}
                                onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
                                placeholder="Add more details..."
                                rows={3}
                                className="resize-none"
                            />
                        </div>

                        {/* Type & Priority */}
                        <div className="grid grid-cols-2 gap-4">
                            <div className="space-y-2">
                                <Label>Type</Label>
                                <Select
                                    value={formData.type}
                                    onValueChange={(value: TaskType) => setFormData(prev => ({ ...prev, type: value }))}
                                >
                                    <SelectTrigger>
                                        <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {Object.entries(taskTypeConfig).map(([type, config]) => (
                                            <SelectItem key={type} value={type}>
                                                <div className="flex items-center gap-2">
                                                    <config.icon className={cn("h-4 w-4", config.color)} />
                                                    {config.label}
                                                </div>
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </div>

                            <div className="space-y-2">
                                <Label>Priority</Label>
                                <Select
                                    value={formData.priority}
                                    onValueChange={(value: TaskPriority) => setFormData(prev => ({ ...prev, priority: value }))}
                                >
                                    <SelectTrigger>
                                        <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {Object.entries(priorityConfig).map(([priority, config]) => (
                                            <SelectItem key={priority} value={priority}>
                                                <div className="flex items-center gap-2">
                                                    <config.icon className={cn("h-4 w-4", config.color)} />
                                                    {config.label}
                                                </div>
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </div>
                        </div>

                        {/* Due Date */}
                        <div className="space-y-2">
                            <Label htmlFor="due_date">Due Date</Label>
                            <div className="flex gap-2">
                                <Input
                                    id="due_date"
                                    type="datetime-local"
                                    value={formData.due_date}
                                    onChange={(e) => setFormData(prev => ({ ...prev, due_date: e.target.value }))}
                                    className="flex-1"
                                />
                                {formData.due_date && (
                                    <Button
                                        type="button"
                                        variant="ghost"
                                        size="icon"
                                        onClick={() => setFormData(prev => ({ ...prev, due_date: '' }))}
                                    >
                                        <X className="h-4 w-4" />
                                    </Button>
                                )}
                            </div>

                            {/* Quick Date Buttons */}
                            <div className="flex items-center gap-1.5 flex-wrap">
                                <span className="text-[10px] text-muted-foreground mr-1">Quick:</span>
                                {quickDueDates.map((qd) => (
                                    <Button
                                        key={qd.label}
                                        type="button"
                                        variant="outline"
                                        size="sm"
                                        className="h-6 px-2 text-[10px]"
                                        onClick={() => setQuickDueDate(qd.getValue())}
                                    >
                                        {qd.label}
                                    </Button>
                                ))}
                            </div>
                        </div>

                        <DialogFooter className="gap-2 sm:gap-0">
                            <Button
                                type="button"
                                variant="ghost"
                                onClick={() => setIsCreateDialogOpen(false)}
                            >
                                Cancel
                            </Button>
                            <Button type="submit" disabled={isCreating || !formData.title.trim()}>
                                {isCreating ? (
                                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                                ) : (
                                    <Plus className="mr-2 h-4 w-4" />
                                )}
                                Create Task
                            </Button>
                        </DialogFooter>
                    </form>
                </DialogContent>
            </Dialog>

            {/* Edit Task Dialog */}
            <Dialog open={!!editingTask} onOpenChange={(open) => !open && setEditingTask(null)}>
                <DialogContent className="sm:max-w-lg">
                    <DialogHeader>
                        <DialogTitle>Edit Task</DialogTitle>
                    </DialogHeader>

                    <form onSubmit={handleUpdate} className="space-y-4">
                        <div className="space-y-2">
                            <Label htmlFor="edit-title">Title *</Label>
                            <Input
                                id="edit-title"
                                value={formData.title}
                                onChange={(e) => setFormData(prev => ({ ...prev, title: e.target.value }))}
                                autoFocus
                            />
                        </div>

                        <div className="space-y-2">
                            <Label htmlFor="edit-description">Description</Label>
                            <Textarea
                                id="edit-description"
                                value={formData.description}
                                onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
                                rows={3}
                                className="resize-none"
                            />
                        </div>

                        <div className="grid grid-cols-2 gap-4">
                            <div className="space-y-2">
                                <Label>Type</Label>
                                <Select
                                    value={formData.type}
                                    onValueChange={(value: TaskType) => setFormData(prev => ({ ...prev, type: value }))}
                                >
                                    <SelectTrigger>
                                        <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {Object.entries(taskTypeConfig).map(([type, config]) => (
                                            <SelectItem key={type} value={type}>
                                                <div className="flex items-center gap-2">
                                                    <config.icon className={cn("h-4 w-4", config.color)} />
                                                    {config.label}
                                                </div>
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </div>

                            <div className="space-y-2">
                                <Label>Priority</Label>
                                <Select
                                    value={formData.priority}
                                    onValueChange={(value: TaskPriority) => setFormData(prev => ({ ...prev, priority: value }))}
                                >
                                    <SelectTrigger>
                                        <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {Object.entries(priorityConfig).map(([priority, config]) => (
                                            <SelectItem key={priority} value={priority}>
                                                <div className="flex items-center gap-2">
                                                    <config.icon className={cn("h-4 w-4", config.color)} />
                                                    {config.label}
                                                </div>
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </div>
                        </div>

                        <div className="space-y-2">
                            <Label htmlFor="edit-due_date">Due Date</Label>
                            <div className="flex gap-2">
                                <Input
                                    id="edit-due_date"
                                    type="datetime-local"
                                    value={formData.due_date}
                                    onChange={(e) => setFormData(prev => ({ ...prev, due_date: e.target.value }))}
                                    className="flex-1"
                                />
                                {formData.due_date && (
                                    <Button
                                        type="button"
                                        variant="ghost"
                                        size="icon"
                                        onClick={() => setFormData(prev => ({ ...prev, due_date: '' }))}
                                    >
                                        <X className="h-4 w-4" />
                                    </Button>
                                )}
                            </div>
                        </div>

                        <DialogFooter className="gap-2 sm:gap-0">
                            <Button type="button" variant="ghost" onClick={() => setEditingTask(null)}>
                                Cancel
                            </Button>
                            <Button type="submit" disabled={!formData.title.trim()}>
                                <CheckCircle2 className="mr-2 h-4 w-4" />
                                Save Changes
                            </Button>
                        </DialogFooter>
                    </form>
                </DialogContent>
            </Dialog>

            {/* Delete Confirmation */}
            <AlertDialog open={!!deletingTask} onOpenChange={(open) => !open && setDeletingTask(null)}>
                <AlertDialogContent>
                    <AlertDialogHeader>
                        <AlertDialogTitle>Delete Task</AlertDialogTitle>
                        <AlertDialogDescription>
                            Are you sure you want to delete "{deletingTask?.title}"? This action cannot be undone.
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel>Cancel</AlertDialogCancel>
                        <AlertDialogAction
                            onClick={handleDelete}
                            className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                        >
                            {isDeleting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                            Delete
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>
        </div>
    );
}