import { Head, router, useForm } from '@inertiajs/react';
import {
    AlertTriangle,
    Archive,
    Clock3,
    Database,
    Download,
    RotateCcw,
} from 'lucide-react';

type Backup = {
    id: number;
    source: string;
    status: string;
    size_bytes: number | null;
    created_at: string | null;
    completed_at: string | null;
    failure_reason: string | null;
    requested_by: string;
    download_url: string | null;
};

type Activity = {
    action: string;
    status: string;
    actor: string;
    details: Record<string, unknown> | null;
    created_at: string | null;
    failure_reason: string | null;
};

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

function formatSize(value: number | null): string {
    if (value === null) return '—';
    return `${(value / 1024 / 1024).toFixed(1)} MB`;
}

export default function SystemBackups({
    backups,
    activities,
    configured,
    scheduled_enabled: scheduledEnabled,
    latest_success: latestSuccess,
    overdue,
}: {
    backups: Backup[];
    activities: Activity[];
    configured: boolean;
    scheduled_enabled: boolean;
    latest_success: string | null;
    overdue: boolean;
}) {
    const backupForm = useForm({});

    return (
        <>
            <Head title="System backups" />
            <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-[1500px]">
                    <div className="flex flex-col justify-between gap-5 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">
                                System backups
                            </h1>
                            <p className="mt-1 max-w-2xl text-sm text-slate-600">
                                Encrypted snapshots include the database and
                                private uploads. Application secrets and code
                                are never included.
                            </p>
                        </div>
                        <button
                            type="button"
                            disabled={!configured || backupForm.processing}
                            onClick={() =>
                                backupForm.post('/super-admin/backups')
                            }
                            className="inline-flex min-h-12 items-center justify-center gap-2 rounded-lg bg-[#cf3329] px-5 font-bold text-white hover:bg-[#ae281f] disabled:cursor-not-allowed disabled:opacity-50"
                        >
                            <Archive size={18} /> Create backup
                        </button>
                    </div>

                    {!configured ? (
                        <div
                            role="alert"
                            className="mt-6 flex gap-3 rounded-xl border border-amber-300 bg-amber-50 p-4 text-sm text-amber-950"
                        >
                            <AlertTriangle
                                className="mt-0.5 shrink-0"
                                size={19}
                            />
                            <p>
                                Encrypted backup storage is not configured for
                                this deployment. Set the private archive
                                password in the application environment before
                                creating backups.
                            </p>
                        </div>
                    ) : null}
                    {overdue && configured ? (
                        <div
                            role="alert"
                            className="mt-4 flex gap-3 rounded-xl border border-red-300 bg-red-50 p-4 text-sm text-red-900"
                        >
                            <AlertTriangle
                                className="mt-0.5 shrink-0"
                                size={19}
                            />
                            <p>
                                No successful backup has completed in the past
                                36 hours. Check that the cPanel scheduler is
                                running and review failed operations below.
                            </p>
                        </div>
                    ) : null}

                    <div className="mt-6 grid gap-4 sm:grid-cols-3">
                        <div className="rounded-xl border border-black/10 bg-white p-5">
                            <div className="flex items-center gap-2 text-sm font-bold text-slate-500">
                                <Database size={17} /> Latest successful backup
                            </div>
                            <p className="mt-3 text-lg font-extrabold">
                                {formatDate(latestSuccess)}
                            </p>
                        </div>
                        <div className="rounded-xl border border-black/10 bg-white p-5">
                            <div className="flex items-center gap-2 text-sm font-bold text-slate-500">
                                <Clock3 size={17} /> Schedule
                            </div>
                            <p className="mt-3 text-lg font-extrabold">
                                {scheduledEnabled
                                    ? 'Enabled · nightly at 02:00'
                                    : 'Paused until server checks pass'}
                            </p>
                            <p className="mt-1 text-xs text-slate-500">
                                {scheduledEnabled
                                    ? 'Requires cPanel to run Laravel’s scheduler every minute.'
                                    : 'Confirm ZIP encryption and MySQL dump support on cPanel, then set BACKUP_ENABLED=true for this deployment.'}
                            </p>
                        </div>
                        <div className="rounded-xl border border-black/10 bg-white p-5">
                            <div className="flex items-center gap-2 text-sm font-bold text-slate-500">
                                <Archive size={17} /> Retention
                            </div>
                            <p className="mt-3 text-lg font-extrabold">
                                30 days
                            </p>
                            <p className="mt-1 text-xs text-slate-500">
                                Backups remain in private application storage.
                            </p>
                        </div>
                    </div>

                    <section className="mt-8 overflow-hidden rounded-xl border border-black/10 bg-white">
                        <div className="border-b border-black/10 px-5 py-4 sm:px-6">
                            <h2 className="text-xl font-black">
                                Backup history
                            </h2>
                            <p className="mt-1 text-sm text-slate-500">
                                Restore replaces the database and private
                                uploads. A safety backup is created first.
                            </p>
                        </div>
                        {backups.length ? (
                            <div className="divide-y divide-black/10">
                                {backups.map((backup) => (
                                    <article
                                        key={backup.id}
                                        className="flex flex-col gap-4 px-5 py-4 sm:flex-row sm:items-center sm:justify-between sm:px-6"
                                    >
                                        <div className="min-w-0">
                                            <div className="flex flex-wrap items-center gap-2">
                                                <h3 className="font-extrabold">
                                                    Backup #{backup.id}
                                                </h3>
                                                <span
                                                    className={`rounded-full px-2.5 py-1 text-xs font-bold capitalize ${backup.status === 'completed' ? 'bg-emerald-100 text-emerald-800' : backup.status === 'failed' ? 'bg-red-100 text-red-800' : 'bg-amber-100 text-amber-900'}`}
                                                >
                                                    {backup.status}
                                                </span>
                                                <span className="text-xs text-slate-500">
                                                    {backup.source}
                                                </span>
                                            </div>
                                            <p className="mt-1 text-sm text-slate-600">
                                                {formatDate(backup.created_at)}{' '}
                                                ·{' '}
                                                {formatSize(backup.size_bytes)}{' '}
                                                · requested by{' '}
                                                {backup.requested_by}
                                            </p>
                                            {backup.failure_reason ? (
                                                <p className="mt-1 text-sm text-red-700">
                                                    {backup.failure_reason}
                                                </p>
                                            ) : null}
                                        </div>
                                        <div className="flex shrink-0 flex-wrap gap-2">
                                            {backup.download_url ? (
                                                <a
                                                    href={backup.download_url}
                                                    className="inline-flex min-h-10 items-center gap-2 rounded-lg border border-black/15 px-3 text-sm font-bold hover:bg-slate-50"
                                                >
                                                    <Download size={16} />{' '}
                                                    Download
                                                </a>
                                            ) : null}
                                            {backup.status === 'completed' ? (
                                                <button
                                                    type="button"
                                                    onClick={() => {
                                                        const confirmation =
                                                            window.prompt(
                                                                'This replaces the current database and private uploads. Type RESTORE to queue a restore.',
                                                            );
                                                        if (
                                                            confirmation ===
                                                            'RESTORE'
                                                        )
                                                            router.post(
                                                                `/super-admin/backups/${backup.id}/restore`,
                                                                {
                                                                    confirmation,
                                                                },
                                                            );
                                                    }}
                                                    className="inline-flex min-h-10 items-center gap-2 rounded-lg border border-red-200 px-3 text-sm font-bold text-red-800 hover:bg-red-50"
                                                >
                                                    <RotateCcw size={16} />{' '}
                                                    Restore
                                                </button>
                                            ) : null}
                                        </div>
                                    </article>
                                ))}
                            </div>
                        ) : (
                            <p className="px-6 py-10 text-center text-sm text-slate-500">
                                No backups yet. Create one now or wait for the
                                nightly schedule.
                            </p>
                        )}
                    </section>

                    <section className="mt-8 overflow-hidden rounded-xl border border-black/10 bg-white">
                        <div className="border-b border-black/10 px-5 py-4 sm:px-6">
                            <h2 className="text-xl font-black">
                                Recent operations
                            </h2>
                        </div>
                        {activities.length ? (
                            <div className="divide-y divide-black/10">
                                {activities.map((activity, index) => (
                                    <div
                                        key={`${activity.action}-${activity.created_at}-${index}`}
                                        className="flex flex-col gap-1 px-5 py-3 text-sm sm:flex-row sm:items-center sm:justify-between sm:px-6"
                                    >
                                        <p>
                                            <span className="font-bold capitalize">
                                                {activity.action}
                                            </span>{' '}
                                            ·{' '}
                                            <span className="capitalize">
                                                {activity.status}
                                            </span>{' '}
                                            · {activity.actor}
                                        </p>
                                        <p className="text-slate-500">
                                            {formatDate(activity.created_at)}
                                        </p>
                                        {activity.failure_reason ? (
                                            <p className="text-red-700">
                                                {activity.failure_reason}
                                            </p>
                                        ) : null}
                                    </div>
                                ))}
                            </div>
                        ) : (
                            <p className="px-6 py-8 text-sm text-slate-500">
                                No backup or restore activity has been recorded.
                            </p>
                        )}
                    </section>
                </div>
            </main>
        </>
    );
}
