import { useState } from "react";
import { Form, Head, Link } from "@inertiajs/react";
import {
    ArrowUpRight,
    BriefcaseBusiness,
    Building2,
    CalendarDays,
    CircleAlert,
    Clock,
    FileText,
    KeyRound,
    Mail,
    MapPin,
    ShieldCheck,
    Sparkles,
    Target,
    UserRound,
} from "lucide-react";
import CustomerController from "@/actions/App/Http/Controllers/CustomerController";
import {
    DetailRow,
    EmptyState,
    MetaStrip,
    PageHeader,
    SectionCard,
} from "@/components/crm/page-header";
import { FormField, NativeSelect } from "@/components/crm/native-select";
import { StatusPill } from "@/components/crm/status-badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useInitials } from "@/hooks/use-initials";
import {
    formatAddress,
    formatDate,
    formatDateTime,
    formatRelative,
} from "@/lib/format";
import { index as accountsIndex } from "@/routes/customer-accounts";
import {
    index as customersIndex,
    show as customerShow,
} from "@/routes/customers";
import { create as jobCreate } from "@/routes/jobs";
import { create as ticketCreate } from "@/routes/tickets";
import type {
    CustomerChangeRequest,
    CustomerDetail,
    CustomerPortalAccount,
    OptionsBundle,
    ProfileHealth,
} from "@/types";

type Props = {
    customer: CustomerDetail;
    account: CustomerPortalAccount | null;
    pendingChange: CustomerChangeRequest | null;
    health: ProfileHealth;
    options: OptionsBundle;
    ticketCounts: { open: number; total: number };
    can: {
        update: boolean;
        delete: boolean;
        createJob: boolean;
        createTicket: boolean;
        manageAccounts: boolean;
        reviewChanges: boolean;
    };
};

/**
 * The client profile.
 *
 * The customer detail page answers "what work is there for this customer?".
 * This page answers "who is this customer?" — so it is built in a different
 * shape: a summary at the top, the person's details laid out as a form someone
 * can read straight through, and the relationship (sign-in, sites, pending
 * corrections, history) down the side where it is visible but out of the way.
 */
