import { Head, useForm } from '@inertiajs/react';
import {
    AlertTriangle,
    BadgeCheck,
    Fingerprint,
    RotateCcw,
    ShieldCheck,
    Upload,
} from 'lucide-react';
import { FormEvent } from 'react';

type Certificate = {
    fingerprint: string;
    subject: string;
    issuer: string;
    valid_from: string | null;
    expires_at: string | null;
    self_signed: boolean;
    active: boolean;
    key_configured: boolean;
};

type PreviousCertificate = {
    id: number;
    fingerprint: string;
    subject: string;
    issuer: string;
    expires_at: string | null;
    self_signed: boolean;
    created_at: string | null;
};

function formatDate(value: string | null): string {
    return value ? new Date(value).toLocaleDateString() : 'Not available';
}

export default function TicketSigning({
    certificate,
    previous_certificates: previousCertificates,
}: {
    certificate: Certificate;
    previous_certificates: PreviousCertificate[];
}) {
    const rotateForm = useForm({});
    const uploadForm = useForm<{
        certificate_bundle: File | null;
        certificate_password: string;
    }>({ certificate_bundle: null, certificate_password: '' });

    function installCertificate(event: FormEvent<HTMLFormElement>) {
        event.preventDefault();
        uploadForm.post('/super-admin/ticket-signing/certificate', {
            forceFormData: true,
            preserveScroll: true,
            onSuccess: () => uploadForm.reset(),
        });
    }

    return (
        <>
            <Head title="Ticket signing" />
            <main className="min-h-full bg-slate-50 px-4 py-4 text-slate-900 sm:px-6 lg:px-7">
                <div className="mx-auto max-w-[1450px]">
                    <header className="flex flex-col justify-between gap-4 sm:flex-row sm:items-end">
                        <div>
                            <p className="text-xs font-semibold text-slate-500">
                                Racing.lk / Super Admin
                            </p>
                            <h1 className="mt-1 text-2xl font-bold tracking-tight">
                                Ticket signing
                            </h1>
                            <p className="mt-1 max-w-2xl text-sm leading-6 text-slate-600">
                                Manage the certificate used to sign ticket QR
                                codes and downloadable PDF passes.
                            </p>
                        </div>
                        <button
                            type="button"
                            disabled={rotateForm.processing}
                            onClick={() =>
                                rotateForm.post(
                                    '/super-admin/ticket-signing/self-signed',
                                    { preserveScroll: true },
                                )
                            }
                            className="inline-flex min-h-11 items-center justify-center gap-2 rounded-lg border border-slate-300 bg-white px-4 text-sm font-bold hover:border-red-400 hover:text-red-700 disabled:opacity-50"
                        >
                            <RotateCcw size={16} /> Generate new self-signed
                            certificate
                        </button>
                    </header>

                    <div className="mt-6 grid gap-5 xl:grid-cols-[1.1fr_.9fr]">
                        <section className="rounded-xl border border-slate-200 bg-white p-5 shadow-sm sm:p-6">
                            <div className="flex flex-wrap items-center justify-between gap-3">
                                <div className="flex items-center gap-3">
                                    <span className="grid size-11 place-items-center rounded-lg bg-emerald-50 text-emerald-700">
                                        <ShieldCheck size={22} />
                                    </span>
                                    <div>
                                        <h2 className="text-lg font-bold">
                                            Active signing certificate
                                        </h2>
                                        <p className="text-sm text-slate-500">
                                            {certificate.subject}
                                        </p>
                                    </div>
                                </div>
                                <span className="inline-flex items-center gap-1.5 rounded-full bg-emerald-50 px-3 py-1.5 text-xs font-bold text-emerald-800">
                                    <BadgeCheck size={14} /> Active
                                </span>
                            </div>

                            {certificate.self_signed && (
                                <div
                                    role="status"
                                    className="mt-5 flex gap-3 rounded-lg border border-amber-300 bg-amber-50 p-4 text-sm leading-6 text-amber-950"
                                >
                                    <AlertTriangle
                                        className="mt-0.5 shrink-0"
                                        size={18}
                                    />
                                    <p>
                                        This certificate signs tickets
                                        correctly, but PDF readers will show its
                                        signer as untrusted until you install a
                                        certificate issued by a trusted
                                        certificate authority.
                                    </p>
                                </div>
                            )}

                            <dl className="mt-5 grid gap-x-6 gap-y-4 sm:grid-cols-2">
                                <div>
                                    <dt className="text-xs font-bold tracking-wider text-slate-500 uppercase">
                                        Issuer
                                    </dt>
                                    <dd className="mt-1 text-sm font-semibold">
                                        {certificate.issuer}
                                    </dd>
                                </div>
                                <div>
                                    <dt className="text-xs font-bold tracking-wider text-slate-500 uppercase">
                                        Validity
                                    </dt>
                                    <dd className="mt-1 text-sm font-semibold">
                                        {formatDate(certificate.valid_from)} –{' '}
                                        {formatDate(certificate.expires_at)}
                                    </dd>
                                </div>
                                <div className="sm:col-span-2">
                                    <dt className="text-xs font-bold tracking-wider text-slate-500 uppercase">
                                        SHA-256 fingerprint
                                    </dt>
                                    <dd className="mt-1 font-mono text-xs break-all text-slate-700">
                                        {certificate.fingerprint}
                                    </dd>
                                </div>
                            </dl>
                            <p className="mt-5 rounded-lg bg-slate-50 p-3 text-xs leading-5 text-slate-600">
                                The private signing key is encrypted in the
                                database and never sent to this page. Rotating
                                certificates preserves old public certificates
                                so tickets already issued remain verifiable.
                            </p>
                        </section>

                        <section className="rounded-xl border border-slate-200 bg-white p-5 shadow-sm sm:p-6">
                            <div className="flex items-center gap-3">
                                <span className="grid size-11 place-items-center rounded-lg bg-red-50 text-red-700">
                                    <Fingerprint size={22} />
                                </span>
                                <div>
                                    <h2 className="text-lg font-bold">
                                        Install a trusted certificate
                                    </h2>
                                    <p className="text-sm text-slate-500">
                                        Upload a password-protected PKCS#12 file
                                        (.p12 or .pfx).
                                    </p>
                                </div>
                            </div>
                            <form
                                onSubmit={installCertificate}
                                className="mt-5 space-y-4"
                            >
                                <div>
                                    <label
                                        htmlFor="certificate_bundle"
                                        className="text-sm font-semibold"
                                    >
                                        Certificate file
                                    </label>
                                    <input
                                        id="certificate_bundle"
                                        type="file"
                                        accept=".p12,.pfx"
                                        onChange={(event) =>
                                            uploadForm.setData(
                                                'certificate_bundle',
                                                event.target.files?.[0] ?? null,
                                            )
                                        }
                                        className="mt-2 block w-full rounded-lg border border-slate-300 bg-white p-2.5 text-sm file:mr-3 file:rounded-md file:border-0 file:bg-slate-100 file:px-3 file:py-2 file:font-semibold"
                                    />
                                    {uploadForm.errors.certificate_bundle && (
                                        <p className="mt-1 text-sm text-red-700">
                                            {
                                                uploadForm.errors
                                                    .certificate_bundle
                                            }
                                        </p>
                                    )}
                                </div>
                                <div>
                                    <label
                                        htmlFor="certificate_password"
                                        className="text-sm font-semibold"
                                    >
                                        File password
                                    </label>
                                    <input
                                        id="certificate_password"
                                        type="password"
                                        autoComplete="new-password"
                                        value={
                                            uploadForm.data.certificate_password
                                        }
                                        onChange={(event) =>
                                            uploadForm.setData(
                                                'certificate_password',
                                                event.target.value,
                                            )
                                        }
                                        className="mt-2 w-full rounded-lg border border-slate-300 px-3 py-2.5 text-sm outline-none focus:border-red-600 focus:ring-2 focus:ring-red-600/15"
                                    />
                                    {uploadForm.errors.certificate_password && (
                                        <p className="mt-1 text-sm text-red-700">
                                            {
                                                uploadForm.errors
                                                    .certificate_password
                                            }
                                        </p>
                                    )}
                                </div>
                                <button
                                    type="submit"
                                    disabled={
                                        uploadForm.processing ||
                                        !uploadForm.data.certificate_bundle
                                    }
                                    className="inline-flex min-h-11 items-center justify-center gap-2 rounded-lg bg-[#cf3329] px-4 text-sm font-bold text-white hover:bg-[#ae281f] disabled:cursor-not-allowed disabled:opacity-50"
                                >
                                    <Upload size={16} />{' '}
                                    {uploadForm.processing
                                        ? 'Installing…'
                                        : 'Install and activate'}
                                </button>
                            </form>
                        </section>
                    </div>

                    <section className="mt-6 overflow-hidden rounded-xl border border-slate-200 bg-white">
                        <div className="border-b border-slate-200 px-5 py-4 sm:px-6">
                            <h2 className="font-bold">Previous certificates</h2>
                            <p className="mt-1 text-sm text-slate-500">
                                Public certificates remain available to validate
                                QR codes issued before a rotation.
                            </p>
                        </div>
                        {previousCertificates.length ? (
                            previousCertificates.map((previous) => (
                                <article
                                    key={previous.id}
                                    className="grid gap-2 border-b border-slate-100 px-5 py-4 last:border-0 sm:grid-cols-[1fr_auto] sm:items-center sm:px-6"
                                >
                                    <div>
                                        <p className="text-sm font-bold">
                                            {previous.subject}{' '}
                                            {previous.self_signed && (
                                                <span className="font-medium text-amber-700">
                                                    · Self-signed
                                                </span>
                                            )}
                                        </p>
                                        <p className="mt-1 font-mono text-[11px] break-all text-slate-500">
                                            {previous.fingerprint}
                                        </p>
                                    </div>
                                    <p className="text-xs text-slate-500">
                                        Expired{' '}
                                        {formatDate(previous.expires_at)}
                                    </p>
                                </article>
                            ))
                        ) : (
                            <p className="px-5 py-7 text-sm text-slate-500 sm:px-6">
                                No earlier certificates.
                            </p>
                        )}
                    </section>
                </div>
            </main>
        </>
    );
}
