import { Link } from '@inertiajs/react';
import {
    ArrowRightLeft,
    CalendarClock,
    FileUp,
    House,
    Mail,
    MessageSquare,
    Phone,
    Plus,
    ShieldCheck,
    StickyNote,
    UserCheck,
    type LucideIcon,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { RichText } from '@/components/crm/rich-text';
import { formatDateTime, formatRelative } from '@/lib/format';
import type { ActivityEntry, StatusHistoryEntry } from '@/types';
import { toneClasses } from './tone';

/**
 * Activity type to icon and colour. The keys mirror App\Enums\JobActivityType.
 */
const activityIcons: Record<string, { icon: LucideIcon; tone: string }> = {
    status_changed: { icon: ArrowRightLeft, tone: 'info' },
    note: { icon: StickyNote, tone: 'slate' },
    call: { icon: Phone, tone: 'solar' },
    email: { icon: Mail, tone: 'info' },
    sms: { icon: MessageSquare, tone: 'info' },
    site_visit: { icon: CalendarClock, tone: 'violet' },
    document_uploaded: { icon: FileUp, tone: 'teal' },
    assigned: { icon: UserCheck, tone: 'indigo' },
    scheduled: { icon: CalendarClock, tone: 'amber' },
    compliance_updated: { icon: ShieldCheck, tone: 'success' },
    created: { icon: Plus, tone: 'slate' },
    ownership_transferred: { icon: House, tone: 'violet' },
};

export function activityIcon(type: string): { icon: LucideIcon; tone: string } {
    return activityIcons[type] ?? { icon: StickyNote, tone: 'slate' };
}

/**
 * A vertical timeline of what happened on a job. The rail is a hairline, the
 * entries carry the colour.
 */
export function ActivityTimeline({
    entries,
    jobHref,
    className,
    emptyMessage = 'No activity recorded yet.',
}: {
    entries: ActivityEntry[];
    jobHref?: (jobId: number) => string;
    className?: string;
    emptyMessage?: string;
}) {
    if (entries.length === 0) {
        return (
            <p className="text-muted-foreground py-6 text-center text-sm">
                {emptyMessage}
            </p>
        );
    }

    return (
        <ol className={cn('relative space-y-4', className)}>
            <span
                aria-hidden
                className="bg-hairline absolute top-2 bottom-2 left-[15px] w-px"
            />

            {entries.map((entry) => {
                const { icon: Icon, tone } = activityIcon(entry.type.value);
                const classes = toneClasses(tone);

                return (
                    <li key={entry.id} className="relative flex gap-3">
                        <span
                            className={cn(
                                'ring-card z-10 flex size-8 shrink-0 items-center justify-center rounded-full ring-4',
                                classes.soft,
                            )}
                        >
                            <Icon className="size-3.5" />
                        </span>
                        <div className="min-w-0 flex-1 pt-1">
                            <div className="flex flex-wrap items-baseline gap-x-2 gap-y-0.5">
                                <p className="text-sm font-medium">
                                    {entry.subject ?? entry.type.label}
                                </p>
                                {entry.job && jobHref ? (
                                    <Link
                                        href={jobHref(entry.job.id)}
                                        className="text-muted-foreground hover:text-foreground font-mono text-xs"
                                    >
                                        {entry.job.job_number}
                                    </Link>
                                ) : null}
                            </div>
                            <RichText
                                html={entry.body_html}
                                className="text-muted-foreground mt-0.5 text-xs leading-relaxed"
                            />
                            <p className="text-muted-foreground mt-1 flex items-center gap-1.5 text-[11px]">
                                <span>{entry.user?.name ?? 'System'}</span>
                                <span aria-hidden>·</span>
                                <span title={formatDateTime(entry.occurred_at)}>
                                    {formatRelative(entry.occurred_at)}
                                </span>
                            </p>
                        </div>
                    </li>
                );
            })}
        </ol>
    );
}

/**
 * The compliance record: every pipeline change, who made it and why.
 * Deliberately plain — this is the part that gets read under scrutiny.
 */
export function StatusAuditTrail({
    entries,
    className,
}: {
    entries: StatusHistoryEntry[];
    className?: string;
}) {
    if (entries.length === 0) {
        return (
            <p className="text-muted-foreground py-6 text-center text-sm">
                No status changes recorded yet.
            </p>
        );
    }

    return (
        <ol className={cn('space-y-3', className)}>
            {entries.map((entry) => (
                <li
                    key={entry.id}
                    className="border-hairline flex flex-col gap-1.5 border-b pb-3 last:border-0 last:pb-0 sm:flex-row sm:items-start sm:gap-4"
                >
                    <div className="flex min-w-0 flex-1 flex-wrap items-center gap-1.5 text-sm">
                        {entry.from ? (
                            <>
                                <span className="text-muted-foreground">
                                    {entry.from.label}
                                </span>
                                <ArrowRightLeft className="text-muted-foreground/60 size-3" />
                            </>
                        ) : null}
                        <span className="flex items-center gap-1.5 font-medium">
                            <span
                                aria-hidden
                                className={cn(
                                    'size-1.5 rounded-full',
                                    toneClasses(entry.to.color).dot,
                                )}
                            />
                            {entry.to.label}
                        </span>
                    </div>
                    <div className="text-muted-foreground shrink-0 text-xs sm:w-56 sm:text-right">
                        <span>{entry.user?.name ?? 'System'}</span>
                        <span aria-hidden> · </span>
                        <span title={formatDateTime(entry.created_at)}>
                            {formatDateTime(entry.created_at)}
                        </span>
                    </div>
                    <RichText
                        html={entry.notes_html}
                        className="text-muted-foreground w-full text-xs leading-relaxed sm:order-last"
                    />
                </li>
            ))}
        </ol>
    );
}
