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

interface Locale {
    code: string;
    label: string;
    is_default: boolean;
    enabled: boolean;
    translated: number;
}

interface Props {
    locales: Locale[];
    totalKeys: number;
}

export default function AdminLanguages({ locales, totalKeys }: Props) {
    const t = useTranslator();
    const { flash } = usePage<any>().props;
    const addForm = useForm({ code: '', label: '' });

    function addLanguage(e: React.FormEvent) {
        e.preventDefault();
        addForm.post('/admin/languages', { onSuccess: () => addForm.reset(), preserveScroll: true });
    }

    function setDefault(code: string) {
        router.post(`/admin/languages/${code}/default`, {}, { preserveScroll: true });
    }

    function toggleEnabled(l: Locale) {
        router.patch(`/admin/languages/${l.code}`, { enabled: !l.enabled }, { preserveScroll: true });
    }

    function remove(l: Locale) {
        if (!confirm(t('admin.lang_delete_confirm', { label: l.label }))) return;
        router.delete(`/admin/languages/${l.code}`, { preserveScroll: true });
    }

    return (
        <AppLayout>
            <div className="max-w-4xl mx-auto px-6 py-10">
                <div className="mb-8">
                    <Link href="/admin" className="text-sm text-muted-foreground hover:text-foreground">← {t('admin.back')}</Link>
                    <h1 className="font-serif text-3xl mt-2">{t('admin.languages')}</h1>
                    <p className="text-sm text-muted-foreground mt-1 max-w-xl">
                        {t('admin.lang_intro')}
                    </p>
                </div>

                {flash?.error && (
                    <div className="mb-4 rounded-lg border border-danger/30 bg-danger/10 px-4 py-3 text-sm text-danger">{flash.error}</div>
                )}
                {flash?.success && (
                    <div className="mb-4 rounded-lg border border-success/30 bg-success/10 px-4 py-3 text-sm text-success">{flash.success}</div>
                )}

                {/* Language list */}
                <div className="space-y-2 mb-8">
                    {locales.map((l) => {
                        const pct = totalKeys > 0 ? Math.round((l.translated / totalKeys) * 100) : 0;
                        return (
                            <div key={l.code} className="bg-card border border-border rounded-xl p-4 flex items-center justify-between gap-4 flex-wrap">
                                <div className="min-w-0">
                                    <div className="flex items-center gap-2">
                                        <span className="font-medium">{l.label}</span>
                                        <span className="text-[11px] uppercase tracking-wide text-muted-foreground bg-muted px-1.5 py-0.5 rounded">{l.code}</span>
                                        {l.is_default && (
                                            <span className="text-[10.5px] uppercase tracking-[0.14em] text-primary bg-primary/10 px-2 py-0.5 rounded-full">{t('admin.lang_default')}</span>
                                        )}
                                    </div>
                                    <p className="text-[12px] text-muted-foreground mt-1">
                                        {l.code === 'en'
                                            ? t('admin.lang_base_note')
                                            : t('admin.lang_translated_note', { translated: l.translated, total: totalKeys, pct })}
                                    </p>
                                </div>
                                <div className="flex items-center gap-3 shrink-0">
                                    <Link
                                        href={`/admin/languages/${l.code}/translations`}
                                        className="text-sm text-primary hover:underline"
                                    >
                                        {t('admin.lang_edit')}
                                    </Link>
                                    {!l.is_default && (
                                        <button onClick={() => setDefault(l.code)} className="text-sm text-muted-foreground hover:text-foreground">
                                            {t('admin.lang_make_default')}
                                        </button>
                                    )}
                                    <label className="flex items-center gap-1.5 text-sm text-muted-foreground cursor-pointer" title={l.is_default ? t('admin.lang_default_enabled_title') : t('admin.lang_switcher_title')}>
                                        <input
                                            type="checkbox"
                                            checked={l.enabled}
                                            disabled={l.is_default}
                                            onChange={() => toggleEnabled(l)}
                                        />
                                        {t('admin.lang_enabled')}
                                    </label>
                                    {!l.is_default && (
                                        <button onClick={() => remove(l)} className="text-sm text-danger hover:underline">{t('common.delete')}</button>
                                    )}
                                </div>
                            </div>
                        );
                    })}
                </div>

                {/* Add language */}
                <div className="bg-card border border-border rounded-xl p-6">
                    <h2 className="font-semibold mb-1">{t('admin.lang_add_title')}</h2>
                    <p className="text-[12px] text-muted-foreground mb-4">
                        {t('admin.lang_add_note')}
                    </p>
                    <form onSubmit={addLanguage} className="flex gap-3 items-start flex-wrap">
                        <div>
                            <input
                                type="text"
                                placeholder={t('admin.lang_code_placeholder')}
                                value={addForm.data.code}
                                onChange={(e) => addForm.setData('code', e.target.value)}
                                className="border border-border rounded-lg px-3 py-2 text-sm w-40"
                                required
                            />
                            {addForm.errors.code && <p className="text-danger text-xs mt-1">{addForm.errors.code}</p>}
                        </div>
                        <div>
                            <input
                                type="text"
                                placeholder={t('admin.lang_label_placeholder')}
                                value={addForm.data.label}
                                onChange={(e) => addForm.setData('label', e.target.value)}
                                className="border border-border rounded-lg px-3 py-2 text-sm w-56"
                                required
                            />
                            {addForm.errors.label && <p className="text-danger text-xs mt-1">{addForm.errors.label}</p>}
                        </div>
                        <button type="submit" disabled={addForm.processing} className="bg-primary text-primary-foreground px-4 py-2 rounded-lg text-sm disabled:opacity-50">
                            {t('admin.lang_add_button')}
                        </button>
                    </form>
                </div>
            </div>
        </AppLayout>
    );
}
