import { Head, router, usePage } from '@inertiajs/react';
import {
    AlertTriangle,
    ArrowRight,
    Check,
    FileSpreadsheet,
    Save,
    Sparkles,
    Upload,
} from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import { PageHeader, SectionCard } from '@/components/crm/page-header';
import { NativeSelect, FormField } from '@/components/crm/native-select';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { cn } from '@/lib/utils';
import type { Option } from '@/types';

type Field = {
    key: string;
    label: string;
    required: boolean;
    help: string;
};

type Column = { index: number; label: string };

type Profile = {
    name: string;
    sheet: string | null;
    mapping: Record<string, number>;
    options: Record<string, string>;
};

type Upload = {
    token: string;
    name: string;
    sheets: string[];
    sheet: string;
    header_row: number;
    columns: Column[];
    mapping: Record<string, number>;
};

type SystemReading = {
    panel_count: number | null;
    panel_wattage: number | null;
    system_size_kw: number | null;
    panel_make: string | null;
    panel_model: string | null;
    inverter_make: string | null;
    inverter_model: string | null;
    inverter_capacity_kw: number | null;
    battery_make: string | null;
    battery_model: string | null;
    battery_capacity_kwh: number | null;
    installation_config: string;
    summary: string;
};

type PreviewRow = {
    row: number;
    name: string;
    phone: string | null;
    email: string | null;
    address: string;
    componentry: string | null;
    system: SystemReading | null;
    export_limit_kw: number | null;
    approved_export_limit_kw: number | null;
    outcome: string;
    reason: string | null;
    match: { job_number: string | null; similarity: number; source: string } | null;
    customer: { id: number | null; name: string | null; existing: boolean };
    site: { id: number | null; address: string; existing: boolean };
    extras: Record<string, string>;
};

type Preview = {
    stats: Record<string, number>;
    rows: PreviewRow[];
    mapping: Record<string, number>;
    settings: {
        status: string;
        type: string;
        default_state: string | null;
        marker: string;
    };
    carried_columns: Column[];
};

type Props = {
    profiles: Profile[];
    fields: Field[];
    options: {
        statuses: (Option & { group?: string })[];
        types: Option[];
        states: Option[];
    };
    upload: Upload | null;
    preview: Preview | null;
};

type Payload = Record<
    string,
    string | number | boolean | null | undefined | File | Record<string, number>
>;

const outcomeStyles: Record<string, string> = {
    create: 'bg-emerald-500/10 text-emerald-700 ring-emerald-500/20 dark:text-emerald-300',
    duplicate: 'bg-amber-500/10 text-amber-700 ring-amber-500/20 dark:text-amber-300',
    missing_contact: 'bg-slate-500/10 text-slate-600 ring-slate-500/20 dark:text-slate-300',
    missing_address: 'bg-slate-500/10 text-slate-600 ring-slate-500/20 dark:text-slate-300',
    missing_name: 'bg-slate-500/10 text-slate-600 ring-slate-500/20 dark:text-slate-300',
    invalid_address: 'bg-rose-500/10 text-rose-700 ring-rose-500/20 dark:text-rose-300',
};

const outcomeLabels: Record<string, string> = {
    create: 'Import',
    duplicate: 'Duplicate',
    missing_contact: 'No contact',
    missing_address: 'No address',
    missing_name: 'No name',
    invalid_address: 'Bad address',
};

function csrfToken(): string {
    const match = document.cookie.match(/(?:^|;\s*)XSRF-TOKEN=([^;]+)/);

    return match ? decodeURIComponent(match[1]) : '';
}

