import { useState } from 'react';
import { Head, Link, router } from '@inertiajs/react';
import {
    ArrowLeft,
    ArrowUpRight,
    Award,
    BatteryCharging,
    Camera,
    CheckCircle2,
    ClipboardCheck,
    Copy,
    Download,
    FileText,
    Gauge,
    Info,
    Link2,
    Lock,
    Mail,
    MessageSquare,
    PencilRuler,
    ShieldAlert,
    ShieldCheck,
    Signature,
    Smartphone,
    Sun,
    TimerReset,
    Trash2,
    TriangleAlert,
    Unlink,
    UserRound,
    XCircle,
} from 'lucide-react';
import {
    Callout,
    EmptyState,
    KeyValueGrid,
    PageHeader,
    SectionCard,
} from '@/components/crm/page-header';
import { StatusPill } from '@/components/crm/status-badge';
import { Button } from '@/components/ui/button';
import { copyToClipboard } from '@/lib/clipboard';
import { formatDate, formatDateTime } from '@/lib/format';
import { cn } from '@/lib/utils';
import { show as jobShow } from '@/routes/jobs';
import { index as inspectionsIndex } from '@/routes/inspections';
import type {
    InspectionAttachment,
    InspectionChecklistSection,
    InspectionDetail,
    InspectionIntakeCandidate,
} from '@/types';

type PageProps = {
    report: InspectionDetail;
    /** Who the typed name and address might be, when nothing is linked yet. */
    linkCandidates: InspectionIntakeCandidate[];
    can: { manage: boolean; delete: boolean };
};

const ANSWER_STYLES: Record<
    string,
    { label: string; className: string; icon: typeof CheckCircle2 }
> = {
    pass: {
        label: 'Pass',
        className: 'text-emerald-700 dark:text-emerald-400',
        icon: CheckCircle2,
    },
    fail: {
        label: 'Fail',
        className: 'text-red-700 dark:text-red-400',
        icon: XCircle,
    },
    na: {
        label: 'N/A',
        className: 'text-muted-foreground',
        icon: Info,
    },
};

const SEVERITY_TONES: Record<string, string> = {
    critical: 'red',
    major: 'amber',
    minor: 'slate',
};

const SYSTEM_ICONS: Record<string, typeof Sun> = {
    pv: Sun,
    hybrid: BatteryCharging,
    battery: BatteryCharging,
    offgrid: BatteryCharging,
};

/**
 * One inspection report, as the office reads it.
 *
 * It is laid out in the order the crew was asked: what the system is, the
 * checklist section by section, the readings, the defects, the photographs and
 * finally the declaration. The review sits at the top while it is outstanding,
 * because that is the one action a submitted report is waiting for.
 */
