import { Link } from '@inertiajs/react';
import { Handle, Position } from '@xyflow/react';
import type { Node, NodeProps } from '@xyflow/react';
import { ChevronDown, ChevronRight, UserRound } from 'lucide-react';
import { cn } from '@/lib/utils';
import { show as showEmployee } from '@/routes/admin/employees';
import { useOrgChartCollapse } from './org-chart-collapse-context';

export type OrgNodeData = {
    id: string;
    type: 'employee' | 'user';
    employee_id: number | null;
    user_id: number | null;
    parent_id: string | null;
    name: string;
    code: string | null;
    job_title: string | null;
    department: string | null;
    email: string | null;
    is_synthetic: boolean;
    hasChildren: boolean;
    collapsed: boolean;
};

export type OrgFlowNode = Node<OrgNodeData, 'org'>;

function initials(name: string): string {
    return name
        .split(/\s+/)
        .filter(Boolean)
        .slice(0, 2)
        .map((part) => part.charAt(0).toUpperCase())
        .join('');
}

export function OrganizationChartNode({ data }: NodeProps<OrgFlowNode>) {
    const toggleCollapse = useOrgChartCollapse();
    const subtitle = data.job_title ?? (data.is_synthetic ? 'Manager' : null);
    const meta = [data.code, data.department].filter(Boolean).join(' · ');

    const identity = (
        <div className="flex items-start gap-3">
            <div
                className={cn(
                    'flex size-9 shrink-0 items-center justify-center rounded-full text-xs font-semibold',
                    data.is_synthetic
                        ? 'bg-muted text-muted-foreground'
                        : 'bg-foreground text-background',
                )}
            >
                {data.is_synthetic ? (
                    <UserRound className="size-4" />
                ) : (
                    initials(data.name) || '?'
                )}
            </div>
            <div className="min-w-0 flex-1">
                <p className="truncate text-sm font-semibold leading-tight">
                    {data.name}
                </p>
                {subtitle && (
                    <p className="mt-0.5 truncate text-xs text-muted-foreground">
                        {subtitle}
                    </p>
                )}
                {meta && (
                    <p className="mt-1 truncate text-[11px] text-muted-foreground">
                        {meta}
                    </p>
                )}
            </div>
        </div>
    );

    return (
        <>
            <Handle
                type="target"
                position={Position.Top}
                className="!size-2 !border-background !bg-muted-foreground"
            />
            <div
                className={cn(
                    'w-56 rounded-xl border bg-background px-3.5 py-3 shadow-sm transition-colors',
                    data.is_synthetic
                        ? 'border-dashed border-muted-foreground/40 bg-muted/40'
                        : 'border-border hover:border-foreground/30',
                )}
            >
                {data.employee_id !== null ? (
                    <Link
                        href={showEmployee(data.employee_id)}
                        className="nodrag nopan block outline-none"
                        onClick={(event) => event.stopPropagation()}
                        onMouseDown={(event) => {
                            event.stopPropagation();
                        }}
                        onPointerDown={(event) => {
                            event.stopPropagation();
                        }}
                    >
                        {identity}
                    </Link>
                ) : (
                    identity
                )}

                {data.hasChildren && (
                    <button
                        type="button"
                        className="nodrag nopan mt-2.5 flex w-full items-center justify-center gap-1 rounded-md border border-transparent py-1 text-[11px] font-medium text-muted-foreground hover:border-border hover:bg-muted/60 hover:text-foreground"
                        onClick={(event) => {
                            event.preventDefault();
                            event.stopPropagation();
                            toggleCollapse(data.id);
                        }}
                        onMouseDown={(event) => {
                            event.stopPropagation();
                        }}
                        onPointerDown={(event) => {
                            event.stopPropagation();
                        }}
                    >
                        {data.collapsed ? (
                            <>
                                <ChevronRight className="size-3.5" />
                                Déplier
                            </>
                        ) : (
                            <>
                                <ChevronDown className="size-3.5" />
                                Replier
                            </>
                        )}
                    </button>
                )}
            </div>
            <Handle
                type="source"
                position={Position.Bottom}
                className="!size-2 !border-background !bg-muted-foreground"
            />
        </>
    );
}
