"use client"

import * as React from "react"
import { Contact, ContactStatus } from "./types"
import { Button } from "@/components/ui/button"
import {
    Dialog,
    DialogContent,
    DialogTitle,
} from "@/components/ui/dialog"
import { cn } from "@/lib/utils"
import { formatTeamLabelForUi } from "@/lib/deal-display"
import {
    Mail, Phone, MapPin, Building2, User2, MessageSquare,
    History, Send, Globe, Briefcase, Pencil, DollarSign, Target,
} from "lucide-react"
import { ContactDealsWidget } from "./contact-deals-widget"

interface ContactDetailModalProps {
    contact: Contact | null
    isOpen: boolean
    onClose: () => void
    onEdit: () => void
    onSendEmail: (email: string) => void
    canUpdate?: boolean
}

const stageColors: Record<string, string> = {
    'Prospecting': '#6C63FF',
    'Qualified': '#8B83FF',
    'Proposal Sent': '#F59E0B',
    'Negotiation': '#FF8C42',
    'Closed Won': '#22C55E',
    'Closed Lost': '#FF6B6B',
}

const statusBadges: Record<ContactStatus, string> = {
    'Active': 'bg-[#EEF2FF] text-[#6C63FF]',
    'Nurturing': 'bg-gray-100 text-gray-700',
    'Hot': 'bg-[#ECFDF5] text-[#22C55E]',
    'Cold': 'bg-gray-100 text-gray-600',
    'Won': 'bg-[#ECFDF5] text-[#22C55E]',
    'Lost': 'bg-[#FEF2F2] text-[#FF6B6B]',
}

