import React, { useId, useMemo, useState } from 'react';
import { Link, useNavigate, useParams } from 'react-router-dom';
import { differenceInDays, formatDistanceToNow, isValid, parseISO } from 'date-fns';
import { motion, AnimatePresence } from 'framer-motion';
import {
    Activity,
    ArrowLeft,
    ArrowRight,
    Building2,
    Calendar,
    CalendarPlus,
    Camera,
    CheckCircle2,
    Circle,
    Clock,
    Copy,
    Edit2,
    Flame,
    FileText,
    Gauge,
    LinkIcon,
    ListTodo,
    Loader2,
    Mail,
    MoreVertical,
    Paperclip,
    Phone,
    Settings2,
    Shield,
    Sparkles,
    Star,
    Tag,
    Target,
    Trash2,
    TrendingUp,
    UserCircle,
    Zap,
    ChevronRight,
} from 'lucide-react';

import { Button } from '@/components/ui/button';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';

import { ContactNotesTab } from '@/components/contacts/ContactNotesTab';
import { ContactTasksTab } from '@/components/contacts/ContactTasksTab';
import { ContactActivitiesTab } from '@/components/contacts/ContactActivitiesTab';
import { ContactAttachmentsTab } from '@/components/contacts/ContactAttachmentsTab';
import { ContactCustomFieldsTab } from '@/components/contacts/ContactCustomFieldsTab';
import { ContactFormDialog } from '@/components/contacts/ContactFormDialog';
import { ContactTagsManager } from '@/components/contacts/ContactTagsManager';
import { ContactAvatarUpload } from '@/components/contacts/ContactAvatarUpload';
import { SendEmailDialog } from '@/components/contacts/SendEmailDialog';

import { useContact, usePipelineStages, usePipelines } from '@/hooks/useContact';
import { useTrashedContacts } from '@/hooks/useTrash';
import { ContactWithTags } from '@/hooks/useContacts';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';

// Status configuration
const statusConfig = {
    lead: {
        color: 'bg-violet-500',
        bgLight: 'bg-violet-500/10',
        border: 'border-violet-500/30',
        text: 'text-violet-600',
        gradient: 'from-violet-500 via-purple-500 to-fuchsia-500',
        icon: Sparkles,
        label: 'Lead',
    },
    prospect: {
        color: 'bg-amber-500',
        bgLight: 'bg-amber-500/10',
        border: 'border-amber-500/30',
        text: 'text-amber-600',
        gradient: 'from-amber-500 via-orange-500 to-red-500',
        icon: Target,
        label: 'Prospect',
    },
    customer: {
        color: 'bg-emerald-500',
        bgLight: 'bg-emerald-500/10',
        border: 'border-emerald-500/30',
        text: 'text-emerald-600',
        gradient: 'from-emerald-500 via-green-500 to-teal-500',
        icon: CheckCircle2,
        label: 'Customer',
    },
    churned: {
        color: 'bg-slate-400',
        bgLight: 'bg-slate-400/10',
        border: 'border-slate-400/30',
        text: 'text-slate-500',
        gradient: 'from-slate-400 via-slate-500 to-slate-600',
        icon: Clock,
        label: 'Churned',
    },
};

// Engagement calculation
function calculateEngagementScore(contact: any): number {
    let score = 50;
    if (contact.email) score += 10;
    if (contact.phone) score += 10;
    if (contact.company) score += 5;
    if (contact.tags?.length > 0) score += contact.tags.length * 3;
    if (contact.pipeline_id) score += 10;
    if (contact.stage_id) score += 5;
    return Math.min(score, 100);
}

function getEngagementLevel(score: number) {
    if (score >= 80) return { label: 'Hot', color: 'text-rose-500', bg: 'bg-rose-500', icon: Flame };
    if (score >= 60) return { label: 'Warm', color: 'text-amber-500', bg: 'bg-amber-500', icon: TrendingUp };
    if (score >= 40) return { label: 'Cool', color: 'text-sky-500', bg: 'bg-sky-500', icon: Activity };
    return { label: 'Cold', color: 'text-slate-400', bg: 'bg-slate-400', icon: Circle };
}

// Circular Progress
function CircularProgress({
    value,
    size = 64,
    strokeWidth = 6,
    children,
}: {
    value: number;
    size?: number;
    strokeWidth?: number;
    children?: React.ReactNode;
}) {
    const radius = (size - strokeWidth) / 2;
    const circumference = radius * 2 * Math.PI;
    const offset = circumference - (value / 100) * circumference;

    // Avoid duplicate gradient IDs if component renders multiple times
    const gradientId = useId();

    return (
        <div className="relative inline-flex items-center justify-center">
            <svg width={size} height={size} className="-rotate-90">
                <circle
                    cx={size / 2}
                    cy={size / 2}
                    r={radius}
                    fill="none"
                    stroke="currentColor"
                    strokeWidth={strokeWidth}
                    className="text-muted/20"
                />
                <circle
                    cx={size / 2}
                    cy={size / 2}
                    r={radius}
                    fill="none"
                    stroke={`url(#${gradientId})`}
                    strokeWidth={strokeWidth}
                    strokeLinecap="round"
                    strokeDasharray={circumference}
                    strokeDashoffset={offset}
                    className="transition-all duration-700 ease-out"
                />
                <defs>
                    <linearGradient id={gradientId} x1="0%" y1="0%" x2="100%" y2="100%">
                        <stop offset="0%" stopColor="hsl(var(--primary))" />
                        <stop offset="100%" stopColor="hsl(280, 100%, 60%)" />
                    </linearGradient>
                </defs>
            </svg>
            <div className="absolute inset-0 flex items-center justify-center">{children}</div>
        </div>
    );
}

