import ClientLayout from '@/Layouts/ClientLayout';
import { parseServerDate } from '@/lib/date';
import { PageProps } from '@/types';
import { Head, Link } from '@inertiajs/react';
import {
    AlertTriangle,
    Building2,
    CheckCircle2,
    Circle,
    CreditCard,
    ExternalLink,
    Globe,
    Users,
    Zap,
} from 'lucide-react';
import AppNav, { AppDetailWithNext } from './components/AppNav';

const ORG_TYPE_LABELS: Record<string, string> = {
    sacco: 'SACCO',
    microfinance: 'Microfinance',
    bank: 'Bank',
    insurance: 'Insurance',
    other: 'Organisation',
};

function statusColor(status: string | null) {
    switch (status) {
        case 'trialing':
            return 'text-sky-600 bg-sky-50 border-sky-200 dark:text-sky-400 dark:bg-sky-900/20 dark:border-sky-700/30';
        case 'active':
            return 'text-emerald-600 bg-emerald-50 border-emerald-200 dark:text-emerald-400 dark:bg-emerald-900/20 dark:border-emerald-700/30';
        case 'past_due':
            return 'text-amber-600 bg-amber-50 border-amber-200 dark:text-amber-400 dark:bg-amber-900/20 dark:border-amber-700/30';
        case 'suspended':
            return 'text-red-600 bg-red-50 border-red-200 dark:text-red-400 dark:bg-red-900/20 dark:border-red-700/30';
        default:
            return 'text-muted-foreground bg-muted border-border';
    }
}

function LimitRow({
    label,
    value,
}: {
    label: string;
    value: number | null | undefined;
}) {
    const display = value == null ? 'Unlimited' : value.toLocaleString();
    return (
        <div className="flex items-center justify-between gap-4 py-2.5">
            <span className="text-muted-foreground text-sm">{label}</span>
            <span className="text-foreground text-sm font-medium">
                {display}
            </span>
        </div>
    );
}

type Props = PageProps<{ app: AppDetailWithNext }>;