export default function CustomerProfile({
    customer,
    account,
    pendingChange,
    health,
    options,
    ticketCounts,
    can,
}: Props) {
    const getInitials = useInitials();
    const [type, setType] = useState(customer.type.value);

    const isOrganisation = type !== "residential";

    const billingAddress = formatAddress([
        customer.billing.line1,
        customer.billing.line2,
        customer.billing.suburb,
        customer.billing.state_label,
        customer.billing.postcode,
    ]);

    return (
        <>
            <Head title={`${customer.name} — profile`} />

            <Form
                {...CustomerController.updateProfile.form({
                    customer: customer.id,
                })}
                options={{ preserveScroll: true }}
                className="flex flex-col gap-5"
            >
                {({ processing, errors }) => (
                    <>
                        <PageHeader
                            eyebrow={
                                <>
                                    <Building2 className="text-solar size-3.5" />
                                    <span>{customer.customer_number}</span>
                                    <span
                                        aria-hidden
                                        className="text-muted-foreground/50"
                                    >
                                        ·
                                    </span>
                                    <span>{customer.type.label}</span>
                                    {customer.abn ? (
                                        <>
                                            <span
                                                aria-hidden
                                                className="text-muted-foreground/50"
                                            >
                                                ·
                                            </span>
                                            <span>ABN {customer.abn}</span>
                                        </>
                                    ) : null}
                                </>
                            }
                            title="Client profile"
                            description="The person or business behind the jobs. Keep their details, their sign-in and their sites in one place."
                            actions={
                                <>
                                    <Button variant="outline" size="sm" asChild>
                                        <Link href={customerShow(customer.id)}>
                                            Customer page
                                        </Link>
                                    </Button>
                                    {can.createJob ? (
                                        <Button
                                            variant="outline"
                                            size="sm"
                                            asChild
                                        >
                                            <Link
                                                href={jobCreate({
                                                    query: {
                                                        customer: customer.id,
                                                    },
                                                })}
                                            >
                                                New job
                                                <ArrowUpRight />
                                            </Link>
                                        </Button>
                                    ) : null}
                                    {can.update ? (
                                        <Button
                                            type="submit"
                                            disabled={processing}
                                        >
                                            {processing
                                                ? "Saving…"
                                                : "Save changes"}
                                        </Button>
                                    ) : null}
                                </>
                            }
                        />

                        {/* The identity card. It reads like a contact card
                            rather than a form, so the person is recognisable
                            before any field is touched. */}
                        <section className="shadow-card relative overflow-hidden rounded-2xl bg-gradient-to-br from-solar-soft/70 via-card to-card ring-1 ring-hairline">
                            <div className="pointer-events-none absolute -top-24 -right-16 size-64 rounded-full bg-solar/10 blur-3xl" />

                            <div className="relative flex flex-col gap-6 p-5 lg:flex-row lg:items-center lg:justify-between">
                                <div className="flex min-w-0 items-start gap-4">
                                    <span className="flex size-16 shrink-0 items-center justify-center rounded-2xl bg-solar-soft text-xl font-semibold text-solar-ink ring-1 ring-solar/20">
                                        {getInitials(customer.name)}
                                    </span>

                                    <div className="min-w-0">
                                        <div className="flex flex-wrap items-center gap-2">
                                            <h2 className="text-xl font-semibold tracking-tight">
                                                {customer.name}
                                            </h2>
                                            <StatusPill
                                                tone={
                                                    customer.type
                                                        .is_organisation
                                                        ? "violet"
                                                        : "blue"
                                                }
                                            >
                                                {customer.type.label}
                                            </StatusPill>
                                            <StatusPill
                                                tone={
                                                    customer.is_active
                                                        ? "success"
                                                        : "slate"
                                                }
                                            >
                                                {customer.is_active
                                                    ? "Active"
                                                    : "Inactive"}
                                            </StatusPill>
                                        </div>

                                        <p className="text-muted-foreground mt-1 text-sm">
                                            {billingAddress ||
                                                "No postal address recorded yet"}
                                        </p>

                                        <MetaStrip
                                            className="mt-3"
                                            items={[
                                                {
                                                    label: "Email",
                                                    value:
                                                        customer.email ?? "—",
                                                },
                                                {
                                                    label: "Phone",
                                                    value:
                                                        customer.phone ?? "—",
                                                },
                                                {
                                                    label: "Manager",
                                                    value:
                                                        customer.owner?.name ??
                                                        "Unassigned",
                                                },
                                                {
                                                    label: "Customer since",
                                                    value: formatDate(
                                                        customer.created_at,
                                                    ),
                                                },
                                            ]}
                                        />
                                    </div>
                                </div>

                                <CompletenessRing health={health} />
                            </div>
                        </section>

                        <div className="grid gap-4 lg:grid-cols-3">
                            <div className="flex flex-col gap-4 lg:col-span-2">
                                <SectionCard
                                    title="Who they are"
                                    description="The legal shape of the customer: a household, or a business with a company name and ABN."
                                    icon={UserRound}
                                    tone="solar"
                                >
                                    <div className="grid gap-4 sm:grid-cols-2">
                                        <FormField
                                            label="Customer type"
                                            htmlFor="type"
                                            error={errors.type}
                                            required
                                            hint="Switches the name fields below"
                                            className="sm:col-span-2"
                                        >
                                            <NativeSelect
                                                id="type"
                                                name="type"
                                                value={type}
                                                onChange={(event) =>
                                                    setType(event.target.value)
                                                }
                                            >
                                                {options.customerTypes.map(
                                                    (option) => (
                                                        <option
                                                            key={option.value}
                                                            value={option.value}
                                                        >
                                                            {option.label}
                                                        </option>
                                                    ),
                                                )}
                                            </NativeSelect>
                                        </FormField>

                                        {isOrganisation ? (
                                            <>
                                                <FormField
                                                    label="Company name"
                                                    htmlFor="company_name"
                                                    error={errors.company_name}
                                                    required
                                                    className="sm:col-span-2"
                                                >
                                                    <Input
                                                        id="company_name"
                                                        name="company_name"
                                                        defaultValue={
                                                            customer.company_name ??
                                                            ""
                                                        }
                                                        placeholder="As it appears on the ABN"
                                                    />
                                                </FormField>

                                                <FormField
                                                    label="ABN"
                                                    htmlFor="abn"
                                                    error={errors.abn}
                                                    hint="11 digits"
                                                >
                                                    <Input
                                                        id="abn"
                                                        name="abn"
                                                        inputMode="numeric"
                                                        defaultValue={
                                                            customer.abn ?? ""
                                                        }
                                                        placeholder="12 345 678 901"
                                                    />
                                                </FormField>

                                                <FormField
                                                    label="ACN"
                                                    htmlFor="acn"
                                                    error={errors.acn}
                                                    hint="9 digits, if registered"
                                                >
                                                    <Input
                                                        id="acn"
                                                        name="acn"
                                                        inputMode="numeric"
                                                        defaultValue={
                                                            customer.acn ?? ""
                                                        }
                                                        placeholder="123 456 789"
                                                    />
                                                </FormField>
                                            </>
                                        ) : null}

                                        <FormField
                                            label={
                                                isOrganisation
                                                    ? "Contact first name"
                                                    : "First name"
                                            }
                                            htmlFor="first_name"
                                            error={errors.first_name}
                                            required={!isOrganisation}
                                        >
                                            <Input
                                                id="first_name"
                                                name="first_name"
                                                autoComplete="given-name"
                                                defaultValue={
                                                    customer.first_name ?? ""
                                                }
                                            />
                                        </FormField>

                                        <FormField
                                            label={
                                                isOrganisation
                                                    ? "Contact last name"
                                                    : "Last name"
                                            }
                                            htmlFor="last_name"
                                            error={errors.last_name}
                                            required={!isOrganisation}
                                        >
                                            <Input
                                                id="last_name"
                                                name="last_name"
                                                autoComplete="family-name"
                                                defaultValue={
                                                    customer.last_name ?? ""
                                                }
                                            />
                                        </FormField>

                                        <FormField
                                            label="Account status"
                                            htmlFor="is_active"
                                            error={errors.is_active}
                                            hint="Inactive keeps their history but hides them from lists"
                                            className="sm:col-span-2"
                                        >
                                            <>
                                                <input
                                                    type="hidden"
                                                    name="is_active"
                                                    value="0"
                                                />
                                                <label className="ring-hairline hover:bg-accent/40 flex cursor-pointer items-center gap-3 rounded-lg px-3 py-2.5 ring-1 ring-inset">
                                                    <input
                                                        id="is_active"
                                                        name="is_active"
                                                        type="checkbox"
                                                        value="1"
                                                        defaultChecked={
                                                            customer.is_active
                                                        }
                                                        className="border-input size-4 shrink-0 rounded border"
                                                    />
                                                    <span className="text-sm">
                                                        Active customer — they
                                                        appear in lists and can
                                                        be chosen for new work
                                                    </span>
                                                </label>
                                            </>
                                        </FormField>
                                    </div>
                                </SectionCard>

                                <SectionCard
                                    title="How to reach them"
                                    description="The details the office and the crews use, and that the customer can correct from the portal."
                                    icon={Mail}
                                    tone="info"
                                >
                                    <div className="grid gap-4 sm:grid-cols-2">
                                        <FormField
                                            label="Email"
                                            htmlFor="email"
                                            error={errors.email}
                                            hint="Also their portal sign-in where one exists"
                                        >
                                            <Input
                                                id="email"
                                                name="email"
                                                type="email"
                                                autoComplete="email"
                                                defaultValue={
                                                    customer.email ?? ""
                                                }
                                            />
                                        </FormField>

                                        <FormField
                                            label="Phone"
                                            htmlFor="phone"
                                            error={errors.phone}
                                        >
                                            <Input
                                                id="phone"
                                                name="phone"
                                                type="tel"
                                                autoComplete="tel"
                                                defaultValue={
                                                    customer.phone ?? ""
                                                }
                                            />
                                        </FormField>

                                        <FormField
                                            label="Alternate phone"
                                            htmlFor="alternate_phone"
                                            error={errors.alternate_phone}
                                        >
                                            <Input
                                                id="alternate_phone"
                                                name="alternate_phone"
                                                type="tel"
                                                defaultValue={
                                                    customer.alternate_phone ??
                                                    ""
                                                }
                                            />
                                        </FormField>

                                        <FormField
                                            label="Preferred contact"
                                            htmlFor="preferred_contact_method"
                                            error={
                                                errors.preferred_contact_method
                                            }
                                        >
                                            <NativeSelect
                                                id="preferred_contact_method"
                                                name="preferred_contact_method"
                                                defaultValue={
                                                    customer
                                                        .preferred_contact_method
                                                        ?.value ?? ""
                                                }
                                            >
                                                <option value="">
                                                    No preference
                                                </option>
                                                {options.contactMethods.map(
                                                    (option) => (
                                                        <option
                                                            key={option.value}
                                                            value={option.value}
                                                        >
                                                            {option.label}
                                                        </option>
                                                    ),
                                                )}
                                            </NativeSelect>
                                        </FormField>
                                    </div>
                                </SectionCard>

                                <SectionCard
                                    title="Postal address"
                                    description="Where invoices and paperwork go. The installation address lives on the site, not here."
                                    icon={MapPin}
                                    tone="violet"
                                >
                                    <div className="grid gap-4 sm:grid-cols-2">
                                        <FormField
                                            label="Address line 1"
                                            htmlFor="billing_address_line1"
                                            error={errors.billing_address_line1}
                                            className="sm:col-span-2"
                                        >
                                            <Input
                                                id="billing_address_line1"
                                                name="billing_address_line1"
                                                autoComplete="address-line1"
                                                defaultValue={
                                                    customer.billing.line1 ?? ""
                                                }
                                            />
                                        </FormField>

                                        <FormField
                                            label="Address line 2"
                                            htmlFor="billing_address_line2"
                                            error={errors.billing_address_line2}
                                            className="sm:col-span-2"
                                        >
                                            <Input
                                                id="billing_address_line2"
                                                name="billing_address_line2"
                                                autoComplete="address-line2"
                                                defaultValue={
                                                    customer.billing.line2 ?? ""
                                                }
                                            />
                                        </FormField>

                                        <FormField
                                            label="Suburb"
                                            htmlFor="billing_suburb"
                                            error={errors.billing_suburb}
                                        >
                                            <Input
                                                id="billing_suburb"
                                                name="billing_suburb"
                                                autoComplete="address-level2"
                                                defaultValue={
                                                    customer.billing.suburb ??
                                                    ""
                                                }
                                            />
                                        </FormField>

                                        <FormField
                                            label="State"
                                            htmlFor="billing_state"
                                            error={errors.billing_state}
                                        >
                                            <NativeSelect
                                                id="billing_state"
                                                name="billing_state"
                                                defaultValue={
                                                    customer.billing.state ?? ""
                                                }
                                            >
                                                <option value="">
                                                    Select a state
                                                </option>
                                                {options.states.map(
                                                    (option) => (
                                                        <option
                                                            key={option.value}
                                                            value={option.value}
                                                        >
                                                            {option.label}
                                                        </option>
                                                    ),
                                                )}
                                            </NativeSelect>
                                        </FormField>

                                        <FormField
                                            label="Postcode"
                                            htmlFor="billing_postcode"
                                            error={errors.billing_postcode}
                                            hint="4 digits"
                                        >
                                            <Input
                                                id="billing_postcode"
                                                name="billing_postcode"
                                                inputMode="numeric"
                                                autoComplete="postal-code"
                                                defaultValue={
                                                    customer.billing.postcode ??
                                                    ""
                                                }
                                            />
                                        </FormField>
                                    </div>
                                </SectionCard>

                                <SectionCard
                                    title="Relationship"
                                    description="Where the customer came from and who looks after them."
                                    icon={Target}
                                    tone="amber"
                                >
                                    <div className="grid gap-4 sm:grid-cols-2">
                                        <FormField
                                            label="Account manager"
                                            htmlFor="owner_id"
                                            error={errors.owner_id}
                                            hint="Who the customer rings"
                                        >
                                            <NativeSelect
                                                id="owner_id"
                                                name="owner_id"
                                                defaultValue={
                                                    customer.owner?.id ?? ""
                                                }
                                            >
                                                <option value="">
                                                    Unassigned
                                                </option>
                                                {options.staff.map((option) => (
                                                    <option
                                                        key={option.value}
                                                        value={option.value}
                                                    >
                                                        {option.label}
                                                        {option.role
                                                            ? ` (${option.role})`
                                                            : ""}
                                                    </option>
                                                ))}
                                            </NativeSelect>
                                        </FormField>

                                        <FormField
                                            label="Lead source"
                                            htmlFor="lead_source"
                                            error={errors.lead_source}
                                        >
                                            <NativeSelect
                                                id="lead_source"
                                                name="lead_source"
                                                defaultValue={
                                                    customer.lead_source
                                                        ?.value ?? ""
                                                }
                                            >
                                                <option value="">
                                                    Not recorded
                                                </option>
                                                {options.leadSources.map(
                                                    (option) => (
                                                        <option
                                                            key={option.value}
                                                            value={option.value}
                                                        >
                                                            {option.label}
                                                        </option>
                                                    ),
                                                )}
                                            </NativeSelect>
                                        </FormField>

                                        <FormField
                                            label="Lead source detail"
                                            htmlFor="lead_source_detail"
                                            error={errors.lead_source_detail}
                                            hint="A referrer's name, a campaign, a street"
                                            className="sm:col-span-2"
                                        >
                                            <Input
                                                id="lead_source_detail"
                                                name="lead_source_detail"
                                                defaultValue={
                                                    customer.lead_source_detail ??
                                                    ""
                                                }
                                            />
                                        </FormField>
                                    </div>
                                </SectionCard>

                                <SectionCard
                                    title="Notes"
                                    description="Anything the next person needs to know before they ring or arrive."
                                    icon={FileText}
                                    tone="slate"
                                >
                                    <FormField
                                        label="Internal notes"
                                        htmlFor="notes"
                                        error={errors.notes}
                                        hint="Only staff can see this"
                                    >
                                        <textarea
                                            id="notes"
                                            name="notes"
                                            rows={4}
                                            defaultValue={customer.notes ?? ""}
                                            className="border-input dark:bg-input/30 focus-visible:border-ring focus-visible:ring-ring/50 w-full rounded-md border bg-transparent px-3 py-2 text-sm shadow-xs outline-none focus-visible:ring-[3px]"
                                        />
                                    </FormField>
                                </SectionCard>

                                <div className="bg-card/85 shadow-raised ring-hairline sticky bottom-4 z-10 flex flex-wrap items-center justify-between gap-3 rounded-xl px-4 py-3 ring-1 backdrop-blur">
                                    <p className="text-muted-foreground hidden text-xs sm:block">
                                        Saving keeps you on the profile.
                                    </p>
                                    <div className="flex shrink-0 gap-2">
                                        <Button variant="outline" asChild>
                                            <Link href={customersIndex()}>
                                                Back to customers
                                            </Link>
                                        </Button>
                                        {can.update ? (
                                            <Button
                                                type="submit"
                                                disabled={processing}
                                                data-test="save-customer-profile"
                                            >
                                                {processing
                                                    ? "Saving…"
                                                    : "Save changes"}
                                            </Button>
                                        ) : null}
                                    </div>
                                </div>
                            </div>

                            <aside className="flex flex-col gap-4">
                                <SectionCard
                                    title="Portal sign-in"
                                    description="The customer's own way into the ticket portal."
                                    icon={KeyRound}
                                    tone={
                                        account?.is_locked
                                            ? "warning"
                                            : "success"
                                    }
                                    actions={
                                        account && can.manageAccounts ? (
                                            <Button
                                                variant="ghost"
                                                size="sm"
                                                asChild
                                            >
                                                <Link
                                                    href={accountsIndex({
                                                        query: {
                                                            search: account.email,
                                                        },
                                                    })}
                                                >
                                                    Manage
                                                    <ArrowUpRight />
                                                </Link>
                                            </Button>
                                        ) : null
                                    }
                                >
                                    {account ? (
                                        <div className="flex flex-col gap-3">
                                            <div className="flex flex-wrap items-center gap-1.5">
                                                <StatusPill
                                                    tone={
                                                        account.verified
                                                            ? "success"
                                                            : "warning"
                                                    }
                                                >
                                                    {account.verified
                                                        ? "Email confirmed"
                                                        : "Not confirmed"}
                                                </StatusPill>
                                                <StatusPill
                                                    tone={
                                                        account.is_locked
                                                            ? "danger"
                                                            : "slate"
                                                    }
                                                >
                                                    {account.is_locked
                                                        ? "Paused"
                                                        : "Can sign in"}
                                                </StatusPill>
                                            </div>

                                            <dl className="grid gap-2.5">
                                                <DetailRow
                                                    label="Signs in as"
                                                    value={account.email}
                                                />
                                                <DetailRow
                                                    label="Last sign in"
                                                    value={
                                                        account.last_login_at
                                                            ? formatDateTime(
                                                                  account.last_login_at,
                                                              )
                                                            : "Never"
                                                    }
                                                />
                                                <DetailRow
                                                    label="Account opened"
                                                    value={formatDate(
                                                        account.created_at,
                                                    )}
                                                />
                                            </dl>

                                            {account.is_locked &&
                                            account.locked_at ? (
                                                <p className="flex items-start gap-2 rounded-lg bg-muted/60 px-3 py-2 text-xs text-muted-foreground">
                                                    <CircleAlert className="mt-0.5 size-3.5 shrink-0" />
                                                    Paused{" "}
                                                    {formatDate(
                                                        account.locked_at,
                                                    )}
                                                    . The customer record is
                                                    untouched.
                                                </p>
                                            ) : null}
                                        </div>
                                    ) : (
                                        <EmptyState
                                            icon={KeyRound}
                                            title="No portal account"
                                            description="The customer can create one from the portal's sign-up page using their email address."
                                            action={
                                                <Button
                                                    variant="outline"
                                                    size="sm"
                                                    asChild
                                                >
                                                    <a
                                                        href="/ticket/register"
                                                        target="_blank"
                                                        rel="noreferrer"
                                                    >
                                                        Open portal sign-up
                                                        <ArrowUpRight />
                                                    </a>
                                                </Button>
                                            }
                                        />
                                    )}
                                </SectionCard>

                                <SectionCard
                                    title="Installation sites"
                                    description="Where the work is, and the grid connection behind it."
                                    icon={MapPin}
                                    tone="info"
                                    actions={
                                        <Button
                                            variant="ghost"
                                            size="sm"
                                            asChild
                                        >
                                            <Link
                                                href={customerShow(customer.id)}
                                            >
                                                All sites
                                                <ArrowUpRight />
                                            </Link>
                                        </Button>
                                    }
                                >
                                    {customer.sites.length === 0 ? (
                                        <EmptyState
                                            icon={MapPin}
                                            title="No site recorded"
                                            description="Add the installation address from the customer page so jobs, inspections and grid applications have somewhere to point."
                                            action={
                                                <Button
                                                    variant="outline"
                                                    size="sm"
                                                    asChild
                                                >
                                                    <Link
                                                        href={customerShow(
                                                            customer.id,
                                                        )}
                                                    >
                                                        Add a site
                                                    </Link>
                                                </Button>
                                            }
                                        />
                                    ) : (
                                        <ul className="flex flex-col gap-2">
                                            {customer.sites.map((site) => (
                                                <li
                                                    key={site.id}
                                                    className="ring-hairline rounded-lg px-3 py-2.5 ring-1 ring-inset"
                                                >
                                                    <div className="flex items-start justify-between gap-2">
                                                        <p className="text-sm font-medium">
                                                            {site.address_line1}
                                                        </p>
                                                        {site.is_primary ? (
                                                            <StatusPill tone="solar">
                                                                Primary
                                                            </StatusPill>
                                                        ) : null}
                                                    </div>
                                                    <p className="text-muted-foreground mt-0.5 text-xs">
                                                        {[
                                                            site.suburb,
                                                            site.state_label,
                                                            site.postcode,
                                                        ]
                                                            .filter(Boolean)
                                                            .join(" ")}
                                                    </p>
                                                    <p className="text-muted-foreground mt-1 text-xs">
                                                        {site
                                                            .distribution_network
                                                            ?.name ??
                                                            "No network recorded"}
                                                        {site.nmi
                                                            ? ` · NMI ${site.nmi}`
                                                            : ""}
                                                    </p>
                                                </li>
                                            ))}
                                        </ul>
                                    )}
                                </SectionCard>

                                {pendingChange ? (
                                    <SectionCard
                                        title="Change waiting for review"
                                        description="The customer asked for these details from the portal. Nothing changes until somebody here approves it."
                                        icon={Clock}
                                        tone="warning"
                                    >
                                        <p className="text-muted-foreground text-xs">
                                            {pendingChange.submitted_by ??
                                                "The customer"}{" "}
                                            ·{" "}
                                            {formatRelative(
                                                pendingChange.submitted_at,
                                            )}
                                        </p>

                                        <dl className="mt-3 divide-y divide-hairline/70 overflow-hidden rounded-lg bg-muted/40">
                                            {pendingChange.changes.map(
                                                (change) => (
                                                    <div
                                                        key={change.field}
                                                        className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1 px-3 py-2 text-xs"
                                                    >
                                                        <dt className="text-muted-foreground font-medium">
                                                            {change.label}
                                                        </dt>
                                                        <dd className="flex flex-wrap items-baseline gap-1.5">
                                                            <span className="text-muted-foreground line-through">
                                                                {change.from ??
                                                                    "—"}
                                                            </span>
                                                            <span className="text-muted-foreground">
                                                                →
                                                            </span>
                                                            <span className="font-medium">
                                                                {change.to ??
                                                                    "—"}
                                                            </span>
                                                        </dd>
                                                    </div>
                                                ),
                                            )}
                                        </dl>

                                        {pendingChange.customer_note ? (
                                            <p className="mt-3 rounded-lg bg-background/60 px-3 py-2 text-xs leading-relaxed">
                                                <span className="font-medium">
                                                    Their note:{" "}
                                                </span>
                                                {pendingChange.customer_note}
                                            </p>
                                        ) : null}

                                        {can.reviewChanges ? (
                                            <Button
                                                className="mt-3"
                                                size="sm"
                                                asChild
                                            >
                                                <Link href="/customers/profile-changes">
                                                    Review the request
                                                </Link>
                                            </Button>
                                        ) : null}
                                    </SectionCard>
                                ) : null}

                                <SectionCard
                                    title="At a glance"
                                    description="The relationship in numbers."
                                    icon={BriefcaseBusiness}
                                    tone="slate"
                                >
                                    <dl className="grid grid-cols-2 gap-x-4 gap-y-4">
                                        <DetailRow
                                            label="Jobs"
                                            value={customer.jobs_count ?? 0}
                                        />
                                        <DetailRow
                                            label="Active jobs"
                                            value={
                                                customer.active_jobs_count ?? 0
                                            }
                                        />
                                        <DetailRow
                                            label="Sites"
                                            value={customer.sites.length}
                                        />
                                        <DetailRow
                                            label="Open tickets"
                                            value={ticketCounts.open}
                                        />
                                        <DetailRow
                                            label="Customer since"
                                            value={formatDate(
                                                customer.created_at,
                                            )}
                                        />
                                        <DetailRow
                                            label="Last contacted"
                                            value={formatRelative(
                                                customer.last_contacted_at,
                                            )}
                                        />
                                    </dl>

                                    {can.createTicket ? (
                                        <Button
                                            className="mt-4 w-full"
                                            variant="outline"
                                            size="sm"
                                            asChild
                                        >
                                            <Link
                                                href={ticketCreate({
                                                    query: {
                                                        customer: customer.id,
                                                    },
                                                })}
                                            >
                                                <Sparkles />
                                                Log a ticket for them
                                            </Link>
                                        </Button>
                                    ) : null}
                                </SectionCard>

                                <div className="ring-hairline flex items-start gap-2 rounded-xl bg-muted/40 px-3 py-2.5 text-xs leading-relaxed text-muted-foreground ring-1">
                                    <ShieldCheck className="mt-0.5 size-3.5 shrink-0 text-success" />
                                    <p>
                                        Corrections the customer submits from
                                        the portal wait for approval and appear
                                        here. The record above always shows what
                                        is in force.
                                    </p>
                                </div>
                            </aside>
                        </div>
                    </>
                )}
            </Form>
        </>
    );
}