// Action Button Component
function ActionButton({
    icon: Icon,
    label,
    onClick,
    variant = 'default',
    disabled,
    className,
}: {
    icon: React.ElementType;
    label: string;
    onClick?: () => void;
    variant?: 'default' | 'primary' | 'success' | 'warning';
    disabled?: boolean;
    className?: string;
}) {
    const variants = {
        default: 'bg-muted/60 hover:bg-muted text-foreground border-transparent',
        primary: 'bg-primary/10 hover:bg-primary/20 text-primary border-primary/20',
        success: 'bg-emerald-500/10 hover:bg-emerald-500/20 text-emerald-600 border-emerald-500/20',
        warning: 'bg-amber-500/10 hover:bg-amber-500/20 text-amber-600 border-amber-500/20',
    };

    return (
        <Tooltip>
            <TooltipTrigger asChild>
                <motion.button
                    whileHover={{ scale: 1.02 }}
                    whileTap={{ scale: 0.98 }}
                    onClick={onClick}
                    disabled={disabled}
                    className={cn(
                        'flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl border transition-all duration-200',
                        'disabled:opacity-50 disabled:cursor-not-allowed font-medium text-sm',
                        variants[variant],
                        className,
                    )}
                >
                    <Icon className="h-4 w-4" />
                    <span className="hidden sm:inline">{label}</span>
                </motion.button>
            </TooltipTrigger>
            <TooltipContent side="bottom" className="sm:hidden">
                <p>{label}</p>
            </TooltipContent>
        </Tooltip>
    );
}

// Info Pill Component
function InfoPill({
    icon: Icon,
    text,
    variant = 'default',
}: {
    icon: React.ElementType;
    text: string;
    variant?: 'default' | 'warning' | 'success';
}) {
    const variants = {
        default: 'bg-muted/70 text-muted-foreground',
        warning: 'bg-amber-500/10 text-amber-600',
        success: 'bg-emerald-500/10 text-emerald-600',
    };

    return (
        <div className={cn('inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium', variants[variant])}>
            <Icon className="h-3.5 w-3.5" />
            {text}
        </div>
    );
}

// Stage Dot Indicator
function StageDots({ stages, currentIndex }: { stages: any[]; currentIndex: number }) {
    return (
        <div className="flex items-center gap-1">
            {stages.map((stage, idx) => (
                <div
                    key={stage.id}
                    className={cn(
                        'h-2 rounded-full transition-all duration-300',
                        idx <= currentIndex ? 'bg-primary' : 'bg-muted',
                        idx === currentIndex ? 'w-6' : 'w-2',
                    )}
                    style={idx <= currentIndex && stage.color ? { backgroundColor: stage.color } : undefined}
                />
            ))}
        </div>
    );
}

function LoadingSkeleton() {
    return (
        <div className="min-h-screen bg-background">
            <div className="animate-pulse">
                <div className="h-16 border-b bg-muted/30" />
                <div className="p-6 space-y-6 max-w-7xl mx-auto">
                    <div className="h-56 bg-muted/50 rounded-2xl" />
                    <div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
                        <div className="xl:col-span-2 h-[500px] bg-muted/50 rounded-2xl" />
                        <div className="space-y-6">
                            <div className="h-48 bg-muted/50 rounded-2xl" />
                            <div className="h-64 bg-muted/50 rounded-2xl" />
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}

function ContactNotFound() {
    const navigate = useNavigate();
    return (
        <div className="min-h-screen flex items-center justify-center p-6 bg-background">
            <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} className="max-w-md text-center">
                <div className="mx-auto mb-6 h-20 w-20 rounded-2xl bg-muted flex items-center justify-center">
                    <UserCircle className="h-10 w-10 text-muted-foreground" />
                </div>
                <h2 className="text-2xl font-bold">Contact not found</h2>
                <p className="text-muted-foreground mt-2">This contact may have been deleted or you don't have access.</p>
                <div className="flex items-center justify-center gap-3 mt-6">
                    <Button variant="outline" onClick={() => navigate(-1)}>
                        <ArrowLeft className="h-4 w-4 mr-2" />
                        Go back
                    </Button>
                    <Button onClick={() => navigate('/contacts')}>All contacts</Button>
                </div>
            </motion.div>
        </div>
    );
}

