import { Head, Link, router } from '@inertiajs/react';
import {
    BadgeCheck,
    ClipboardCheck,
    IdCard,
    MapPin,
    Pencil,
    ShieldCheck,
    Trash2,
    TriangleAlert,
    UserRound,
} from 'lucide-react';
import {
    Callout,
    KeyValueGrid,
    PageHeader,
    SectionCard,
} from '@/components/crm/page-header';
import { StatusPill } from '@/components/crm/status-badge';
import { Button } from '@/components/ui/button';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { formatCurrency, formatDate } from '@/lib/format';
import {
    destroy as installersDestroy,
    edit as installersEdit,
    index as installersIndex,
} from '@/routes/installers';
import type { CredentialStatus, InstallerDetail } from '@/types';

const statusTone: Record<string, string> = {
    current: 'emerald',
    expiring: 'amber',
    expired: 'red',
    missing: 'slate',
    none: 'slate',
};

const statusLabel: Record<string, string> = {
    current: 'Current',
    expiring: 'Expiring soon',
    expired: 'Expired',
    missing: 'Not recorded',
    none: 'No expiry on file',
};

export default function InstallersShow({
    installer,
    can,
}: {
    installer: InstallerDetail;
    can: { update: boolean; delete: boolean };
}) {
    const remove = () => {
        if (
            !window.confirm(
                `Remove ${installer.display_name} from the register? The record is kept, so old jobs can still name them.`,
            )
        ) {
            return;
        }

        router.delete(installersDestroy(installer.id).url);
    };

    const issues = installer.compliance.issues;

    return (
        <>
            <Head title={installer.display_name} />

            <PageHeader
                eyebrow={
                    <>
                        <UserRound className="size-3.5 text-solar" />
                        <span className="font-mono">
                            {installer.installer_number}
                        </span>
                        {installer.state ? (
                            <span>
                                {installer.state.value}
                                {installer.service_area
                                    ? ` · ${installer.service_area}`
                                    : ''}
                            </span>
                        ) : null}
                        <StatusPill
                            tone={statusTone[installer.compliance.status]}
                        >
                            {installer.compliance.label}
                        </StatusPill>
                        {!installer.is_active ? (
                            <StatusPill tone="slate">Not used</StatusPill>
                        ) : null}
                    </>
                }
                title={installer.display_name}
                description={installer.address.one_line || null}
                actions={
                    <>
                        {can.update ? (
                            <Button size="sm" asChild>
                                <Link href={installersEdit(installer.id)}>
                                    <Pencil />
                                    Edit
                                </Link>
                            </Button>
                        ) : null}
                        {can.delete ? (
                            <Button
                                size="sm"
                                variant="ghost"
                                onClick={remove}
                            >
                                <Trash2 />
                                Remove
                            </Button>
                        ) : null}
                    </>
                }
            />

            {issues.length > 0 ? (
                <Callout
                    tone={installer.compliance.status === 'expired' ? 'danger' : 'warning'}
                    icon={TriangleAlert}
                    title={
                        installer.compliance.status === 'expired'
                            ? 'A credential has expired'
                            : 'A credential is about to expire'
                    }
                >
                    <ul className="space-y-1">
                        {issues.map((issue) => (
                            <li key={issue.key}>
                                <span className="font-medium">
                                    {issue.label}
                                </span>{' '}
                                —{' '}
                                {issue.expired
                                    ? `expired ${formatDate(issue.date)}`
                                    : `expires ${formatDate(issue.date)}`}{' '}
                                ({Math.abs(issue.days)} day
                                {Math.abs(issue.days) === 1 ? '' : 's'}{' '}
                                {issue.expired ? 'ago' : 'left'})
                            </li>
                        ))}
                    </ul>
                </Callout>
            ) : (
                <Callout tone="success" icon={BadgeCheck}>
                    Nothing on file is expired or expiring in the next 30 days.
                </Callout>
            )}

            <div className="grid gap-5 lg:grid-cols-2">
                <SectionCard
                    title="Who they are"
                    icon={UserRound}
                    tone="solar"
                >
                    <KeyValueGrid
                        columns={2}
                        items={[
                            { label: 'Name', value: installer.name },
                            {
                                label: 'Business',
                                value: installer.business_name,
                            },
                            { label: 'ABN', value: installer.abn },
                            { label: 'Phone', value: installer.phone },
                            { label: 'Email', value: installer.email },
                            {
                                label: 'Documents received',
                                value: installer.documents_received
                                    ? 'Yes'
                                    : 'No',
                            },
                        ]}
                    />
                </SectionCard>

                <SectionCard
                    title="Address"
                    icon={MapPin}
                    tone="info"
                >
                    <KeyValueGrid
                        columns={2}
                        items={[
                            { label: 'Street', value: installer.address.line1 },
                            {
                                label: 'Suburb',
                                value: installer.address.suburb,
                            },
                            {
                                label: 'State',
                                value: installer.address.state_label,
                            },
                            {
                                label: 'Postcode',
                                value: installer.address.postcode,
                            },
                            {
                                label: 'Service area',
                                value: installer.service_area,
                            },
                            {
                                label: 'Verified',
                                value: installer.verified_at
                                    ? formatDate(installer.verified_at)
                                    : 'Not checked yet',
                            },
                        ]}
                    />
                </SectionCard>
            </div>

            <SectionCard
                title="Credentials"
                description="What the state regulator, Solar Accreditation Australia and the insurer have issued, and when each one runs out."
                icon={IdCard}
                tone="info"
                flush
            >
                <div className="crm-scroll overflow-x-auto">
                    <Table>
                        <TableHeader>
                            <TableRow>
                                <TableHead className="pl-5">
                                    Credential
                                </TableHead>
                                <TableHead>Number</TableHead>
                                <TableHead>Expiry</TableHead>
                                <TableHead className="pr-5">Status</TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {installer.credentials.map((credential) => (
                                <TableRow key={credential.key}>
                                    <TableCell className="min-w-52 pl-5">
                                        <div className="text-sm font-medium">
                                            {credential.label}
                                        </div>
                                        <div className="mt-0.5 text-xs text-muted-foreground">
                                            {credential.source}
                                        </div>
                                    </TableCell>
                                    <TableCell className="font-mono text-xs">
                                        {credential.number ?? '—'}
                                    </TableCell>
                                    <TableCell className="text-sm">
                                        {credential.expiry
                                            ? formatDate(credential.expiry)
                                            : '—'}
                                    </TableCell>
                                    <TableCell className="pr-5">
                                        <StatusPill
                                            tone={
                                                statusTone[
                                                    credential.status as CredentialStatus
                                                ]
                                            }
                                        >
                                            {statusLabel[credential.status]}
                                        </StatusPill>
                                    </TableCell>
                                </TableRow>
                            ))}
                        </TableBody>
                    </Table>
                </div>
            </SectionCard>

            <div className="grid gap-5 lg:grid-cols-2">
                <SectionCard
                    title="Insurance cover"
                    icon={ShieldCheck}
                    tone="emerald"
                >
                    <KeyValueGrid
                        columns={2}
                        items={[
                            {
                                label: 'Public liability',
                                value: formatCurrency(
                                    installer.cover.public_liability,
                                ),
                            },
                            {
                                label: 'Professional indemnity',
                                value: formatCurrency(
                                    installer.cover.professional_indemnity,
                                ),
                            },
                            {
                                label: 'Accreditation classes',
                                value:
                                    installer.accreditation_classes.length > 0
                                        ? installer.accreditation_classes.join(
                                              ', ',
                                          )
                                        : null,
                            },
                        ]}
                    />
                </SectionCard>

                <SectionCard
                    title="Record"
                    icon={ClipboardCheck}
                    tone="slate"
                >
                    <KeyValueGrid
                        columns={2}
                        items={[
                            {
                                label: 'Source',
                                value: installer.source ?? 'Added in the CRM',
                            },
                            {
                                label: 'Last updated',
                                value: formatDate(installer.updated_at),
                            },
                            {
                                label: 'Added by',
                                value: installer.created_by?.name ?? null,
                            },
                            {
                                label: 'Updated by',
                                value: installer.updated_by?.name ?? null,
                            },
                        ]}
                    />
                </SectionCard>
            </div>

            {installer.notes ? (
                <SectionCard title="Notes" tone="slate">
                    <p className="text-sm whitespace-pre-line">
                        {installer.notes}
                    </p>
                </SectionCard>
            ) : null}
        </>
    );
}

InstallersShow.layout = {
    breadcrumbs: [{ title: 'Installers', href: installersIndex() }],
};
