import { router, Link } from '@inertiajs/react';
import AppLayout from '@/layouts/AppLayout';
import { useTranslator } from '@/lib/i18n';

type Plan = 'free' | 'premium' | 'planner';

interface User {
    id: string;
    name: string;
    email: string;
    is_admin: boolean;
    is_blocked: boolean;
    plan: Plan | null;
    email_verified_at?: string;
    created_at: string;
}

interface Props {
    users: {
        data: User[];
        current_page: number;
        last_page: number;
    };
}

const PLAN_STYLES: Record<Plan, string> = {
    free:    'bg-muted text-foreground/70 border-border',
    premium: 'bg-primary/[0.10] text-primary border-primary/30',
    planner: 'bg-foreground text-background border-foreground',
};

export default function AdminUsers({ users }: Props) {
    const t = useTranslator();

    function toggleAdmin(user: User) {
        router.patch(`/admin/users/${user.id}/admin`, { is_admin: !user.is_admin }, { preserveScroll: true });
    }

    function toggleBlocked(user: User) {
        const verb = user.is_blocked ? t('admin.verb_reinstate') : t('admin.verb_suspend');
        if (!confirm(t('admin.confirm_toggle', { verb, email: user.email }))) return;
        router.patch(`/admin/users/${user.id}/blocked`, { is_blocked: !user.is_blocked }, { preserveScroll: true });
    }

    function setPlan(user: User, plan: Plan) {
        if (plan === (user.plan ?? 'free')) return;
        router.patch(`/admin/users/${user.id}/plan`, { plan }, { preserveScroll: true });
    }

    function deleteUser(user: User) {
        if (!confirm(t('admin.confirm_delete_user', { email: user.email }))) return;
        router.delete(`/admin/users/${user.id}`, { preserveScroll: true });
    }

    return (
        <AppLayout>
            <div className="max-w-5xl mx-auto px-6 py-10">
                <div className="flex items-center gap-4 mb-8">
                    <Link href="/admin" className="text-muted-foreground hover:text-foreground">← {t('admin.back')}</Link>
                    <h1 className="font-serif text-3xl">{t('admin.users_title')}</h1>
                </div>

                <div className="overflow-x-auto">
                    <table className="w-full text-sm">
                        <thead>
                            <tr className="border-b border-border text-left">
                                <th className="pb-2 font-medium text-muted-foreground pr-4">{t('admin.col_name')}</th>
                                <th className="pb-2 font-medium text-muted-foreground pr-4">{t('admin.col_email')}</th>
                                <th className="pb-2 font-medium text-muted-foreground pr-4">{t('admin.col_verified')}</th>
                                <th className="pb-2 font-medium text-muted-foreground pr-4">{t('admin.col_plan')}</th>
                                <th className="pb-2 font-medium text-muted-foreground pr-4">{t('admin.col_admin')}</th>
                                <th className="pb-2 font-medium text-muted-foreground pr-4">{t('admin.col_status')}</th>
                                <th className="pb-2 font-medium text-muted-foreground pr-4">{t('admin.col_joined')}</th>
                                <th className="pb-2" />
                            </tr>
                        </thead>
                        <tbody>
                            {users.data.map(u => (
                                <tr key={u.id} className="border-b border-border/50">
                                    <td className="py-3 pr-4 font-medium">{u.name}</td>
                                    <td className="py-3 pr-4 text-muted-foreground">{u.email}</td>
                                    <td className="py-3 pr-4">
                                        {u.email_verified_at ? <span className="text-green-600">✓</span> : <span className="text-muted-foreground">—</span>}
                                    </td>
                                    <td className="py-3 pr-4">
                                        <PlanCell user={u} onChange={(p) => setPlan(u, p)} />
                                    </td>
                                    <td className="py-3 pr-4">
                                        <button onClick={() => toggleAdmin(u)} className={`text-xs px-2 py-0.5 rounded ${u.is_admin ? 'bg-primary text-white' : 'bg-muted'}`}>
                                            {u.is_admin ? t('admin.role_admin') : t('admin.role_user')}
                                        </button>
                                    </td>
                                    <td className="py-3 pr-4">
                                        <button onClick={() => toggleBlocked(u)} className={`text-xs px-2 py-0.5 rounded ${u.is_blocked ? 'bg-red-500/15 text-red-700' : 'bg-emerald-500/15 text-emerald-700'}`}>
                                            {u.is_blocked ? t('admin.status_suspended') : t('admin.status_active')}
                                        </button>
                                    </td>
                                    <td className="py-3 pr-4 text-muted-foreground text-xs">
                                        {new Date(u.created_at).toLocaleDateString()}
                                    </td>
                                    <td className="py-3">
                                        <button onClick={() => deleteUser(u)} className="text-xs text-red-500 hover:underline">{t('common.delete')}</button>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>

                <p className="text-[11px] text-muted-foreground mt-3">
                    {t('admin.plan_note')}
                </p>

                {users.last_page > 1 && (
                    <div className="flex gap-2 mt-6">
                        {Array.from({ length: users.last_page }, (_, i) => i + 1).map(page => (
                            <Link
                                key={page}
                                href={`/admin/users?page=${page}`}
                                className={`px-3 py-1 rounded text-sm ${page === users.current_page ? 'bg-primary text-white' : 'border border-border hover:bg-muted'}`}
                            >
                                {page}
                            </Link>
                        ))}
                    </div>
                )}
            </div>
        </AppLayout>
    );
}

function PlanCell({ user, onChange }: { user: User; onChange: (plan: Plan) => void }) {
    const t = useTranslator();
    const current: Plan = (user.plan ?? 'free') as Plan;
    return (
        <div className="relative inline-flex">
            <span
                className={`pointer-events-none absolute inset-0 flex items-center justify-center text-[11px] font-medium tracking-tight rounded-md border ${PLAN_STYLES[current]} px-2.5`}
                aria-hidden="true"
            >
                {t(`billing.${current}`)}
            </span>
            <select
                value={current}
                onChange={(e) => onChange(e.target.value as Plan)}
                className="appearance-none bg-transparent border border-transparent text-transparent text-[11px] px-2.5 py-1 rounded-md cursor-pointer outline-none focus:border-foreground/30"
                aria-label={t('admin.set_plan_aria', { email: user.email })}
                style={{ minWidth: '5.25rem' }}
            >
                <option value="free">{t('billing.free')}</option>
                <option value="premium">{t('billing.premium')}</option>
                <option value="planner">{t('billing.planner')}</option>
            </select>
        </div>
    );
}
