import { Head, Link, useForm } from "@inertiajs/react";
import {
    AlertTriangle,
    ArrowRight,
    CheckCircle2,
    FileSpreadsheet,
    Lock,
    Unlock,
} from "lucide-react";
import { Callout, SectionCard } from "@/components/crm/page-header";
import { Button } from "@/components/ui/button";
import { formatCurrency, formatDateTime, formatNumber } from "@/lib/format";

type ImportRun = {
    at: string;
    by: string | null;
    source: string;
    report: string;
    stats: {
        rows: number;
        ready: number;
        unmatched: number;
        duplicate: number;
        no_amount: number;
    };
    totals: {
        sale_price: number;
        deposit: number;
        balance: number;
    };
    written_totals?: {
        sale_price: number;
        deposit: number;
        balance: number;
    };
    result: {
        jobs_updated: number;
        invoices_created: number;
        invoices_updated: number;
        invoices_skipped: number;
    };
    before: { jobs: number; invoices: number };
    after: { jobs: number; invoices: number };
};

type PageProps = {
    state: {
        enabled: boolean;
        opened_at: string | null;
        opened_by: string | null;
        closed_at: string | null;
        closed_by: string | null;
        last_run: ImportRun | null;
    };
    canImport: boolean;
};

/**
 * Settings -> Client information import.
 *
 * A temporary door, not a permanent import. The owner opens it for the weeks
 * the old sales workbook is being brought across and closes it when the work is
 * done; closing leaves every imported job and invoice where it is.
 */