export function ContactDetailModal({ contact, isOpen, onClose, onEdit, onSendEmail, canUpdate = true }: ContactDetailModalProps) {
    if (!contact) return null

    const stageColor = stageColors[contact.stage] || '#6C63FF'

    return (
        <Dialog open={isOpen} onOpenChange={(v) => !v && onClose()}>
            <DialogContent
                className="sm:max-w-[580px] p-0 overflow-hidden gap-0"
                aria-describedby={undefined}
            >
                {/* Hero header */}
                <div className="relative px-8 pt-8 pb-6 bg-gradient-to-br from-accent/10 via-accent/5 to-transparent border-b border-border/40">
                    <div className="flex items-center gap-4">
                        <div
                            className="size-14 rounded-2xl flex items-center justify-center text-[18px] font-extrabold text-white shadow-md font-['Lexend_Deca'] shrink-0"
                            style={{ backgroundColor: contact.color || '#6C63FF' }}
                        >
                            {contact.initials}
                        </div>
                        <div className="min-w-0">
                            <DialogTitle className="text-[20px] font-extrabold text-text font-['Lexend'] leading-tight truncate">
                                {contact.name}
                            </DialogTitle>
                            <p className="text-[13px] text-gray-500 font-['Lexend_Deca'] mt-0.5">
                                {contact.title} · {contact.company}
                            </p>
                        </div>
                        <div className="ml-auto shrink-0">
                            <span
                                className="text-[11px] font-bold px-3 py-1 rounded-full"
                                style={{ backgroundColor: `${stageColor}18`, color: stageColor }}
                            >
                                {contact.stage}
                            </span>
                        </div>
                    </div>
                </div>

                {/* Scrollable body */}
                <div className="overflow-y-auto max-h-[60vh] scrollbar-themed">
                    <div className="px-8 py-6 space-y-8">

                        {/* Contact Details */}
                        <Section icon={<User2 size={13} />} title="Contact Details">
                            <Grid>
                                <InfoItem icon={<Mail size={12} />} label="Email" value={contact.email} accent />
                                <InfoItem icon={<Phone size={12} />} label="Phone" value={contact.phone || "Not set"} />
                                <InfoItem icon={<Globe size={12} />} label="Website" value={contact.website || "Not set"} />
                                <InfoItem icon={<MessageSquare size={12} />} label="Language" value={contact.defaultLanguage || "English"} />
                            </Grid>
                        </Section>

                        {/* Business Insights */}
                        <Section icon={<Building2 size={13} />} title="Business Insights">
                            <Grid>
                                <InfoItem icon={<Building2 size={12} />} label="Company" value={contact.company} />
                                <InfoItem icon={<Briefcase size={12} />} label="Position" value={contact.title} />
                                <div className="flex flex-col gap-1.5">
                                    <span className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.07em] font-['Lexend_Deca'] flex items-center gap-1.5">
                                        <DollarSign size={11} className="text-accent" /> Deal Value
                                    </span>
                                    <span className="text-[18px] font-extrabold text-accent font-['Lexend_Deca'] tracking-tight">
                                        ${contact.dealValue >= 1000 ? `${(contact.dealValue / 1000).toFixed(1)}M` : `${contact.dealValue}K`}
                                    </span>
                                </div>
                                <div className="flex flex-col gap-1.5">
                                    <span className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.07em] font-['Lexend_Deca'] flex items-center gap-1.5">
                                        <Target size={11} className="text-accent" /> Status
                                    </span>
                                    <span className={cn("w-fit text-[11px] font-bold px-2.5 py-0.5 rounded-full", statusBadges[contact.status])}>
                                        {contact.status}
                                    </span>
                                </div>
                                <InfoItem icon={<User2 size={12} />} label="Assigned Rep" value={contact.rep} />
                                <div className="flex flex-col gap-1.5">
                                    <span className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.07em] font-['Lexend_Deca']">Team</span>
                                    <span className="text-[13px] font-semibold text-text font-['Lexend']">
                                        {contact.team
                                            ? `Team ${formatTeamLabelForUi(contact.team)}`
                                            : "—"}
                                    </span>
                                </div>
                            </Grid>
                        </Section>

                        {/* Location */}
                        <Section icon={<MapPin size={13} />} title="Location Info">
                            <Grid>
                                <InfoItem icon={<MapPin size={12} />} label="City" value={contact.city || "Not set"} />
                                <InfoItem label="State" value={contact.state || "Not set"} />
                                <InfoItem label="Country" value={contact.country || "Not set"} />
                                <InfoItem label="Zip Code" value={contact.zipCode || "Not set"} />
                                <div className="col-span-2">
                                    <InfoItem label="Street Address" value={contact.address || "Not set"} />
                                </div>
                            </Grid>
                        </Section>

                        {/* Description */}
                        {contact.description && (
                            <Section title="Description & Notes">
                                <div className="bg-gray-50 rounded-xl p-4 border border-border/40">
                                    <p className="text-[13px] text-text font-medium leading-relaxed italic">
                                        "{contact.description}"
                                    </p>
                                </div>
                            </Section>
                        )}

                        {/* Linked Deals */}
                        <Section icon={<Briefcase size={13} />} title="Linked Deals">
                            <ContactDealsWidget contactId={contact.id} />
                        </Section>

                        {/* Timeline */}
                        {contact.timeline?.length > 0 && (
                            <Section icon={<History size={13} />} title="Recent Activity">
                                <div className="space-y-3">
                                    {contact.timeline.map((item, i) => (
                                        <div key={i} className="flex gap-3">
                                            <div className="relative flex flex-col items-center">
                                                <div
                                                    className="size-2 rounded-full mt-1.5 shrink-0 z-10"
                                                    style={{ backgroundColor: item.color }}
                                                />
                                                {i < contact.timeline.length - 1 && (
                                                    <div className="w-px absolute top-3 -bottom-4 bg-border" />
                                                )}
                                            </div>
                                            <div className="flex flex-col gap-0.5 pb-1">
                                                <p className="text-[13px] text-text font-medium leading-relaxed">{item.text}</p>
                                                <span className="text-[10px] text-gray-400 font-bold font-['Lexend_Deca'] uppercase">{item.days}d ago</span>
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            </Section>
                        )}
                    </div>
                </div>

                {/* Footer */}
                <div className="flex items-center justify-end gap-2 px-8 py-4 border-t border-border/40 bg-gray-50/60">
                    <Button variant="ghost" size="sm" onClick={onClose}>
                        Close
                    </Button>
                    {canUpdate && (
                        <Button
                            variant="outlineAccentSoft"
                            onClick={onEdit}
                        >
                            <Pencil size={13} /> Edit Contact
                        </Button>
                    )}
                    <Button
                        size="sm"
                        onClick={() => onSendEmail(contact.email)}
                    >
                        <Send size={13} /> Send Email
                    </Button>
                </div>
            </DialogContent>
        </Dialog>
    )
}

// ── Helpers ──────────────────────────────────────────────────────────────────

function Section({
    title,
    icon,
    children,
}: {
    title: string
    icon?: React.ReactNode
    children: React.ReactNode
}) {
    return (
        <div className="space-y-4">
            <div className="flex items-center gap-2 pb-2 border-b border-border/40">
                {icon && <span className="text-accent">{icon}</span>}
                <h3 className="text-[11px] font-bold text-gray-500 uppercase tracking-wider font-['Lexend_Deca']">
                    {title}
                </h3>
            </div>
            {children}
        </div>
    )
}

function Grid({ children }: { children: React.ReactNode }) {
    return (
        <div className="grid grid-cols-2 gap-x-8 gap-y-5">
            {children}
        </div>
    )
}

function InfoItem({
    label,
    value,
    icon,
    accent,
}: {
    label: string
    value: string
    icon?: React.ReactNode
    accent?: boolean
}) {
    return (
        <div className="flex flex-col gap-1.5">
            <span className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.07em] font-['Lexend_Deca'] flex items-center gap-1.5">
                {icon && <span className="text-accent">{icon}</span>}
                {label}
            </span>
            <span className={cn(
                "text-[13px] font-semibold font-['Lexend'] break-all",
                accent ? "text-accent" : "text-text"
            )}>
                {value || "—"}
            </span>
        </div>
    )
}