export default function InspectionShow({
    report,
    linkCandidates,
    can,
}: PageProps) {
    const [copied, setCopied] = useState(false);
    const [note, setNote] = useState('');
    const [sending, setSending] = useState(false);
    const [attachSite, setAttachSite] = useState<number | null>(null);

    const attach = (event: React.FormEvent) => {
        event.preventDefault();

        if (attachSite === null) {
            return;
        }

        router.post(
            `/inspections/${report.id}/attach`,
            { site_id: attachSite },
            { preserveScroll: true },
        );
    };

    const data = report.data;
    const answers = data?.answers ?? {};
    const itemNotes = data?.item_notes ?? {};
    const measurements = data?.measurements ?? {};
    const defects = data?.defects ?? [];
    const photos = report.attachments.filter((file) => file.kind === 'photo');
    const documents = report.attachments.filter((file) => file.kind === 'document');
    const signatures = report.attachments.filter((file) => file.kind === 'signature');
    const signatureImage = signatures.find((file) => file.is_image) ?? null;
    const systemType = data?.system?.type ?? 'pv';
    const SystemIcon = SYSTEM_ICONS[systemType] ?? Sun;

    const copyLink = async () => {
        // Works on a plain-HTTP host as well as HTTPS: see lib/clipboard.
        const copied = await copyToClipboard(report.share_url);

        setCopied(copied);

        if (copied) {
            window.setTimeout(() => setCopied(false), 2000);
        }
    };

    const post = (path: string, payload: Record<string, string> = {}) => {
        setSending(true);
        router.post(path, payload, {
            preserveScroll: true,
            onFinish: () => setSending(false),
        });
    };

    const submitReview = (event: React.FormEvent) => {
        event.preventDefault();
        post(`/inspections/${report.id}/review`, { note });
    };

    const remove = () => {
        // A report that already holds answers is a different thing to delete
        // from an empty link, so the question says which one it is.
        const answered = report.data !== null;

        const question = answered
            ? `Remove ${report.reference}? Its answers, photos and documents are deleted with it, and nothing here brings them back — only a backup.`
            : `Remove ${report.reference}? The link stops working and the report is deleted.`;

        if (!window.confirm(question)) {
            return;
        }

        router.delete(`/inspections/${report.id}`);
    };

    return (
        <>
            <Head title={`${report.reference} — inspection report`} />

            <div className="flex flex-col gap-5">
                <PageHeader
                    eyebrow={
                        <>
                            <ClipboardCheck className="text-solar size-3.5" />
                            <span>{report.purpose.label}</span>
                            {report.job ? (
                                <span className="text-muted-foreground/60">·</span>
                            ) : null}
                            {report.job ? (
                                <Link
                                    href={jobShow(report.job.id)}
                                    className="hover:text-foreground inline-flex items-center gap-1"
                                >
                                    Job {report.job.job_number}
                                    <ArrowUpRight className="size-3" />
                                </Link>
                            ) : null}
                        </>
                    }
                    title={report.reference}
                    description={
                        report.customer
                            ? `${report.customer.name} — ${report.site?.address ?? 'no site on file'}`
                            : 'Not linked to a customer'
                    }
                    actions={
                        <>
                            <Button variant="ghost" size="sm" asChild>
                                <Link href={inspectionsIndex()}>
                                    <ArrowLeft />
                                    All reports
                                </Link>
                            </Button>
                            <Button variant="outline" size="sm" asChild>
                                <a href={`/inspections/${report.id}/pack`}>
                                    <Download />
                                    Download pack
                                </a>
                            </Button>
                            <Button variant="outline" size="sm" onClick={copyLink}>
                                {copied ? <CheckCircle2 /> : <Copy />}
                                {copied ? 'Copied' : 'Copy link'}
                            </Button>
                            {can.manage && report.status.value === 'invited' ? (
                                <Button
                                    size="sm"
                                    disabled={sending}
                                    onClick={() => post(`/inspections/${report.id}/resend`)}
                                >
                                    <Mail />
                                    Email it again
                                </Button>
                            ) : null}
                        </>
                    }
                />

                <div className="flex flex-wrap items-center gap-2">
                    <StatusPill tone={report.status.color}>{report.status.label}</StatusPill>
                    {report.outcome ? (
                        <StatusPill tone={report.outcome.color}>
                            {report.outcome.full_label ?? report.outcome.label}
                        </StatusPill>
                    ) : null}
                    {report.source.value === 'self_service' ? (
                        <StatusPill tone="violet">
                            <Smartphone className="size-3" />
                            Opened on site
                        </StatusPill>
                    ) : null}
                    {!report.client_linked ? (
                        <StatusPill tone="amber">
                            <Unlink className="size-3" />
                            No client linked
                        </StatusPill>
                    ) : null}
                    {report.system_kw !== null ? (
                        <StatusPill tone="slate">{report.system_kw} kW</StatusPill>
                    ) : null}
                    {report.defect_count > 0 ? (
                        <StatusPill tone="amber">
                            {report.defect_count} defect
                            {report.defect_count === 1 ? '' : 's'}
                        </StatusPill>
                    ) : null}
                </div>

                {report.status.value === 'submitted' ? (
                    <Callout
                        tone={report.outcome?.value === 'fail' ? 'red' : 'amber'}
                        icon={report.outcome?.value === 'fail' ? ShieldAlert : ClipboardCheck}
                        title="Submitted and waiting to be read"
                    >
                        {report.outcome?.value === 'fail'
                            ? 'The crew failed this system. Nothing should be energised or handed over until the defects are fixed and it is reinspected.'
                            : 'The crew has finished. Read it, then record the review so the office knows it has been seen.'}
                    </Callout>
                ) : null}

                {report.status.value === 'expired' ? (
                    <Callout tone="slate" icon={Lock} title="The link has closed">
                        Nothing more can be added by the crew. Everything already
                        in the report is kept, and it can still be downloaded.
                    </Callout>
                ) : null}

                <div className="grid gap-5 lg:grid-cols-3">
                    <div className="flex flex-col gap-5 lg:col-span-2">
                        <SectionCard
                            title="The system"
                            description="As the crew recorded it, with the job's own details alongside."
                            icon={SystemIcon}
                            tone="solar"
                        >
                            <KeyValueGrid
                                columns={3}
                                items={[
                                    {
                                        label: 'System type',
                                        value:
                                            report.checklist.system_types.find(
                                                (type) => type.value === systemType,
                                            )?.label ?? systemType,
                                    },
                                    {
                                        label: 'Size',
                                        value:
                                            data?.system?.kw ??
                                            report.system.size_kw ??
                                            '—',
                                        // kW is added below rather than in the label.
                                    },
                                    {
                                        label: 'Modules',
                                        value:
                                            data?.system?.modules ??
                                            report.system.panel ??
                                            '—',
                                    },
                                    {
                                        label: 'Inverter',
                                        value:
                                            data?.system?.inverter ??
                                            report.system.inverter ??
                                            '—',
                                    },
                                    {
                                        label: 'Battery',
                                        value:
                                            data?.system?.battery ??
                                            report.system.battery ??
                                            '—',
                                    },
                                    {
                                        label: 'Monitoring',
                                        value: data?.system?.monitoring ?? '—',
                                    },
                                    {
                                        label: 'Installed',
                                        value: data?.system?.installed_on
                                            ? formatDate(data.system.installed_on)
                                            : '—',
                                    },
                                    {
                                        label: 'Serials',
                                        value: data?.system?.serials ?? '—',
                                    },
                                    {
                                        label: 'NMI',
                                        value:
                                            data?.site?.nmi ??
                                            report.job?.site?.nmi ??
                                            '—',
                                    },
                                    {
                                        label: 'Meter number',
                                        value:
                                            data?.site?.meter_number ??
                                            report.job?.site?.meter_number ??
                                            '—',
                                    },
                                    {
                                        label: 'Network',
                                        value:
                                            data?.site?.dnsp ??
                                            report.job?.site?.dnsp ??
                                            '—',
                                    },
                                    {
                                        label: 'Supply',
                                        value:
                                            (data?.site?.phase ?? report.job?.site?.phase) ===
                                            'three'
                                                ? 'Three phase'
                                                : 'Single phase',
                                    },
                                    {
                                        label: 'Switchboard',
                                        value: data?.site?.switchboard ?? '—',
                                    },
                                    {
                                        label: 'Roof',
                                        value: [
                                            data?.site?.roof_type ??
                                                report.job?.site?.roof,
                                            data?.site?.roof_condition
                                                ? `condition ${data.site.roof_condition}`
                                                : null,
                                            data?.site?.tilt
                                                ? `${data.site.tilt}° tilt`
                                                : null,
                                            data?.site?.azimuth,
                                        ]
                                            .filter(Boolean)
                                            .join(' · '),
                                    },
                                    {
                                        label: 'Access notes',
                                        value:
                                            data?.site?.access_notes ??
                                            report.job?.site?.access_notes ??
                                            '—',
                                    },
                                ]}
                            />
                        </SectionCard>

                        <SectionCard
                            title="The checklist"
                            description={
                                report.submitted_at
                                    ? 'Every item answered on site, section by section.'
                                    : 'Nothing answered yet — the crew still has the link.'
                            }
                            icon={ClipboardCheck}
                            tone="emerald"
                            flush
                        >
                            {report.submitted_at ? (
                                <div className="divide-y divide-hairline">
                                    {report.checklist.sections
                                        .filter(
                                            (section) =>
                                                !section.battery_only ||
                                                ['hybrid', 'battery'].includes(systemType),
                                        )
                                        .map((section) => (
                                            <ChecklistBlock
                                                key={section.key}
                                                section={section}
                                                answers={answers[section.key] ?? {}}
                                                notes={itemNotes[section.key] ?? {}}
                                            />
                                        ))}
                                </div>
                            ) : (
                                <div className="px-5 pb-5">
                                    <EmptyState
                                        icon={TimerReset}
                                        title="Waiting on the crew"
                                        description={
                                            report.status.value === 'invited'
                                                ? `The link works until ${formatDate(report.expires_at)}. Answers, photos and the signature appear here the moment it is submitted.`
                                                : 'The link closed before the report was submitted.'
                                        }
                                    />
                                </div>
                            )}
                        </SectionCard>

                        {report.submitted_at ? (
                            <SectionCard
                                title="Test results"
                                description="The readings the crew measured, with the instrument behind them."
                                icon={Gauge}
                                tone="blue"
                            >
                                <div className="grid gap-x-8 gap-y-4 sm:grid-cols-2">
                                    {Object.entries(report.checklist.measurements).map(
                                        ([key, measurement]) => (
                                            <div
                                                key={key}
                                                className="border-hairline flex items-baseline justify-between gap-4 border-b pb-2"
                                            >
                                                <span className="text-muted-foreground text-xs">
                                                    {measurement.label}
                                                </span>
                                                <span className="crm-num text-sm font-medium">
                                                    {measurements[key] ?? '—'}
                                                    {measurements[key] ? (
                                                        <span className="text-muted-foreground ml-1 text-xs">
                                                            {measurement.unit}
                                                        </span>
                                                    ) : null}
                                                </span>
                                            </div>
                                        ),
                                    )}
                                </div>
                                <p className="text-muted-foreground mt-4 text-xs">
                                    Instrument:{' '}
                                    <span className="text-foreground font-medium">
                                        {measurements.instrument ?? '—'}
                                    </span>
                                    {measurements.calibration_due
                                        ? ` · calibrated to ${formatDate(
                                              measurements.calibration_due,
                                          )}`
                                        : ''}
                                </p>
                            </SectionCard>
                        ) : null}

                        {defects.length > 0 ? (
                            <SectionCard
                                title={`Defects (${defects.length})`}
                                description="What has to be fixed, how serious it is, and who owes it."
                                icon={TriangleAlert}
                                tone="red"
                                flush
                            >
                                <ul className="divide-y divide-hairline">
                                    {defects.map((defect, index) => (
                                        <li
                                            key={`${defect.title}-${index}`}
                                            className="px-5 py-4"
                                        >
                                            <div className="flex flex-wrap items-center gap-2">
                                                <StatusPill
                                                    tone={
                                                        SEVERITY_TONES[defect.severity] ??
                                                        'slate'
                                                    }
                                                >
                                                    {defect.severity}
                                                </StatusPill>
                                                {defect.due ? (
                                                    <span className="text-muted-foreground text-xs">
                                                        Due {formatDate(defect.due)}
                                                    </span>
                                                ) : null}
                                            </div>
                                            <p className="mt-2 text-sm font-medium">
                                                {defect.title}
                                            </p>
                                            {defect.description ? (
                                                <p className="text-muted-foreground mt-1 text-xs leading-relaxed">
                                                    {defect.description}
                                                </p>
                                            ) : null}
                                            {defect.action ? (
                                                <p className="mt-1.5 text-xs">
                                                    <span className="text-muted-foreground">
                                                        Action:{' '}
                                                    </span>
                                                    {defect.action}
                                                </p>
                                            ) : null}
                                        </li>
                                    ))}
                                </ul>
                            </SectionCard>
                        ) : null}

                        {data?.findings || data?.recommendations || data?.customer?.comment ? (
                            <SectionCard
                                title="In the crew's words"
                                icon={MessageSquare}
                                tone="violet"
                            >
                                <div className="space-y-4 text-sm leading-relaxed">
                                    {data?.findings ? (
                                        <div>
                                            <p className="crm-label mb-1">Findings</p>
                                            <p className="whitespace-pre-line">
                                                {data.findings}
                                            </p>
                                        </div>
                                    ) : null}
                                    {data?.recommendations ? (
                                        <div>
                                            <p className="crm-label mb-1">
                                                Recommendations
                                            </p>
                                            <p className="whitespace-pre-line">
                                                {data.recommendations}
                                            </p>
                                        </div>
                                    ) : null}
                                    {data?.customer?.comment ? (
                                        <div>
                                            <p className="crm-label mb-1">
                                                Customer comments
                                            </p>
                                            <p className="whitespace-pre-line">
                                                {data.customer.comment}
                                            </p>
                                        </div>
                                    ) : null}
                                </div>
                            </SectionCard>
                        ) : null}

                        <SectionCard
                            title={`Photos and documents${
                                report.attachments.length > 0
                                    ? ` (${report.attachments.length})`
                                    : ''
                            }`}
                            description="Files the crew attached on site. Click one to open it full size."
                            icon={Camera}
                            tone="slate"
                        >
                            {report.attachments.length === 0 ? (
                                <EmptyState
                                    icon={Camera}
                                    title="No files yet"
                                    description="Photos, PDFs and Word documents appear here as the crew uploads them."
                                />
                            ) : (
                                <div className="space-y-4">
                                    {photos.length > 0 ? (
                                        <div className="grid grid-cols-2 gap-2 sm:grid-cols-3">
                                            {photos.map((photo) => (
                                                <a
                                                    key={photo.id}
                                                    href={photo.url}
                                                    target="_blank"
                                                    rel="noreferrer"
                                                    className="group ring-hairline relative aspect-[4/3] overflow-hidden rounded-lg ring-1"
                                                >
                                                    {photo.is_image ? (
                                                        <img
                                                            src={photo.url}
                                                            alt={
                                                                photo.caption ??
                                                                photo.name
                                                            }
                                                            className="size-full object-cover transition-transform group-hover:scale-[1.02]"
                                                            loading="lazy"
                                                        />
                                                    ) : (
                                                        <span className="text-muted-foreground flex size-full items-center justify-center text-xs">
                                                            {photo.label}
                                                        </span>
                                                    )}
                                                    {photo.caption ? (
                                                        <span className="absolute inset-x-0 bottom-0 bg-black/55 px-2 py-1 text-[11px] text-white">
                                                            {photo.caption}
                                                        </span>
                                                    ) : null}
                                                </a>
                                            ))}
                                        </div>
                                    ) : null}

                                    {documents.length > 0 ? (
                                        <ul className="divide-y divide-hairline">
                                            {documents.map((document) => (
                                                <AttachmentRow
                                                    key={document.id}
                                                    file={document}
                                                    icon={FileText}
                                                />
                                            ))}
                                        </ul>
                                    ) : null}

                                    {signatures.length > 0 ? (
                                        <div>
                                            <p className="crm-label mb-1">
                                                Signed declaration
                                            </p>
                                            <ul className="divide-y divide-hairline">
                                                {signatures.map((signature) => (
                                                    <AttachmentRow
                                                        key={signature.id}
                                                        file={signature}
                                                        icon={Signature}
                                                    />
                                                ))}
                                            </ul>
                                        </div>
                                    ) : null}
                                </div>
                            )}
                        </SectionCard>

                        <SectionCard
                            title="Declaration"
                            description="What the person who did the inspection signed."
                            icon={ShieldCheck}
                            tone="emerald"
                        >
                            {report.submitted_at ? (
                                <div className="grid gap-5 sm:grid-cols-2">
                                    <KeyValueGrid
                                        columns={1}
                                        items={[
                                            {
                                                label: 'Signature',
                                                value: signatureImage ? (
                                                    <a
                                                        href={signatureImage.url}
                                                        target="_blank"
                                                        rel="noreferrer"
                                                        className="inline-block"
                                                    >
                                                        <img
                                                            src={signatureImage.url}
                                                            alt="Signature"
                                                            className="ring-hairline bg-white max-h-24 rounded-md p-1 ring-1"
                                                        />
                                                    </a>
                                                ) : (
                                                    'On file'
                                                ),
                                            },
                                            {
                                                label: 'Name',
                                                value:
                                                    data?.declaration?.name ??
                                                    report.inspector_name ??
                                                    '—',
                                            },
                                            {
                                                label: 'Company',
                                                value: data?.declaration?.company ?? '—',
                                            },
                                            {
                                                label: 'Licence',
                                                value:
                                                    data?.declaration?.licence ??
                                                    report.inspector_licence ??
                                                    '—',
                                            },
                                            {
                                                label: 'Signed on',
                                                value: data?.declaration?.date
                                                    ? formatDate(data.declaration.date)
                                                    : report.inspected_on
                                                      ? formatDate(report.inspected_on)
                                                      : '—',
                                            },
                                            {
                                                label: 'Submitted',
                                                value: formatDateTime(report.submitted_at),
                                            },
                                        ]}
                                    />
                                    <div className="text-muted-foreground bg-muted/40 rounded-lg px-4 py-3 text-xs leading-relaxed">
                                        I certify that I carried out this
                                        inspection, that the results recorded are
                                        the readings I measured on site, and that
                                        the work complies with the standards named
                                        above except where a defect is listed.
                                        {data?.declaration?.agreed ? (
                                            <p className="text-foreground mt-2 font-medium">
                                                Declaration accepted on submission.
                                            </p>
                                        ) : null}
                                    </div>
                                </div>
                            ) : (
                                <p className="text-muted-foreground text-sm">
                                    Signed when the crew submits. Nothing has been
                                    signed yet.
                                </p>
                            )}
                        </SectionCard>
                    </div>

                    <div className="flex flex-col gap-5">
                        <SectionCard
                            title="The link"
                            description="Share it with the crew. It is the only key — no sign-in needed."
                            icon={Link2}
                            tone="amber"
                        >
                            <label className="crm-label" htmlFor="share_url">
                                Public address
                            </label>
                            <div className="mt-1 flex gap-2">
                                <input
                                    id="share_url"
                                    readOnly
                                    value={report.share_url}
                                    onFocus={(event) => event.currentTarget.select()}
                                    className="border-hairline bg-muted/40 focus-visible:ring-solar/40 w-full rounded-md border px-2.5 py-1.5 font-mono text-[11px] outline-none focus-visible:ring-2"
                                />
                                <Button
                                    type="button"
                                    size="sm"
                                    variant="outline"
                                    onClick={copyLink}
                                >
                                    {copied ? <CheckCircle2 /> : <Copy />}
                                </Button>
                            </div>

                            <div className="text-muted-foreground mt-3 space-y-1 text-xs">
                                {report.status.value === 'invited' ? (
                                    <p>
                                        {report.expires_at
                                            ? `Works until ${formatDate(report.expires_at)}${
                                                  report.link_days_left !== null
                                                      ? ` — ${Math.max(
                                                            report.link_days_left,
                                                            0,
                                                        )} days left`
                                                      : ''
                                              }.`
                                            : 'No expiry on this link.'}
                                    </p>
                                ) : (
                                    <p>The link is closed to further answers.</p>
                                )}
                                <p>
                                    Sent{' '}
                                    {report.sent_at
                                        ? formatDate(report.sent_at)
                                        : 'not yet'}
                                    {report.submitted_at
                                        ? ` · submitted ${formatDate(report.submitted_at)}`
                                        : ''}
                                </p>
                            </div>

                            {can.manage && report.status.value === 'invited' ? (
                                <div className="mt-4 flex flex-wrap gap-2">
                                    <Button
                                        size="sm"
                                        variant="outline"
                                        disabled={sending}
                                        onClick={() =>
                                            post(`/inspections/${report.id}/reissue`)
                                        }
                                    >
                                        <TimerReset />
                                        Give it another 30 days
                                    </Button>
                                    <Button
                                        size="sm"
                                        variant="ghost"
                                        disabled={sending}
                                        onClick={() =>
                                            post(`/inspections/${report.id}/close`)
                                        }
                                    >
                                        <Lock />
                                        Close the link
                                    </Button>
                                </div>
                            ) : null}
                        </SectionCard>

                        <SectionCard
                            title="The job"
                            icon={ClipboardCheck}
                        >
                            {report.job ? (
                                <>
                                    <KeyValueGrid
                                        columns={1}
                                        items={[
                                            {
                                                label: 'Job',
                                                value: (
                                                    <Link
                                                        href={jobShow(report.job.id)}
                                                        className="hover:underline"
                                                    >
                                                        {report.job.job_number}
                                                        {report.job.title
                                                            ? ` · ${report.job.title}`
                                                            : ''}
                                                    </Link>
                                                ),
                                            },
                                            {
                                                label: 'Status',
                                                value: (
                                                    <StatusPill
                                                        tone={report.job.status.color}
                                                    >
                                                        {report.job.status.label}
                                                    </StatusPill>
                                                ),
                                            },
                                            {
                                                label: 'Customer',
                                                value: report.customer?.name ?? '—',
                                            },
                                            {
                                                label: 'Phone',
                                                value: report.job.customer?.phone ?? '—',
                                            },
                                            {
                                                label: 'Site',
                                                value: report.site?.address ?? '—',
                                            },
                                            {
                                                label: 'Crew on the job',
                                                value: report.job.installer ?? '—',
                                            },
                                        ]}
                                    />
                                    <p className="text-muted-foreground mt-3 text-xs">
                                        Requested by{' '}
                                        {report.creator?.name ?? 'the system'} on{' '}
                                        {formatDate(report.created_at)}.
                                    </p>
                                </>
                            ) : report.source.value === 'self_service' ? (
                                <>
                                    <p className="text-muted-foreground text-sm">
                                        No job was raised before this visit. A crew
                                        opened the report on site from the
                                        standing warranty link, for a client they
                                        did not find on file.
                                    </p>
                                    <KeyValueGrid
                                        columns={1}
                                        items={[
                                            {
                                                label: 'Customer as typed',
                                                value:
                                                    report.intake.customer_name ??
                                                    '—',
                                            },
                                            {
                                                label: 'Phone as typed',
                                                value:
                                                    report.intake.customer_phone ??
                                                    '—',
                                            },
                                            {
                                                label: 'Address as typed',
                                                value:
                                                    [
                                                        report.intake.address,
                                                        report.intake.suburb,
                                                        report.intake.state,
                                                        report.intake.postcode,
                                                    ]
                                                        .filter(Boolean)
                                                        .join(', ') || '—',
                                            },
                                        ]}
                                    />
                                </>
                            ) : (
                                <p className="text-muted-foreground text-sm">
                                    This job is no longer on file.
                                </p>
                            )}
                        </SectionCard>

                        {can.manage && !report.client_linked ? (
                            <SectionCard
                                title="Link this report to a client"
                                description="The name and address the crew typed, matched against the CRM. Confirming one files the report against that client; their record is not changed."
                                icon={UserRound}
                                tone="amber"
                            >
                                {linkCandidates.length === 0 ? (
                                    <p className="text-muted-foreground text-sm leading-relaxed">
                                        Nothing in the CRM looks like that name and
                                        address. The report stays as it is — the
                                        typed name, phone and address are already
                                        on it — and can be linked once the client
                                        exists here.
                                    </p>
                                ) : (
                                    <form onSubmit={attach} className="space-y-2.5">
                                        {linkCandidates.map((candidate) => (
                                            <label
                                                key={candidate.id}
                                                className={cn(
                                                    'flex cursor-pointer items-start gap-2.5 rounded-lg px-3 py-2.5 ring-1 transition-colors',
                                                    attachSite === candidate.id
                                                        ? 'bg-solar-soft/60 ring-solar/40'
                                                        : 'ring-hairline hover:bg-muted/50',
                                                )}
                                            >
                                                <input
                                                    type="radio"
                                                    name="site_id"
                                                    value={candidate.id}
                                                    checked={
                                                        attachSite === candidate.id
                                                    }
                                                    onChange={() =>
                                                        setAttachSite(
                                                            candidate.id,
                                                        )
                                                    }
                                                    className="mt-1"
                                                />
                                                <span className="min-w-0">
                                                    <span className="block text-sm font-medium">
                                                        {candidate.customer}
                                                    </span>
                                                    <span className="text-muted-foreground block text-xs">
                                                        {candidate.address}
                                                    </span>
                                                    <span className="text-muted-foreground block text-[11px]">
                                                        {candidate.reason}
                                                        {candidate.job
                                                            ? ` · last job ${candidate.job.job_number}`
                                                            : ' · no jobs recorded'}
                                                    </span>
                                                </span>
                                            </label>
                                        ))}

                                        <Button
                                            size="sm"
                                            type="submit"
                                            disabled={attachSite === null}
                                        >
                                            Link to this client
                                        </Button>
                                    </form>
                                )}
                            </SectionCard>
                        ) : null}

                        {report.status.value === 'submitted' || can.manage ? (
                            <SectionCard
                                title="Review"
                                description={
                                    report.status.value === 'reviewed'
                                        ? `Read by ${report.reviewer?.name ?? 'the office'} on ${formatDate(report.reviewed_at)}.`
                                        : 'Record that you have read it, with a note for the file.'
                                }
                                icon={Award}
                                tone="blue"
                            >
                                {data?.review?.note ? (
                                    <p className="bg-muted/40 mb-3 rounded-lg px-3 py-2 text-sm whitespace-pre-line">
                                        {data.review.note}
                                    </p>
                                ) : null}

                                {report.status.value === 'submitted' ? (
                                    <form onSubmit={submitReview} className="space-y-3">
                                        <textarea
                                            value={note}
                                            onChange={(event) =>
                                                setNote(event.target.value)
                                            }
                                            rows={3}
                                            className="border-input focus-visible:border-ring focus-visible:ring-ring/50 min-h-24 w-full rounded-md border bg-transparent px-3 py-2 text-sm shadow-xs outline-none focus-visible:ring-[3px]"
                                            placeholder="What the office did with it: the claim lodged, the work booked, the customer told."
                                        />
                                        <Button
                                            type="submit"
                                            size="sm"
                                            disabled={sending}
                                            className="w-full"
                                        >
                                            <CheckCircle2 />
                                            Mark as reviewed
                                        </Button>
                                    </form>
                                ) : null}

                                {can.manage && report.status.value === 'reviewed' ? (
                                    <p className="text-muted-foreground text-xs">
                                        Reviewed reports stay readable and
                                        downloadable; nothing can be changed by the
                                        crew now.
                                    </p>
                                ) : null}
                            </SectionCard>
                        ) : null}

                        <SectionCard title="What this is" icon={PencilRuler}>
                            <p className="text-muted-foreground text-xs leading-relaxed">
                                The checklist follows AS/NZS 5033 for the array
                                and DC wiring, AS/NZS 4777.2 for the inverter and
                                its grid connection, AS/NZS 5139 for battery
                                storage, and AS/NZS 3000 for earthing and the
                                electrical tests. It records what the crew
                                observed and measured; it is not a certificate
                                of compliance, and the electrical certificate
                                for the install is separate.
                            </p>
                        </SectionCard>

                        {can.delete ? (
                            <Button
                                variant="ghost"
                                size="sm"
                                className="text-red-600 hover:text-red-700 dark:text-red-400"
                                onClick={remove}
                            >
                                <Trash2 />
                                Remove this report
                            </Button>
                        ) : null}
                    </div>
                </div>
            </div>
        </>
    );
}