export default function ClientInformationImportSettings({
    state,
    canImport,
}: PageProps) {
    const form = useForm({ enabled: state.enabled });
    const last = state.last_run;

    const setOpen = (enabled: boolean) => {
        form.setData("enabled", enabled);
        form.put("/settings/client-information-import", {
            preserveScroll: true,
        });
    };

    const close = () => {
        if (
            window.confirm(
                "Close the client information import? The address will answer 404 and the button will disappear from Customers. Every imported job and invoice stays in place, and you can open it again from this screen.",
            )
        ) {
            setOpen(false);
        }
    };

    return (
        <>
            <Head title="Client information import" />

            <div className="flex flex-col gap-5">
                <div>
                    <h2 className="text-lg font-semibold tracking-tight">
                        Client information import
                    </h2>
                    <p className="mt-1 max-w-2xl text-sm text-muted-foreground">
                        A one-off door for the old{" "}
                        <span className="font-medium">Client Information</span>{" "}
                        sales workbook. It updates the sale price and deposit on
                        existing jobs and records each balance as a customer
                        invoice. It does not create customers.
                    </p>
                </div>

                <SectionCard
                    title="The door"
                    description="Opened by hand, closed by hand. Nothing here expires on its own."
                    icon={state.enabled ? Unlock : Lock}
                    tone={state.enabled ? "warning" : "slate"}
                >
                    <div className="flex flex-col gap-4">
                        <div className="flex flex-wrap items-center justify-between gap-3">
                            <div className="flex items-start gap-3">
                                <span
                                    className={
                                        state.enabled
                                            ? "mt-0.5 rounded-full bg-amber-500/15 p-2 text-amber-700 dark:text-amber-300"
                                            : "mt-0.5 rounded-full bg-slate-500/10 p-2 text-slate-600 dark:text-slate-300"
                                    }
                                >
                                    {state.enabled ? (
                                        <Unlock className="size-4" />
                                    ) : (
                                        <Lock className="size-4" />
                                    )}
                                </span>
                                <div>
                                    <p className="text-sm font-medium">
                                        {state.enabled
                                            ? "Open — the import can be used"
                                            : "Closed — the import is not reachable"}
                                    </p>
                                    <p className="mt-0.5 text-xs leading-relaxed text-muted-foreground">
                                        {state.enabled ? (
                                            <>
                                                Opened{" "}
                                                {formatDateTime(
                                                    state.opened_at,
                                                )}
                                                {state.opened_by
                                                    ? ` by ${state.opened_by}`
                                                    : ""}
                                                . The screen is at{" "}
                                                <span className="font-medium">
                                                    Customers → Client
                                                    information import
                                                </span>
                                                .
                                            </>
                                        ) : (
                                            <>
                                                {state.closed_at ? (
                                                    <>
                                                        Closed{" "}
                                                        {formatDateTime(
                                                            state.closed_at,
                                                        )}
                                                        {state.closed_by
                                                            ? ` by ${state.closed_by}`
                                                            : ""}
                                                        .
                                                    </>
                                                ) : (
                                                    "This installation has not opened it yet."
                                                )}{" "}
                                                Imported jobs and invoices are
                                                untouched.
                                            </>
                                        )}
                                    </p>
                                </div>
                            </div>

                            <div className="flex flex-wrap gap-2">
                                {state.enabled && canImport ? (
                                    <Button size="sm" variant="outline" asChild>
                                        <Link href="/customers/information-import">
                                            <FileSpreadsheet />
                                            Open the import
                                            <ArrowRight />
                                        </Link>
                                    </Button>
                                ) : null}

                                {state.enabled ? (
                                    <Button
                                        size="sm"
                                        variant="destructive"
                                        onClick={close}
                                        disabled={form.processing}
                                    >
                                        <Lock />
                                        Close the import
                                    </Button>
                                ) : (
                                    <Button
                                        size="sm"
                                        onClick={() => setOpen(true)}
                                        disabled={form.processing}
                                    >
                                        <Unlock />
                                        Open the import
                                    </Button>
                                )}
                            </div>
                        </div>

                        {!canImport && state.enabled ? (
                            <Callout
                                tone="warning"
                                icon={AlertTriangle}
                                title="The door is open, but this account cannot use it"
                            >
                                Using the import needs the customer update,
                                customer financials and invoice management
                                permissions. An administrator can grant them, or
                                close the door until they have been arranged.
                            </Callout>
                        ) : null}

                        {form.errors.enabled ? (
                            <p className="text-xs font-medium text-destructive">
                                {form.errors.enabled}
                            </p>
                        ) : null}
                    </div>
                </SectionCard>

                <Callout
                    tone="warning"
                    icon={AlertTriangle}
                    title="Close it when the migration is finished"
                >
                    <p>
                        This is not a permanent import. While it is open,
                        somebody with the right permissions can upload a
                        workbook and change customer financials. When the old
                        sheet has been read, press{" "}
                        <span className="font-medium">Close the import</span>.
                        Closing does not delete anything; it only removes the
                        door.
                    </p>
                    <p className="mt-2">
                        A run always takes a verified database backup before it
                        writes. Re-running the same workbook updates the jobs and
                        invoices it already created instead of making a second
                        set.
                    </p>
                </Callout>

                {last ? (
                    <SectionCard
                        title="Last run"
                        description={`${last.source} · ${formatDateTime(last.at)}${last.by ? ` by ${last.by}` : ""}`}
                        icon={CheckCircle2}
                        tone="success"
                    >
                        <dl className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
                            <div>
                                <dt className="text-xs text-muted-foreground">
                                    Rows read
                                </dt>
                                <dd className="text-sm font-semibold">
                                    {formatNumber(last.stats.rows)}
                                </dd>
                            </div>
                            <div>
                                <dt className="text-xs text-muted-foreground">
                                    Jobs updated
                                </dt>
                                <dd className="text-sm font-semibold">
                                    {formatNumber(last.result.jobs_updated)}
                                </dd>
                            </div>
                            <div>
                                <dt className="text-xs text-muted-foreground">
                                    Invoices created
                                </dt>
                                <dd className="text-sm font-semibold">
                                    {formatNumber(last.result.invoices_created)}
                                </dd>
                            </div>
                            <div>
                                <dt className="text-xs text-muted-foreground">
                                    Needs a person
                                </dt>
                                <dd className="text-sm font-semibold">
                                    {formatNumber(
                                        last.stats.unmatched +
                                            last.stats.duplicate,
                                    )}
                                </dd>
                            </div>
                            <div>
                                <dt className="text-xs text-muted-foreground">
                                    Sale price on the sheet
                                </dt>
                                <dd className="text-sm font-semibold">
                                    {formatCurrency(last.totals.sale_price)}
                                </dd>
                            </div>
                            <div>
                                <dt className="text-xs text-muted-foreground">
                                    Deposits on the sheet
                                </dt>
                                <dd className="text-sm font-semibold">
                                    {formatCurrency(last.totals.deposit)}
                                </dd>
                            </div>
                            <div>
                                <dt className="text-xs text-muted-foreground">
                                    Balance on the sheet
                                </dt>
                                <dd className="text-sm font-semibold">
                                    {formatCurrency(last.totals.balance)}
                                </dd>
                            </div>
                            <div>
                                <dt className="text-xs text-muted-foreground">
                                    Invoices
                                </dt>
                                <dd className="text-sm font-semibold">
                                    {formatNumber(last.before.invoices)} →{" "}
                                    {formatNumber(last.after.invoices)}
                                </dd>
                            </div>
                        </dl>
                        <p className="mt-4 text-xs break-all text-muted-foreground">
                            Report: {last.report}
                        </p>
                    </SectionCard>
                ) : null}
            </div>
        </>
    );
}