/**
 * A record health ring. The percentage is the headline; the missing pieces are
 * what someone can actually act on, so they sit right underneath.
 */
function CompletenessRing({ health }: { health: ProfileHealth }) {
    const radius = 30;
    const circumference = 2 * Math.PI * radius;
    const offset = circumference * (1 - health.percent / 100);

    return (
        <div className="flex items-center gap-4 lg:shrink-0">
            <div className="relative flex size-20 shrink-0 items-center justify-center">
                <svg
                    viewBox="0 0 72 72"
                    className="absolute inset-0 size-20 -rotate-90"
                    aria-hidden
                >
                    <circle
                        cx="36"
                        cy="36"
                        r={radius}
                        className="fill-none stroke-muted"
                        strokeWidth="7"
                    />
                    <circle
                        cx="36"
                        cy="36"
                        r={radius}
                        className="fill-none stroke-solar transition-[stroke-dashoffset] duration-500"
                        strokeWidth="7"
                        strokeLinecap="round"
                        strokeDasharray={circumference}
                        strokeDashoffset={offset}
                    />
                </svg>
                <span className="crm-num text-base font-semibold">
                    {health.percent}%
                </span>
            </div>

            <div className="min-w-0">
                <p className="text-sm font-medium">Profile complete</p>
                <p className="text-muted-foreground text-xs">
                    {health.done} of {health.total} details recorded
                </p>

                {health.missing.length > 0 ? (
                    <ul className="mt-2 flex flex-wrap gap-1">
                        {health.missing.slice(0, 4).map((item) => (
                            <li
                                key={item}
                                className="inline-flex items-center gap-1 rounded-full bg-warning/10 px-2 py-0.5 text-[11px] font-medium text-warning"
                            >
                                <CalendarDays className="size-3" />
                                {item}
                            </li>
                        ))}
                        {health.missing.length > 4 ? (
                            <li className="text-muted-foreground px-1 text-[11px]">
                                +{health.missing.length - 4} more
                            </li>
                        ) : null}
                    </ul>
                ) : (
                    <p className="mt-2 inline-flex items-center gap-1 text-[11px] font-medium text-success">
                        <ShieldCheck className="size-3" />
                        Everything we need is on file
                    </p>
                )}
            </div>
        </div>
    );
}

CustomerProfile.layout = {
    breadcrumbs: [
        {
            title: "Customers",
            href: customersIndex(),
        },
        {
            title: "Client profile",
            href: "",
        },
    ],
};