function ChecklistBlock({
    section,
    answers,
    notes,
}: {
    section: InspectionChecklistSection;
    answers: Record<string, string>;
    notes: Record<string, string>;
}) {
    const answered = section.items.filter((item) => answers[item.key]).length;

    return (
        <div className="px-5 py-4">
            <div className="flex flex-wrap items-baseline justify-between gap-2">
                <h3 className="text-sm font-semibold">{section.title}</h3>
                <span className="text-muted-foreground crm-num text-xs">
                    {answered}/{section.items.length}
                </span>
            </div>
            <p className="text-muted-foreground mt-0.5 text-xs">
                {section.standard}
            </p>

            <ul className="mt-3 space-y-1.5">
                {section.items.map((item) => {
                    const value = answers[item.key];
                    const style = value ? ANSWER_STYLES[value] : null;
                    const Icon = style?.icon ?? Info;

                    return (
                        <li
                            key={item.key}
                            className="flex items-start gap-2.5 text-sm"
                        >
                            <Icon
                                className={cn(
                                    'mt-0.5 size-3.5 shrink-0',
                                    style?.className ??
                                        'text-muted-foreground/50',
                                )}
                            />
                            <div className="min-w-0 flex-1">
                                <span className="flex flex-wrap items-baseline justify-between gap-x-3">
                                    <span className="text-[13px] leading-snug">
                                        {item.label}
                                    </span>
                                    <span
                                        className={cn(
                                            'crm-label shrink-0',
                                            style?.className,
                                        )}
                                    >
                                        {style?.label ?? 'Not answered'}
                                    </span>
                                </span>
                                {notes[item.key] ? (
                                    <p className="text-muted-foreground mt-0.5 text-xs leading-relaxed">
                                        {notes[item.key]}
                                    </p>
                                ) : null}
                            </div>
                        </li>
                    );
                })}
            </ul>
        </div>
    );
}

function AttachmentRow({
    file,
    icon: Icon,
}: {
    file: InspectionAttachment;
    icon: typeof FileText;
}) {
    return (
        <li className="flex items-center gap-3 py-2">
            <span className="bg-muted text-muted-foreground flex size-8 shrink-0 items-center justify-center rounded-md">
                <Icon className="size-4" />
            </span>
            <div className="min-w-0 flex-1">
                <a
                    href={file.url}
                    target="_blank"
                    rel="noreferrer"
                    className="block truncate text-sm hover:underline"
                >
                    {file.name}
                </a>
                <span className="text-muted-foreground text-xs">
                    {file.label} · {file.human_size}
                    {file.caption ? ` · ${file.caption}` : ''}
                </span>
            </div>
            {file.download_url ? (
                <Button asChild variant="ghost" size="sm">
                    <a href={file.download_url}>
                        <Download />
                    </a>
                </Button>
            ) : null}
        </li>
    );
}