/**
 * Wrapper component:
 * Only calls hooks that are safe regardless of whether the contact is loaded.
 * This avoids the "Rendered more hooks than during the previous render" crash.
 */
export default function ContactDetail() {
    const { id } = useParams<{ id: string }>();

    const contactId = id ?? '';
    const { contact, isLoading, updateContact, isUpdating } = useContact(contactId);

    // These hooks are safe to run even while contact loads.
    const { softDelete, isSoftDeleting } = useTrashedContacts();
    const { data: pipelines = [] } = usePipelines();

    if (isLoading) return <LoadingSkeleton />;
    if (!contact) return <ContactNotFound />;

    return (
        <ContactDetailView
            id={contactId}
            contact={contact}
            pipelines={pipelines}
            updateContact={updateContact}
            isUpdating={isUpdating}
            softDelete={softDelete}
            isSoftDeleting={isSoftDeleting}
        />
    );
}

function ContactDetailView({
    id,
    contact,
    pipelines,
    updateContact,
    isUpdating,
    softDelete,
    isSoftDeleting,
}: {
    id: string;
    contact: any;
    pipelines: any[];
    updateContact: (data: any) => Promise<any>;
    isUpdating: boolean;
    softDelete: (args: { contactId: string; deletedFrom: string }) => Promise<any>;
    isSoftDeleting: boolean;
}) {
    const navigate = useNavigate();

    // Runs only when contact exists (component is mounted), so no hook-order mismatch.
    const { data: stages = [] } = usePipelineStages(contact.pipeline_id);

    const [activeTab, setActiveTab] = useState<'timeline' | 'tasks' | 'notes' | 'files' | 'custom'>('timeline');
    const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
    const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
    const [isEmailDialogOpen, setIsEmailDialogOpen] = useState(false);
    const [isAvatarDialogOpen, setIsAvatarDialogOpen] = useState(false);
    const [isPinned, setIsPinned] = useState(false);

    const fullName = useMemo(() => {
        const name = `${contact.first_name ?? ''} ${contact.last_name ?? ''}`.trim();
        return name || 'Unnamed Contact';
    }, [contact.first_name, contact.last_name]);

    const initials = useMemo(() => {
        const first = (contact.first_name ?? ' ')[0] ?? '';
        const last = (contact.last_name ?? ' ')[0] ?? '';
        return `${first}${last}`.toUpperCase().trim() || '?';
    }, [contact.first_name, contact.last_name]);

    const statusInfo =
        statusConfig[contact.status as keyof typeof statusConfig] ?? statusConfig.lead;
    const StatusIcon = statusInfo.icon;

    const engagementScore = useMemo(() => calculateEngagementScore(contact), [contact]);
    const engagementLevel = useMemo(() => getEngagementLevel(engagementScore), [engagementScore]);
    const EngagementIcon = engagementLevel.icon;

    // Safe created_at parsing (prevents date-fns "Invalid time value")
    const createdAt = useMemo(() => {
        if (!contact.created_at) return null;
        // If created_at is already a Date, keep it; else parse ISO
        const d = contact.created_at instanceof Date ? contact.created_at : parseISO(String(contact.created_at));
        return isValid(d) ? d : null;
    }, [contact.created_at]);

    const isNewContact = useMemo(() => {
        if (!createdAt) return false;
        const daysSinceCreated = differenceInDays(new Date(), createdAt);
        return daysSinceCreated <= 7;
    }, [createdAt]);

    const contactForForm: ContactWithTags = useMemo(
        () => ({
            ...contact,
            tags: contact.tags ?? [],
        }),
        [contact],
    );

    const currentStageIndex = useMemo(
        () => stages.findIndex((s: any) => s.id === contact.stage_id),
        [stages, contact.stage_id],
    );

    const currentStage = useMemo(
        () => stages.find((s: any) => s.id === contact.stage_id),
        [stages, contact.stage_id],
    );

    const currentPipeline = useMemo(
        () => pipelines.find((p: any) => p.id === contact.pipeline_id),
        [pipelines, contact.pipeline_id],
    );

    const stageProgress = useMemo(() => {
        if (!contact.pipeline_id || !stages.length) return 0;
        const idx = stages.findIndex((s: any) => s.id === contact.stage_id);
        if (idx < 0) return 0;
        return ((idx + 1) / stages.length) * 100;
    }, [contact.pipeline_id, contact.stage_id, stages]);

    const nextStage = useMemo(() => {
        if (currentStageIndex < 0) return null;
        return stages[currentStageIndex + 1] ?? null;
    }, [currentStageIndex, stages]);

    const handleCopy = async (value: string, label: string) => {
        try {
            await navigator.clipboard.writeText(value);
            toast.success(`${label} copied`);
        } catch {
            toast.error('Failed to copy');
        }
    };

    const handleDelete = async () => {
        if (!id) return;
        await softDelete({ contactId: id, deletedFrom: 'Contact Detail Page' });
        navigate('/contacts');
    };

    const handleEditSubmit = async (data: any) => {
        await updateContact(data);
        setIsEditDialogOpen(false);
    };

    const handlePipelineChange = async (pipelineId: string) => {
        await updateContact({ pipeline_id: pipelineId, stage_id: null });
        toast.success('Pipeline updated');
    };

    const handleStageChange = async (stageId: string) => {
        await updateContact({ stage_id: stageId });
        toast.success('Stage updated');
    };

    const handleAdvanceStage = async () => {
        if (!nextStage) return;
        await updateContact({ stage_id: nextStage.id });
        toast.success(`Advanced to ${nextStage.name}`);
    };

    const handleStatusChange = async (status: string) => {
        await updateContact({ status });
        toast.success('Status updated');
    };

    return (
        <TooltipProvider>
            <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="min-h-screen bg-background">
                {/* Top Navigation */}
                <div className="sticky top-0 z-50 border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
                    <div className="max-w-7xl mx-auto px-4 sm:px-6">
                        <div className="flex items-center justify-between h-16 gap-4">
                            {/* Left: Back & Breadcrumb */}
                            <div className="flex items-center gap-3 min-w-0">
                                <Button variant="ghost" size="icon" className="shrink-0" onClick={() => navigate(-1)}>
                                    <ArrowLeft className="h-4 w-4" />
                                </Button>

                                <nav className="hidden md:flex items-center gap-2 text-sm min-w-0">
                                    <Link to="/contacts" className="text-muted-foreground hover:text-foreground transition-colors">
                                        Contacts
                                    </Link>
                                    <ChevronRight className="h-4 w-4 text-muted-foreground/50 shrink-0" />
                                    <span className="font-medium truncate">{fullName}</span>
                                    {isNewContact && (
                                        <Badge variant="secondary" className="bg-emerald-500/10 text-emerald-600 shrink-0">
                                            New
                                        </Badge>
                                    )}
                                </nav>
                            </div>

                            {/* Right: Actions */}
                            <div className="flex items-center gap-2">
                                <Tooltip>
                                    <TooltipTrigger asChild>
                                        <Button
                                            variant="ghost"
                                            size="icon"
                                            className={cn(isPinned && 'text-amber-500')}
                                            onClick={() => {
                                                setIsPinned(!isPinned);
                                                toast.success(isPinned ? 'Unpinned' : 'Pinned');
                                            }}
                                        >
                                            <Star className={cn('h-4 w-4', isPinned && 'fill-current')} />
                                        </Button>
                                    </TooltipTrigger>
                                    <TooltipContent>{isPinned ? 'Unpin' : 'Pin contact'}</TooltipContent>
                                </Tooltip>

                                <Button
                                    variant="ghost"
                                    size="icon"
                                    onClick={() => {
                                        const href = typeof window !== 'undefined' ? window.location.href : '';
                                        if (href) void handleCopy(href, 'Link');
                                    }}
                                >
                                    <LinkIcon className="h-4 w-4" />
                                </Button>

                                <div className="hidden sm:flex items-center gap-2">
                                    <Button variant="outline" size="sm" onClick={() => setIsAvatarDialogOpen(true)}>
                                        <Camera className="h-4 w-4 mr-2" />
                                        Photo
                                    </Button>

                                    <Button variant="outline" size="sm" onClick={() => setIsEditDialogOpen(true)}>
                                        <Edit2 className="h-4 w-4 mr-2" />
                                        Edit
                                    </Button>

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

                                {/* Mobile dropdown */}
                                <DropdownMenu>
                                    <DropdownMenuTrigger asChild className="sm:hidden">
                                        <Button variant="ghost" size="icon">
                                            <MoreVertical className="h-4 w-4" />
                                        </Button>
                                    </DropdownMenuTrigger>
                                    <DropdownMenuContent align="end" className="w-48">
                                        <DropdownMenuItem onClick={() => setIsAvatarDialogOpen(true)}>
                                            <Camera className="h-4 w-4 mr-2" />
                                            Change photo
                                        </DropdownMenuItem>
                                        <DropdownMenuItem onClick={() => setIsEditDialogOpen(true)}>
                                            <Edit2 className="h-4 w-4 mr-2" />
                                            Edit contact
                                        </DropdownMenuItem>
                                        <DropdownMenuSeparator />
                                        <DropdownMenuItem
                                            className="text-destructive focus:text-destructive"
                                            onClick={() => setIsDeleteDialogOpen(true)}
                                        >
                                            <Trash2 className="h-4 w-4 mr-2" />
                                            Delete
                                        </DropdownMenuItem>
                                    </DropdownMenuContent>
                                </DropdownMenu>
                            </div>
                        </div>
                    </div>
                </div>

                {/* Main Content */}
                <div className="max-w-7xl mx-auto px-4 sm:px-6 py-6 space-y-6">
                    {/* Contact Header Card */}
                    <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.1 }}>
                        <Card className="overflow-hidden border-0 shadow-lg">
                            <div className="relative">
                                {/* Gradient background */}
                                <div className={cn('absolute inset-0 opacity-5 bg-gradient-to-r', statusInfo.gradient)} />

                                <CardContent className="relative p-6">
                                    <div className="flex flex-col lg:flex-row gap-6">
                                        {/* Avatar & Basic Info */}
                                        <div className="flex items-start gap-5">
                                            {/* Avatar with status indicator */}
                                            <div className="relative group">
                                                <Avatar className="h-20 w-20 ring-4 ring-background shadow-xl">
                                                    {contact.avatar_url && (
                                                        <AvatarImage src={contact.avatar_url} alt={fullName} className="object-cover" />
                                                    )}
                                                    <AvatarFallback className="bg-gradient-to-br from-primary/20 to-purple-500/20 text-primary text-xl font-bold">
                                                        {initials}
                                                    </AvatarFallback>
                                                </Avatar>

                                                {/* Status badge */}
                                                <div
                                                    className={cn(
                                                        'absolute -bottom-1 -right-1 p-1.5 rounded-full ring-2 ring-background',
                                                        statusInfo.color,
                                                    )}
                                                >
                                                    <StatusIcon className="h-3.5 w-3.5 text-white" />
                                                </div>

                                                {/* Hover overlay for photo change */}
                                                <button
                                                    onClick={() => setIsAvatarDialogOpen(true)}
                                                    className="absolute inset-0 rounded-full bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center"
                                                >
                                                    <Camera className="h-5 w-5 text-white" />
                                                </button>
                                            </div>

                                            {/* Name & Company */}
                                            <div className="space-y-1.5">
                                                <div className="flex items-center gap-2 flex-wrap">
                                                    <h1 className="text-2xl font-bold tracking-tight">{fullName}</h1>
                                                    <Badge variant="secondary" className={cn('font-medium', statusInfo.bgLight, statusInfo.text)}>
                                                        {statusInfo.label}
                                                    </Badge>
                                                </div>

                                                {contact.company && (
                                                    <p className="text-muted-foreground flex items-center gap-2">
                                                        <Building2 className="h-4 w-4" />
                                                        {contact.company}
                                                    </p>
                                                )}

                                                <div className="flex flex-wrap gap-2 pt-2">
                                                    <InfoPill
                                                        icon={Calendar}
                                                        text={createdAt ? formatDistanceToNow(createdAt, { addSuffix: true }) : 'Created date unknown'}
                                                    />
                                                    {contact.source && <InfoPill icon={Target} text={contact.source} />}
                                                    <InfoPill
                                                        icon={EngagementIcon}
                                                        text={`${engagementLevel.label}`}
                                                        variant={engagementScore >= 60 ? 'success' : engagementScore >= 40 ? 'warning' : 'default'}
                                                    />
                                                </div>
                                            </div>
                                        </div>

                                        {/* Engagement & Quick Actions */}
                                        <div className="lg:ml-auto flex flex-col sm:flex-row items-start sm:items-center gap-5">
                                            {/* Engagement Score */}
                                            <div className="flex items-center gap-3">
                                                <CircularProgress value={engagementScore} size={56} strokeWidth={5}>
                                                    <span className="text-sm font-bold">{engagementScore}</span>
                                                </CircularProgress>
                                                <div className="text-sm">
                                                    <p className="font-medium">Engagement</p>
                                                    <p className="text-muted-foreground text-xs">Profile score</p>
                                                </div>
                                            </div>

                                            {/* Quick Actions */}
                                            <div className="flex items-center gap-2">
                                                <ActionButton
                                                    icon={Mail}
                                                    label="Email"
                                                    variant="primary"
                                                    onClick={() => setIsEmailDialogOpen(true)}
                                                    disabled={!contact.email}
                                                />
                                                <ActionButton
                                                    icon={Phone}
                                                    label="Call"
                                                    onClick={() => contact.phone && window.open(`tel:${contact.phone}`, '_self')}
                                                    disabled={!contact.phone}
                                                />
                                                <ActionButton icon={CalendarPlus} label="Meet" onClick={() => toast.info('Coming soon')} />
                                            </div>
                                        </div>
                                    </div>

                                    {/* Contact Details */}
                                    <div className="mt-6 pt-6 border-t grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
                                        {/* Email */}
                                        {contact.email ? (
                                            <button
                                                onClick={() => window.open(`mailto:${contact.email}`, '_self')}
                                                className="flex items-center gap-3 p-3 rounded-xl bg-muted/40 hover:bg-muted/60 transition-colors text-left group"
                                            >
                                                <div className="h-10 w-10 rounded-lg bg-blue-500/10 flex items-center justify-center shrink-0">
                                                    <Mail className="h-5 w-5 text-blue-600" />
                                                </div>
                                                <div className="min-w-0 flex-1">
                                                    <p className="text-xs text-muted-foreground">Email</p>
                                                    <p className="text-sm font-medium truncate">{contact.email}</p>
                                                </div>
                                                <Button
                                                    variant="ghost"
                                                    size="icon"
                                                    className="h-8 w-8 opacity-0 group-hover:opacity-100 shrink-0"
                                                    onClick={(e) => {
                                                        e.stopPropagation();
                                                        void handleCopy(contact.email, 'Email');
                                                    }}
                                                >
                                                    <Copy className="h-3.5 w-3.5" />
                                                </Button>
                                            </button>
                                        ) : (
                                            <div className="flex items-center gap-3 p-3 rounded-xl bg-muted/20 opacity-60">
                                                <div className="h-10 w-10 rounded-lg bg-muted flex items-center justify-center shrink-0">
                                                    <Mail className="h-5 w-5 text-muted-foreground" />
                                                </div>
                                                <div>
                                                    <p className="text-xs text-muted-foreground">Email</p>
                                                    <p className="text-sm text-muted-foreground">Not set</p>
                                                </div>
                                            </div>
                                        )}

                                        {/* Phone */}
                                        {contact.phone ? (
                                            <button
                                                onClick={() => window.open(`tel:${contact.phone}`, '_self')}
                                                className="flex items-center gap-3 p-3 rounded-xl bg-muted/40 hover:bg-muted/60 transition-colors text-left group"
                                            >
                                                <div className="h-10 w-10 rounded-lg bg-emerald-500/10 flex items-center justify-center shrink-0">
                                                    <Phone className="h-5 w-5 text-emerald-600" />
                                                </div>
                                                <div className="min-w-0 flex-1">
                                                    <p className="text-xs text-muted-foreground">Phone</p>
                                                    <p className="text-sm font-medium truncate">{contact.phone}</p>
                                                </div>
                                                <Button
                                                    variant="ghost"
                                                    size="icon"
                                                    className="h-8 w-8 opacity-0 group-hover:opacity-100 shrink-0"
                                                    onClick={(e) => {
                                                        e.stopPropagation();
                                                        void handleCopy(contact.phone, 'Phone');
                                                    }}
                                                >
                                                    <Copy className="h-3.5 w-3.5" />
                                                </Button>
                                            </button>
                                        ) : (
                                            <div className="flex items-center gap-3 p-3 rounded-xl bg-muted/20 opacity-60">
                                                <div className="h-10 w-10 rounded-lg bg-muted flex items-center justify-center shrink-0">
                                                    <Phone className="h-5 w-5 text-muted-foreground" />
                                                </div>
                                                <div>
                                                    <p className="text-xs text-muted-foreground">Phone</p>
                                                    <p className="text-sm text-muted-foreground">Not set</p>
                                                </div>
                                            </div>
                                        )}

                                        {/* Pipeline */}
                                        {currentPipeline && currentStage ? (
                                            <div className="flex items-center gap-3 p-3 rounded-xl bg-muted/40">
                                                <div className="h-10 w-10 rounded-lg bg-purple-500/10 flex items-center justify-center shrink-0">
                                                    <Gauge className="h-5 w-5 text-purple-600" />
                                                </div>
                                                <div className="min-w-0 flex-1">
                                                    <p className="text-xs text-muted-foreground">{currentPipeline.name}</p>
                                                    <div className="flex items-center gap-2">
                                                        {currentStage.color && (
                                                            <span className="h-2 w-2 rounded-full shrink-0" style={{ backgroundColor: currentStage.color }} />
                                                        )}
                                                        <p className="text-sm font-medium truncate">{currentStage.name}</p>
                                                    </div>
                                                </div>
                                            </div>
                                        ) : (
                                            <div className="flex items-center gap-3 p-3 rounded-xl bg-muted/20 opacity-60">
                                                <div className="h-10 w-10 rounded-lg bg-muted flex items-center justify-center shrink-0">
                                                    <Gauge className="h-5 w-5 text-muted-foreground" />
                                                </div>
                                                <div>
                                                    <p className="text-xs text-muted-foreground">Pipeline</p>
                                                    <p className="text-sm text-muted-foreground">Not assigned</p>
                                                </div>
                                            </div>
                                        )}

                                        {/* Tags */}
                                        <div className="flex items-center gap-3 p-3 rounded-xl bg-muted/40">
                                            <div className="h-10 w-10 rounded-lg bg-amber-500/10 flex items-center justify-center shrink-0">
                                                <Tag className="h-5 w-5 text-amber-600" />
                                            </div>
                                            <div className="min-w-0 flex-1">
                                                <p className="text-xs text-muted-foreground">Tags</p>
                                                <div className="flex items-center gap-1 flex-wrap">
                                                    {contact.tags?.length > 0 ? (
                                                        <>
                                                            {contact.tags.slice(0, 2).map((tag: any) => (
                                                                <Badge
                                                                    key={tag.id}
                                                                    variant="secondary"
                                                                    className="text-xs h-5"
                                                                    style={{ backgroundColor: `${tag.color}15`, color: tag.color }}
                                                                >
                                                                    {tag.name}
                                                                </Badge>
                                                            ))}
                                                            {contact.tags.length > 2 && (
                                                                <span className="text-xs text-muted-foreground">+{contact.tags.length - 2}</span>
                                                            )}
                                                        </>
                                                    ) : (
                                                        <span className="text-sm text-muted-foreground">None</span>
                                                    )}
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </CardContent>
                            </div>
                        </Card>
                    </motion.div>

                    {/* Two Column Layout */}
                    <div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
                        {/* Main Workbench */}
                        <motion.div
                            initial={{ opacity: 0, y: 20 }}
                            animate={{ opacity: 1, y: 0 }}
                            transition={{ delay: 0.2 }}
                            className="xl:col-span-2"
                        >
                            <Card className="border-0 shadow-lg overflow-hidden">
                                <Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as any)} className="w-full">
                                    <div className="border-b bg-muted/30">
                                        <TabsList className="h-12 w-full justify-start gap-0 rounded-none bg-transparent px-2">
                                            {[
                                                { id: 'timeline', label: 'Activity', icon: Activity },
                                                { id: 'tasks', label: 'Tasks', icon: ListTodo },
                                                { id: 'notes', label: 'Notes', icon: FileText },
                                                { id: 'files', label: 'Files', icon: Paperclip },
                                                { id: 'custom', label: 'Fields', icon: Settings2 },
                                            ].map((tab) => (
                                                <TabsTrigger
                                                    key={tab.id}
                                                    value={tab.id}
                                                    className="rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent px-4"
                                                >
                                                    <tab.icon className="h-4 w-4 mr-2" />
                                                    {tab.label}
                                                </TabsTrigger>
                                            ))}
                                        </TabsList>
                                    </div>

                                    <div className="p-5">
                                        <AnimatePresence mode="wait">
                                            <motion.div
                                                key={activeTab}
                                                initial={{ opacity: 0, y: 8 }}
                                                animate={{ opacity: 1, y: 0 }}
                                                exit={{ opacity: 0, y: -8 }}
                                                transition={{ duration: 0.15 }}
                                            >
                                                <TabsContent value="timeline" className="mt-0 focus-visible:outline-none">
                                                    <ContactActivitiesTab contactId={contact.id} variant="workbench" />
                                                </TabsContent>

                                                <TabsContent value="tasks" className="mt-0 focus-visible:outline-none">
                                                    <ContactTasksTab contactId={contact.id} variant="workbench" />
                                                </TabsContent>

                                                <TabsContent value="notes" className="mt-0 focus-visible:outline-none">
                                                    <ContactNotesTab contactId={contact.id} variant="workbench" />
                                                </TabsContent>

                                                <TabsContent value="files" className="mt-0 focus-visible:outline-none">
                                                    <ContactAttachmentsTab contactId={contact.id} variant="workbench" />
                                                </TabsContent>

                                                <TabsContent value="custom" className="mt-0 focus-visible:outline-none">
                                                    <ContactCustomFieldsTab contactId={contact.id} variant="workbench" />
                                                </TabsContent>
                                            </motion.div>
                                        </AnimatePresence>
                                    </div>
                                </Tabs>
                            </Card>
                        </motion.div>

                        {/* Sidebar */}
                        <motion.div
                            initial={{ opacity: 0, y: 20 }}
                            animate={{ opacity: 1, y: 0 }}
                            transition={{ delay: 0.3 }}
                            className="space-y-6"
                        >
                            {/* Pipeline Control */}
                            <Card className="border-0 shadow-lg">
                                <CardHeader className="pb-3">
                                    <CardTitle className="text-sm font-semibold flex items-center gap-2">
                                        <Zap className="h-4 w-4 text-primary" />
                                        Pipeline
                                    </CardTitle>
                                </CardHeader>
                                <CardContent className="space-y-4">
                                    <Select value={contact.pipeline_id ?? ''} onValueChange={handlePipelineChange} disabled={isUpdating}>
                                        <SelectTrigger className="bg-muted/40 border-0">
                                            <SelectValue placeholder="Select pipeline" />
                                        </SelectTrigger>
                                        <SelectContent>
                                            {pipelines.map((p: any) => (
                                                <SelectItem key={p.id} value={p.id}>
                                                    {p.name}
                                                </SelectItem>
                                            ))}
                                        </SelectContent>
                                    </Select>

                                    {contact.pipeline_id && stages.length > 0 && (
                                        <>
                                            <Select value={contact.stage_id ?? ''} onValueChange={handleStageChange} disabled={isUpdating}>
                                                <SelectTrigger className="bg-muted/40 border-0">
                                                    <SelectValue placeholder="Select stage" />
                                                </SelectTrigger>
                                                <SelectContent>
                                                    {stages.map((s: any) => (
                                                        <SelectItem key={s.id} value={s.id}>
                                                            <div className="flex items-center gap-2">
                                                                {s.color && <span className="h-2.5 w-2.5 rounded-full" style={{ backgroundColor: s.color }} />}
                                                                {s.name}
                                                            </div>
                                                        </SelectItem>
                                                    ))}
                                                </SelectContent>
                                            </Select>

                                            {/* Progress indicator */}
                                            <div className="space-y-2">
                                                <StageDots stages={stages} currentIndex={currentStageIndex} />
                                                <div className="flex items-center justify-between text-xs text-muted-foreground">
                                                    <span>{currentStage?.name}</span>
                                                    <span>{Math.round(stageProgress)}%</span>
                                                </div>
                                            </div>

                                            {nextStage && (
                                                <Button className="w-full" onClick={handleAdvanceStage} disabled={isUpdating}>
                                                    {isUpdating ? (
                                                        <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                                                    ) : (
                                                        <ArrowRight className="h-4 w-4 mr-2" />
                                                    )}
                                                    Move to {nextStage.name}
                                                </Button>
                                            )}
                                        </>
                                    )}
                                </CardContent>
                            </Card>

                            {/* Status Control */}
                            <Card className="border-0 shadow-lg">
                                <CardHeader className="pb-3">
                                    <CardTitle className="text-sm font-semibold flex items-center gap-2">
                                        <Shield className="h-4 w-4 text-primary" />
                                        Status
                                    </CardTitle>
                                </CardHeader>
                                <CardContent>
                                    <div className="grid grid-cols-2 gap-2">
                                        {Object.entries(statusConfig).map(([status, config]) => {
                                            const Icon = config.icon;
                                            const isActive = contact.status === status;
                                            return (
                                                <button
                                                    key={status}
                                                    onClick={() => void handleStatusChange(status)}
                                                    disabled={isUpdating}
                                                    className={cn(
                                                        'flex items-center gap-2 p-3 rounded-xl transition-all text-sm font-medium',
                                                        'border disabled:opacity-50',
                                                        isActive
                                                            ? cn(config.bgLight, config.border, config.text)
                                                            : 'border-transparent bg-muted/40 hover:bg-muted/60 text-muted-foreground',
                                                    )}
                                                >
                                                    <Icon className="h-4 w-4" />
                                                    {config.label}
                                                </button>
                                            );
                                        })}
                                    </div>
                                </CardContent>
                            </Card>

                            {/* Tags */}
                            <Card className="border-0 shadow-lg">
                                <CardHeader className="pb-3">
                                    <CardTitle className="text-sm font-semibold flex items-center gap-2">
                                        <Tag className="h-4 w-4 text-primary" />
                                        Tags
                                    </CardTitle>
                                </CardHeader>
                                <CardContent>
                                    <ContactTagsManager contactId={contact.id} currentTags={contact.tags} />
                                </CardContent>
                            </Card>
                        </motion.div>
                    </div>
                </div>

                {/* Dialogs */}
                <ContactFormDialog
                    open={isEditDialogOpen}
                    onOpenChange={setIsEditDialogOpen}
                    contact={contactForForm}
                    onSubmit={handleEditSubmit}
                    isSubmitting={isUpdating}
                />

                {/* Avatar Upload Dialog */}
                <Dialog open={isAvatarDialogOpen} onOpenChange={setIsAvatarDialogOpen}>
                    <DialogContent className="sm:max-w-md">
                        <DialogHeader>
                            <DialogTitle>Profile Photo</DialogTitle>
                            <DialogDescription>Upload a photo to help your team recognize this contact.</DialogDescription>
                        </DialogHeader>
                        <div className="py-4">
                            <ContactAvatarUpload
                                contactId={contact.id}
                                avatarUrl={contact.avatar_url}
                                firstName={contact.first_name}
                                lastName={contact.last_name}
                            />
                        </div>
                    </DialogContent>
                </Dialog>

                {/* Delete Dialog */}
                <AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
                    <AlertDialogContent>
                        <AlertDialogHeader>
                            <div className="mx-auto mb-4 h-12 w-12 rounded-full bg-destructive/10 flex items-center justify-center">
                                <Trash2 className="h-6 w-6 text-destructive" />
                            </div>
                            <AlertDialogTitle className="text-center">Delete Contact?</AlertDialogTitle>
                            <AlertDialogDescription className="text-center">
                                <strong>{fullName}</strong> will be moved to trash. You can restore within 30 days.
                            </AlertDialogDescription>
                        </AlertDialogHeader>
                        <AlertDialogFooter className="sm:justify-center gap-2">
                            <AlertDialogCancel>Cancel</AlertDialogCancel>
                            <AlertDialogAction
                                onClick={() => void handleDelete()}
                                className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                                disabled={isSoftDeleting}
                            >
                                {isSoftDeleting ? (
                                    <>
                                        <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                                        Deleting...
                                    </>
                                ) : (
                                    'Delete'
                                )}
                            </AlertDialogAction>
                        </AlertDialogFooter>
                    </AlertDialogContent>
                </AlertDialog>

                {/* Email Dialog */}
                <SendEmailDialog open={isEmailDialogOpen} onOpenChange={setIsEmailDialogOpen} contact={contact} />
            </motion.div>
        </TooltipProvider>
    );
}