export default function JobsImport({
    profiles,
    fields,
    options,
    upload,
    preview,
}: Props) {
    const [file, setFile] = useState<File | null>(null);
    const [busy, setBusy] = useState(false);
    const [profile, setProfile] = useState('');
    const [mappings, setMappings] = useState<Record<string, string>>({});
    const [status, setStatus] = useState('install_scheduled');
    const [type, setType] = useState('residential_install');
    const [state, setState] = useState('');
    const [profileName, setProfileName] = useState('');
    const [savedName, setSavedName] = useState<string | null>(null);
    const [localProfiles, setLocalProfiles] = useState(profiles);
    const fileInput = useRef<HTMLInputElement>(null);
    const { errors } = usePage<{ errors: Record<string, string> }>().props;
    const error = errors.workbook ?? errors.mapping ?? errors.sheet ?? null;

    // The server's mapping is the truth after every preview: it may have
    // detected a column differently, or a saved profile may have been applied.
    useEffect(() => {
        if (preview === null) {
            return;
        }

        const next: Record<string, string> = {};

        fields.forEach((field) => {
            const index = preview.mapping[field.key];
            next[field.key] = index === undefined ? '' : String(index);
        });

        setMappings(next);
        setStatus(preview.settings.status);
        setType(preview.settings.type);
        setState(preview.settings.default_state ?? '');
    }, [preview, fields]);

    const postPreview = (data: Payload) => {
        router.post(
            '/jobs/import/preview',
            { token: upload?.token, sheet: upload?.sheet, ...data },
            {
                preserveScroll: true,
                preserveState: true,
                onStart: () => setBusy(true),
                onFinish: () => setBusy(false),
            },
        );
    };

    const uploadWorkbook = (event: React.FormEvent) => {
        event.preventDefault();

        if (file === null) {
            return;
        }

        const data: Payload = { workbook: file };

        if (profile !== '') {
            data.profile = profile;
        }

        router.post('/jobs/import/preview', data, {
            forceFormData: true,
            preserveScroll: true,
            onStart: () => setBusy(true),
            onFinish: () => setBusy(false),
        });
    };

    const chooseSheet = (sheet: string) => {
        router.post(
            '/jobs/import/preview',
            { token: upload?.token, sheet },
            {
                preserveScroll: true,
                preserveState: true,
                onStart: () => setBusy(true),
                onFinish: () => setBusy(false),
            },
        );
    };

    const changeMapping = (field: string, value: string) => {
        const next = { ...mappings, [field]: value };
        setMappings(next);
        submitMapping(next);
    };

    const submitMapping = (next: Record<string, string>) => {
        const mapping: Record<string, number> = {};

        Object.entries(next).forEach(([field, value]) => {
            if (value !== '') {
                mapping[field] = Number(value);
            }
        });

        postPreview({ mapping, status, type, default_state: state });
    };

    const commit = () => {
        if (upload === null || preview === null) {
            return;
        }

        const mapping: Record<string, number> = {};

        Object.entries(mappings).forEach(([field, value]) => {
            if (value !== '') {
                mapping[field] = Number(value);
            }
        });

        const ready = preview.stats.ready ?? 0;

        if (
            !window.confirm(
                `Import ${ready} ${ready === 1 ? 'job' : 'jobs'}? ` +
                    `${preview.stats.duplicates ?? 0} duplicate rows will be skipped.`,
            )
        ) {
            return;
        }

        router.post(
            '/jobs/import/commit',
            {
                token: upload.token,
                sheet: upload.sheet,
                mapping,
                status,
                type,
                default_state: state,
            },
            {
                onStart: () => setBusy(true),
                onFinish: () => setBusy(false),
            },
        );
    };

    const saveProfile = async () => {
        if (profileName.trim() === '' || upload === null) {
            return;
        }

        const mapping: Record<string, number> = {};

        Object.entries(mappings).forEach(([field, value]) => {
            if (value !== '') {
                mapping[field] = Number(value);
            }
        });

        const response = await fetch('/jobs/import/profiles', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                Accept: 'application/json',
                'X-XSRF-TOKEN': csrfToken(),
            },
            body: JSON.stringify({
                name: profileName,
                sheet: upload.sheet,
                mapping,
                options: { status, type, default_state: state },
            }),
        });

        if (!response.ok) {
            setSavedName('That mapping could not be saved.');

            return;
        }

        const result = (await response.json()) as { profiles: Profile[] };
        setLocalProfiles(result.profiles);
        setSavedName(`Saved "${profileName}".`);
        setProfileName('');
    };

    const stats = preview?.stats;

    return (
        <>
            <Head title="Import jobs" />

            <div className="flex flex-col gap-5">
                <PageHeader
                    eyebrow={
                        <>
                            <FileSpreadsheet className="text-solar size-3.5" />
                            <span>Spreadsheet import</span>
                        </>
                    }
                    title="Import jobs"
                    description="Bring a sheet of jobs across without retyping it. The importer reads the headers, keeps only rows with a name, a contact and an address, and skips the same system at the same address twice."
                />

                {error ? (
                    <div className="rounded-lg bg-destructive/10 px-3 py-2 text-sm text-destructive ring-1 ring-destructive/20 ring-inset">
                        {error}
                    </div>
                ) : null}

                <div className="grid gap-5 lg:grid-cols-[minmax(0,1fr)_320px]">
                    <div className="flex flex-col gap-5">
                        <SectionCard
                            title="1. Choose a workbook"
                            description="An .xlsx file. Nothing is written until the last step."
                            icon={Upload}
                        >
                            <form onSubmit={uploadWorkbook} className="grid gap-4">
                                <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
                                    <input
                                        ref={fileInput}
                                        type="file"
                                        accept=".xlsx"
                                        onChange={(event) =>
                                            setFile(
                                                event.target.files?.[0] ?? null,
                                            )
                                        }
                                        className="file:border-input file:bg-muted file:text-foreground hover:file:bg-accent block w-full cursor-pointer rounded-md border border-dashed border-hairline px-3 py-2 text-sm file:mr-3 file:rounded-md file:border file:px-3 file:py-1.5 file:text-xs file:font-medium"
                                    />
                                    <Button
                                        type="submit"
                                        size="sm"
                                        disabled={file === null || busy}
                                    >
                                        Read workbook
                                        <ArrowRight className="size-4" />
                                    </Button>
                                </div>

                                {upload !== null ? (
                                    <div className="grid gap-4 sm:grid-cols-2">
                                        <FormField
                                            label="Sheet"
                                            htmlFor="sheet"
                                            hint={`${upload.header_row === 0 ? 'Header row 1' : `Header row ${upload.header_row}`} · ${upload.name}`}
                                        >
                                            <NativeSelect
                                                id="sheet"
                                                value={upload.sheet}
                                                onChange={(event) =>
                                                    chooseSheet(
                                                        event.target.value,
                                                    )
                                                }
                                            >
                                                {upload.sheets.map((sheet) => (
                                                    <option
                                                        key={sheet}
                                                        value={sheet}
                                                    >
                                                        {sheet}
                                                    </option>
                                                ))}
                                            </NativeSelect>
                                        </FormField>

                                        <FormField
                                            label="Saved mapping"
                                            htmlFor="profile"
                                            hint="Apply a mapping saved from an earlier import."
                                        >
                                            <NativeSelect
                                                id="profile"
                                                value={profile}
                                                onChange={(event) => {
                                                    const name =
                                                        event.target.value;
                                                    setProfile(name);

                                                    if (name !== '') {
                                                        postPreview({
                                                            profile: name,
                                                        });
                                                    }
                                                }}
                                            >
                                                <option value="">
                                                    Detect automatically
                                                </option>
                                                {localProfiles.map((item) => (
                                                    <option
                                                        key={item.name}
                                                        value={item.name}
                                                    >
                                                        {item.name}
                                                        {item.sheet
                                                            ? ` · ${item.sheet}`
                                                            : ''}
                                                    </option>
                                                ))}
                                            </NativeSelect>
                                        </FormField>
                                    </div>
                                ) : null}
                            </form>
                        </SectionCard>

                        {upload !== null && preview !== null ? (
                            <SectionCard
                                title="2. Match the columns"
                                description="The guess is based on the header names. Change anything that is wrong; the preview follows."
                                icon={Sparkles}
                                actions={
                                    busy ? (
                                        <span className="text-muted-foreground text-xs">
                                            Reading…
                                        </span>
                                    ) : null
                                }
                            >
                                <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
                                    {fields.map((field) => (
                                        <FormField
                                            key={field.key}
                                            label={field.label}
                                            htmlFor={`map-${field.key}`}
                                            required={field.required}
                                            hint={field.help}
                                        >
                                            <NativeSelect
                                                id={`map-${field.key}`}
                                                value={
                                                    mappings[field.key] ?? ''
                                                }
                                                onChange={(event) =>
                                                    changeMapping(
                                                        field.key,
                                                        event.target.value,
                                                    )
                                                }
                                            >
                                                <option value="">
                                                    Not mapped
                                                </option>
                                                {upload.columns.map((column) => (
                                                    <option
                                                        key={column.index}
                                                        value={String(
                                                            column.index,
                                                        )}
                                                    >
                                                        {column.label}
                                                    </option>
                                                ))}
                                            </NativeSelect>
                                        </FormField>
                                    ))}
                                </div>

                                <div className="mt-5 grid gap-4 sm:grid-cols-3">
                                    <FormField
                                        label="Job status"
                                        htmlFor="status"
                                        hint="What these jobs are in the pipeline."
                                    >
                                        <NativeSelect
                                            id="status"
                                            value={status}
                                            onChange={(event) => {
                                                setStatus(event.target.value);
                                                postPreview({
                                                    mapping: mappingsToInts(
                                                        mappings,
                                                    ),
                                                    status: event.target.value,
                                                    type,
                                                    default_state: state,
                                                });
                                            }}
                                        >
                                            {options.statuses.map((option) => (
                                                <option
                                                    key={option.value}
                                                    value={option.value}
                                                >
                                                    {option.label}
                                                </option>
                                            ))}
                                        </NativeSelect>
                                    </FormField>

                                    <FormField
                                        label="Job type"
                                        htmlFor="type"
                                        hint="Applied to every imported job."
                                    >
                                        <NativeSelect
                                            id="type"
                                            value={type}
                                            onChange={(event) => {
                                                setType(event.target.value);
                                                postPreview({
                                                    mapping: mappingsToInts(
                                                        mappings,
                                                    ),
                                                    status,
                                                    type: event.target.value,
                                                    default_state: state,
                                                });
                                            }}
                                        >
                                            {options.types.map((option) => (
                                                <option
                                                    key={option.value}
                                                    value={option.value}
                                                >
                                                    {option.label}
                                                </option>
                                            ))}
                                        </NativeSelect>
                                    </FormField>

                                    <FormField
                                        label="State if omitted"
                                        htmlFor="state"
                                        hint="Used when an address has no state in it."
                                    >
                                        <NativeSelect
                                            id="state"
                                            value={state}
                                            onChange={(event) => {
                                                setState(event.target.value);
                                                postPreview({
                                                    mapping: mappingsToInts(
                                                        mappings,
                                                    ),
                                                    status,
                                                    type,
                                                    default_state:
                                                        event.target.value,
                                                });
                                            }}
                                        >
                                            <option value="">
                                                Read it from the address
                                            </option>
                                            {options.states.map((option) => (
                                                <option
                                                    key={option.value}
                                                    value={option.value}
                                                >
                                                    {option.label}
                                                </option>
                                            ))}
                                        </NativeSelect>
                                    </FormField>
                                </div>

                                {preview.carried_columns.length > 0 ? (
                                    <p className="text-muted-foreground mt-4 text-xs leading-relaxed">
                                        {preview.carried_columns.length} column
                                        {preview.carried_columns.length === 1
                                            ? ''
                                            : 's'}{' '}
                                        not mapped to a field (
                                        {preview.carried_columns
                                            .slice(0, 6)
                                            .map((column) => column.label)
                                            .join(', ')}
                                        {preview.carried_columns.length > 6
                                            ? '…'
                                            : ''}
                                        ) will still be kept on each job's
                                        internal notes, so nothing from the
                                        sheet is lost.
                                    </p>
                                ) : null}
                            </SectionCard>
                        ) : null}

                        {upload !== null && preview !== null ? (
                            <SectionCard
                                title="3. Review the preview"
                                description={`${stats?.rows ?? 0} rows read. Showing the first ${preview.rows.length}, ready rows first. Only rows marked Import are written.`}
                                icon={Check}
                                flush
                            >
                                <div className="crm-scroll max-h-[520px] overflow-auto">
                                    <Table>
                                        <TableHeader className="bg-card sticky top-0 z-10">
                                            <TableRow>
                                                <TableHead className="w-14">
                                                    Row
                                                </TableHead>
                                                <TableHead>Customer</TableHead>
                                                <TableHead>Address</TableHead>
                                                <TableHead>
                                                    Componentry
                                                </TableHead>
                                                <TableHead className="w-28">
                                                    Outcome
                                                </TableHead>
                                            </TableRow>
                                        </TableHeader>
                                        <TableBody>
                                            {preview.rows.map((row) => (
                                                <TableRow key={row.row}>
                                                    <TableCell className="text-muted-foreground text-xs tabular-nums">
                                                        {row.row}
                                                    </TableCell>
                                                    <TableCell>
                                                        <div className="font-medium">
                                                            {row.name || '—'}
                                                        </div>
                                                        <div className="text-muted-foreground text-xs">
                                                            {row.phone ??
                                                                row.email ??
                                                                '—'}
                                                        </div>
                                                    </TableCell>
                                                    <TableCell className="max-w-[280px] text-sm">
                                                        {row.address || '—'}
                                                    </TableCell>
                                                    <TableCell className="max-w-[320px]">
                                                        <p className="line-clamp-2 text-xs leading-relaxed">
                                                            {row.componentry ??
                                                                '—'}
                                                        </p>
                                                        {row.system?.summary ? (
                                                            <p className="mt-1.5 flex items-start gap-1.5 text-[11px] leading-snug text-emerald-700 dark:text-emerald-300">
                                                                <Sparkles className="mt-0.5 size-3 shrink-0" />
                                                                <span className="line-clamp-2">
                                                                    {
                                                                        row
                                                                            .system
                                                                            .summary
                                                                    }
                                                                </span>
                                                            </p>
                                                        ) : null}
                                                        {row.export_limit_kw !== null ||
                                                        row.approved_export_limit_kw !==
                                                            null ? (
                                                            <p className="text-muted-foreground mt-1 text-[11px] leading-snug">
                                                                {row.export_limit_kw !==
                                                                null
                                                                    ? `Export limit ${row.export_limit_kw} kW`
                                                                    : null}
                                                                {row.export_limit_kw !==
                                                                    null &&
                                                                row.approved_export_limit_kw !==
                                                                    null
                                                                    ? ' · '
                                                                    : null}
                                                                {row.approved_export_limit_kw !==
                                                                null
                                                                    ? `Allowed export ${row.approved_export_limit_kw} kW`
                                                                    : null}
                                                            </p>
                                                        ) : null}
                                                        {row.reason ? (
                                                            <p className="text-muted-foreground mt-1 text-[11px] leading-snug">
                                                                {row.reason}
                                                            </p>
                                                        ) : null}
                                                    </TableCell>
                                                    <TableCell>
                                                        <span
                                                            className={cn(
                                                                'inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium ring-1 ring-inset',
                                                                outcomeStyles[
                                                                    row.outcome
                                                                ] ??
                                                                    outcomeStyles.missing_name,
                                                            )}
                                                        >
                                                            {outcomeLabels[
                                                                row.outcome
                                                            ] ?? row.outcome}
                                                        </span>
                                                    </TableCell>
                                                </TableRow>
                                            ))}
                                        </TableBody>
                                    </Table>
                                </div>
                            </SectionCard>
                        ) : null}
                    </div>

                    <aside className="flex flex-col gap-5">
                        <SectionCard
                            title="What will happen"
                            description="A dry read of the sheet. Nothing here has been written."
                            icon={Sparkles}
                        >
                            {stats === undefined ? (
                                <p className="text-muted-foreground text-sm leading-relaxed">
                                    Choose a workbook to see the rows, the
                                    duplicates and the ones that cannot be
                                    imported.
                                </p>
                            ) : (
                                <div className="grid gap-2.5">
                                    <Stat
                                        label="Jobs to create"
                                        value={stats.ready}
                                        tone="good"
                                    />
                                    <Stat
                                        label="Duplicates skipped"
                                        value={stats.duplicates}
                                    />
                                    <Stat
                                        label="Systems read"
                                        value={stats.systems_read ?? 0}
                                        tone={
                                            (stats.systems_read ?? 0) > 0
                                                ? 'good'
                                                : undefined
                                        }
                                    />
                                    <Stat
                                        label="Brands read"
                                        value={stats.brands_matched ?? 0}
                                    />
                                    <Stat
                                        label="Same address, new system"
                                        value={stats.same_site_new_componentry}
                                    />
                                    <Stat
                                        label="New customers"
                                        value={stats.new_customers}
                                    />
                                    <Stat
                                        label="Existing customers"
                                        value={stats.existing_customers}
                                    />
                                    <Stat
                                        label="Missing a contact"
                                        value={stats.missing_contact}
                                        tone={
                                            (stats.missing_contact ?? 0) > 0
                                                ? 'warn'
                                                : undefined
                                        }
                                    />
                                    <Stat
                                        label="Addresses not usable"
                                        value={stats.invalid_address}
                                        tone={
                                            (stats.invalid_address ?? 0) > 0
                                                ? 'warn'
                                                : undefined
                                        }
                                    />
                                </div>
                            )}
                        </SectionCard>

                        {upload !== null && preview !== null ? (
                            <SectionCard
                                title="Keep this mapping"
                                description="Save it against this sheet so next time is one click."
                                icon={Save}
                            >
                                <div className="grid gap-3">
                                    <Input
                                        value={profileName}
                                        onChange={(event) =>
                                            setProfileName(event.target.value)
                                        }
                                        placeholder="e.g. Outstanding jobs - Tas"
                                        aria-label="Profile name"
                                    />
                                    <Button
                                        type="button"
                                        variant="outline"
                                        size="sm"
                                        disabled={profileName.trim() === ''}
                                        onClick={saveProfile}
                                    >
                                        <Save className="size-4" />
                                        Save mapping
                                    </Button>
                                    {savedName ? (
                                        <p className="text-muted-foreground text-xs">
                                            {savedName}
                                        </p>
                                    ) : null}
                                    <Button
                                        type="button"
                                        onClick={commit}
                                        disabled={
                                            busy || (stats?.ready ?? 0) === 0
                                        }
                                    >
                                        <Check className="size-4" />
                                        Import {stats?.ready ?? 0}{' '}
                                        {(stats?.ready ?? 0) === 1
                                            ? 'job'
                                            : 'jobs'}
                                    </Button>
                                    <p className="text-muted-foreground text-[11px] leading-relaxed">
                                        A verified database backup is taken
                                        before anything is written.
                                    </p>
                                </div>
                            </SectionCard>
                        ) : (
                            <SectionCard
                                title="The rules"
                                description="What the importer will and will not do."
                                icon={AlertTriangle}
                            >
                                <ul className="text-muted-foreground grid gap-2.5 text-xs leading-relaxed">
                                    <li>
                                        A row needs a <strong>name</strong>, a{' '}
                                        <strong>phone or email</strong> and an{' '}
                                        <strong>address</strong>. Everything
                                        else is optional.
                                    </li>
                                    <li>
                                        If the address <em>and</em> componentry
                                        are already on the CRM, the row is
                                        skipped as a duplicate.
                                    </li>
                                    <li>
                                        If the address matches but the
                                        componentry does not, the job is added
                                        under the same customer as another job.
                                    </li>
                                    <li>
                                        The componentry is read for the panel
                                        wattage and count, the inverter and the
                                        battery, and each brand is matched to
                                        the warehouse catalogue where it is
                                        known.
                                    </li>
                                    <li>
                                        Columns that are not mapped are kept in
                                        the job's internal notes.
                                    </li>
                                </ul>
                            </SectionCard>
                        )}
                    </aside>
                </div>
            </div>
        </>
    );
}

function mappingsToInts(
    mappings: Record<string, string>,
): Record<string, number> {
    const mapping: Record<string, number> = {};

    Object.entries(mappings).forEach(([field, value]) => {
        if (value !== '') {
            mapping[field] = Number(value);
        }
    });

    return mapping;
}

function Stat({
    label,
    value,
    tone,
}: {
    label: string;
    value: number | undefined;
    tone?: 'good' | 'warn';
}) {
    return (
        <div className="flex items-center justify-between gap-3 rounded-lg bg-muted/40 px-3 py-2">
            <span className="text-muted-foreground text-xs">{label}</span>
            <span
                className={cn(
                    'text-sm font-semibold tabular-nums',
                    tone === 'good' && 'text-emerald-600 dark:text-emerald-400',
                    tone === 'warn' && 'text-amber-600 dark:text-amber-400',
                )}
            >
                {value ?? 0}
            </span>
        </div>
    );
}
