import { useState } from "react";
import { Link } from "@inertiajs/react";
import { History, House } from "lucide-react";
import { RuleFlag, StatusPill } from "@/components/crm/status-badge";
import { Button } from "@/components/ui/button";
import { formatDate } from "@/lib/format";
import { cn } from "@/lib/utils";
import type { OwnershipEntry, SiteOwnership } from "@/types";

/**
 * Whose house this is, and who it was before.
 *
 * A property outlives its owners, so the address is the fixed point and the
 * people change. This shows the current owner with the tenure running under
 * them, and unfolds the earlier owners behind it — because the question that
 * gets asked two years after a sale is "who was this done for?", and the answer
 * has to be on the same screen as the work.
 */
export function OwnershipHistory({
    ownership,
    /** The tenure to mark as the one covering this job, on the job page. */
    markedId = null,
    /** Open on mount where the history is the point of the panel, not a fold. */
    defaultOpen = false,
    className,
}: {
    ownership: SiteOwnership;
    markedId?: number | null;
    defaultOpen?: boolean;
    className?: string;
}) {
    const [open, setOpen] = useState(defaultOpen);

    const current = ownership.current;
    const earlier = ownership.history.filter((entry) => !entry.is_current);

    if (current === null && ownership.history.length === 0) {
        return (
            <p className={cn("text-muted-foreground text-xs", className)}>
                No owner is recorded against this address yet.
            </p>
        );
    }

    return (
        <div className={cn("grid gap-2", className)}>
            <div className="flex flex-wrap items-start justify-between gap-2">
                <div className="min-w-0">
                    <p className="crm-label flex items-center gap-1.5">
                        <House className="size-3.5" />
                        Owner
                    </p>
                    <p className="mt-0.5 truncate text-sm font-semibold">
                        {current ? (
                            <OwnerLink entry={current} />
                        ) : (
                            "Owner not recorded"
                        )}
                    </p>
                    <p className="text-muted-foreground mt-0.5 text-xs">
                        {current
                            ? `Held since ${formatDate(current.started_on)}`
                            : "This address has no current owner on file."}
                        {current?.previous_owner
                            ? ` · taken over from ${current.previous_owner.name}`
                            : ""}
                    </p>
                </div>

                {ownership.history.length > 1 ? (
                    <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        aria-expanded={open}
                        onClick={() => setOpen((value) => !value)}
                        data-test="ownership-history-toggle"
                    >
                        <History />
                        {open ? "Hide" : "History"} ({ownership.history.length})
                    </Button>
                ) : null}
            </div>

            {open ? (
                <ol className="border-hairline mt-1 grid gap-3 border-t pt-3">
                    {ownership.history.map((entry) => (
                        <TenureRow
                            key={entry.id}
                            entry={entry}
                            marked={markedId === entry.id}
                        />
                    ))}
                </ol>
            ) : null}
        </div>
    );
}

/**
 * One owner's stretch: who, for how long, why they got it and what came with it.
 */
function TenureRow({
    entry,
    marked,
}: {
    entry: OwnershipEntry;
    marked: boolean;
}) {
    return (
        <li className="grid gap-1">
            <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
                <span
                    className={cn(
                        "text-sm font-medium",
                        entry.is_current ? "text-foreground" : "text-muted-foreground",
                    )}
                >
                    <OwnerLink entry={entry} />
                </span>
                {entry.is_current ? (
                    <StatusPill tone="green" className="text-[11px]">
                        Current owner
                    </StatusPill>
                ) : null}
                {entry.reason ? (
                    <StatusPill
                        tone={entry.reason.is_correction ? "slate" : "blue"}
                        className="text-[11px]"
                    >
                        {entry.reason.label}
                    </StatusPill>
                ) : null}
                {marked ? (
                    <RuleFlag tone="solar">Owner when this job was created</RuleFlag>
                ) : null}
            </div>

            <p className="text-muted-foreground text-xs">
                {entry.period}
                {entry.jobs_moved > 0
                    ? ` · ${entry.jobs_moved} ${entry.jobs_moved === 1 ? "job" : "jobs"} moved with the house`
                    : ""}
            </p>

            {entry.notes ? (
                <p className="text-muted-foreground text-xs italic">
                    &ldquo;{entry.notes}&rdquo;
                </p>
            ) : null}

            {entry.is_transfer && entry.recorded_by ? (
                <p className="text-muted-foreground/80 text-[11px]">
                    Recorded by {entry.recorded_by} ·{" "}
                    {formatDate(entry.recorded_at)}
                </p>
            ) : null}
        </li>
    );
}

/**
 * The owner's name links to their customer record when that record is still
 * there. The name shown is the one recorded at the time of the handover, so a
 * customer renamed later does not rewrite a property's past.
 */
function OwnerLink({ entry }: { entry: OwnershipEntry }) {
    if (entry.owner.id === null) {
        return <>{entry.owner.name}</>;
    }

    return (
        <Link
            href={`/customers/${entry.owner.id}`}
            className="underline-offset-4 hover:underline"
        >
            {entry.owner.name}
        </Link>
    );
}