export default function AppShow({ app }: Props) {
    const trialDaysLeft = app.trialEndsAt
        ? Math.max(
              0,
              Math.ceil(
                  (new Date(app.trialEndsAt).getTime() - Date.now()) /
                      86_400_000,
              ),
          )
        : null;

    const setupSteps = [
        { label: 'Organisation details', done: true },
        { label: 'Subdomain configured', done: !!app.subdomain },
        { label: 'Plan selected', done: !!app.plan },
    ];

    return (
        <ClientLayout title={app.name}>
            <Head title={`${app.name} — Overview`} />

            <AppNav app={app} />

            <div className="space-y-6 p-6 lg:p-8">
                {/* Status banner — setup incomplete */}
                {!app.setupComplete && (
                    <div className="flex items-start gap-3 rounded-xl border border-amber-200 bg-amber-50 p-4 dark:border-amber-700/30 dark:bg-amber-900/10">
                        <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-amber-600 dark:text-amber-400" />
                        <div className="flex-1">
                            <p className="text-sm font-semibold text-amber-800 dark:text-amber-300">
                                Setup not complete
                            </p>
                            <p className="mt-0.5 text-xs text-amber-700 dark:text-amber-400">
                                Complete the remaining steps below to go live.
                            </p>
                        </div>
                        {app.nextStep && (
                            <Link
                                href={app.nextStep}
                                className="pf-btn shrink-0 px-3 py-1.5 text-xs"
                            >
                                Continue →
                            </Link>
                        )}
                    </div>
                )}

                {/* Trial banner */}
                {app.planStatus === 'trialing' && trialDaysLeft !== null && (
                    <div className="flex items-center justify-between gap-4 rounded-xl border border-sky-200 bg-sky-50 p-4 dark:border-sky-700/30 dark:bg-sky-900/10">
                        <div className="flex items-center gap-3">
                            <Zap className="h-4 w-4 shrink-0 text-sky-600 dark:text-sky-400" />
                            <p className="text-sm text-sky-800 dark:text-sky-300">
                                <span className="font-semibold">
                                    {trialDaysLeft} days
                                </span>{' '}
                                remaining on your {app.plan} trial.
                            </p>
                        </div>
                        <Link
                            href={route('app.billing', { tenant: app.id })}
                            className="shrink-0 text-xs font-semibold text-sky-700 underline dark:text-sky-400"
                        >
                            Manage billing →
                        </Link>
                    </div>
                )}

                <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
                    {/* Left column — 2/3 */}
                    <div className="space-y-6 lg:col-span-2">
                        {/* App info card */}
                        <div className="pf-glass divide-border divide-y overflow-hidden">
                            <div className="px-5 py-4">
                                <p className="text-foreground text-sm font-semibold">
                                    App details
                                </p>
                            </div>
                            <dl className="divide-border divide-y">
                                {[
                                    {
                                        label: 'Organisation name',
                                        value: app.name,
                                        icon: Building2,
                                    },
                                    {
                                        label: 'Type',
                                        value: app.orgType
                                            ? (ORG_TYPE_LABELS[app.orgType] ??
                                              app.orgType)
                                            : '—',
                                        icon: Users,
                                    },
                                    {
                                        label: 'Country',
                                        value: app.country ?? '—',
                                        icon: Globe,
                                    },
                                    {
                                        label: 'Subdomain',
                                        value: app.domain ?? 'Not set',
                                        icon: Globe,
                                        mono: true,
                                        link: app.portalUrl,
                                    },
                                ].map(
                                    ({
                                        label,
                                        value,
                                        icon: Icon,
                                        mono,
                                        link,
                                    }) => (
                                        <div
                                            key={label}
                                            className="flex items-center gap-4 px-5 py-3.5"
                                        >
                                            <Icon className="text-muted-foreground dark:text-muted-foreground/50 h-4 w-4 shrink-0" />
                                            <dt className="text-muted-foreground w-36 shrink-0 text-sm">
                                                {label}
                                            </dt>
                                            <dd
                                                className={`text-foreground min-w-0 flex-1 text-sm font-medium ${mono ? 'font-mono' : ''}`}
                                            >
                                                {link ? (
                                                    <a
                                                        href={link}
                                                        target="_blank"
                                                        rel="noreferrer"
                                                        className="text-primary flex items-center gap-1 hover:underline"
                                                    >
                                                        {value}
                                                        <ExternalLink className="h-3 w-3" />
                                                    </a>
                                                ) : (
                                                    value
                                                )}
                                            </dd>
                                        </div>
                                    ),
                                )}
                            </dl>
                            <div className="px-5 py-3">
                                <Link
                                    href={route('app.settings', {
                                        tenant: app.id,
                                    })}
                                    className="text-primary text-xs font-medium hover:underline"
                                >
                                    Edit settings →
                                </Link>
                            </div>
                        </div>

                        {/* Setup checklist */}
                        {!app.setupComplete && (
                            <div className="pf-glass overflow-hidden">
                                <div className="border-border border-b px-5 py-4">
                                    <p className="text-foreground text-sm font-semibold">
                                        Setup checklist
                                    </p>
                                </div>
                                <div className="divide-border divide-y">
                                    {setupSteps.map((step) => (
                                        <div
                                            key={step.label}
                                            className="flex items-center gap-3 px-5 py-3.5"
                                        >
                                            {step.done ? (
                                                <CheckCircle2 className="text-primary h-4 w-4 shrink-0" />
                                            ) : (
                                                <Circle className="text-border h-4 w-4 shrink-0" />
                                            )}
                                            <span
                                                className={`text-sm ${step.done ? 'text-muted-foreground line-through' : 'text-foreground font-medium'}`}
                                            >
                                                {step.label}
                                            </span>
                                            {step.done && (
                                                <span className="ml-auto text-[10px] font-semibold text-emerald-600 dark:text-emerald-400">
                                                    Done
                                                </span>
                                            )}
                                        </div>
                                    ))}
                                </div>
                            </div>
                        )}
                    </div>

                    {/* Right column — 1/3 */}
                    <div className="space-y-4">
                        {/* Subscription card */}
                        <div className="pf-glass overflow-hidden">
                            <div className="border-border border-b px-5 py-4">
                                <div className="flex items-center justify-between gap-2">
                                    <p className="text-foreground text-sm font-semibold">
                                        Subscription
                                    </p>
                                    <CreditCard className="text-muted-foreground dark:text-muted-foreground/40 h-4 w-4" />
                                </div>
                            </div>

                            {app.plan ? (
                                <div className="space-y-3 px-5 py-4">
                                    <div className="flex items-center justify-between gap-2">
                                        <span className="text-foreground font-semibold">
                                            {app.plan}
                                        </span>
                                        <span
                                            className={`rounded-full border px-2 py-0.5 text-[10px] font-semibold capitalize ${statusColor(app.planStatus)}`}
                                        >
                                            {app.planStatus}
                                        </span>
                                    </div>
                                    {app.billingCycle && (
                                        <p className="text-muted-foreground dark:text-muted-foreground/70 text-xs capitalize">
                                            {app.billingCycle} billing
                                        </p>
                                    )}
                                    {app.trialEndsAt &&
                                        app.planStatus === 'trialing' && (
                                            <p className="text-muted-foreground text-xs">
                                                Trial ends{' '}
                                                {parseServerDate(
                                                    app.trialEndsAt,
                                                ).toLocaleDateString()}
                                            </p>
                                        )}
                                    {app.currentPeriodEnd &&
                                        app.planStatus !== 'trialing' && (
                                            <p className="text-muted-foreground text-xs">
                                                Renews{' '}
                                                {parseServerDate(
                                                    app.currentPeriodEnd,
                                                ).toLocaleDateString()}
                                            </p>
                                        )}
                                </div>
                            ) : (
                                <div className="px-5 py-4">
                                    <p className="text-muted-foreground text-sm">
                                        No plan selected
                                    </p>
                                </div>
                            )}

                            <div className="border-border border-t px-5 py-3">
                                <Link
                                    href={route('app.billing', {
                                        tenant: app.id,
                                    })}
                                    className="text-primary text-xs font-medium hover:underline"
                                >
                                    Manage billing →
                                </Link>
                            </div>
                        </div>

                        {/* Plan limits */}
                        {app.limits && (
                            <div className="pf-glass overflow-hidden">
                                <div className="border-border border-b px-5 py-4">
                                    <p className="text-foreground text-sm font-semibold">
                                        Plan limits
                                    </p>
                                </div>
                                <div className="divide-border divide-y px-5">
                                    <LimitRow
                                        label="Branches"
                                        value={app.limits.maxBranches}
                                    />
                                    <LimitRow
                                        label="Staff users"
                                        value={app.limits.maxStaffUsers}
                                    />
                                    <LimitRow
                                        label="Active borrowers"
                                        value={app.limits.maxActiveBorrowers}
                                    />
                                    <LimitRow
                                        label="Active loans"
                                        value={app.limits.maxActiveLoans}
                                    />
                                    <LimitRow
                                        label="Storage"
                                        value={
                                            app.limits.maxStorageGb != null
                                                ? app.limits.maxStorageGb
                                                : null
                                        }
                                    />
                                </div>
                            </div>
                        )}
                    </div>
                </div>
            </div>
        </ClientLayout>
    );
}
