import { Head, router, useForm, usePage } from '@inertiajs/react';
import { Building2, Pencil, Plus, Trash2 } from 'lucide-react';
import { useState } from 'react';
import SystemAdminController from '@/actions/App/Http/Controllers/SystemAdminController';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useI18n } from '@/hooks/use-i18n';

type InstitutionRow = {
    id: number;
    name_bn: string;
    name_en: string | null;
    slug: string;
    phone: string | null;
    address_bn?: string | null;
    status: string;
};

export default function SystemInstitutions({ institutions }: { institutions: InstitutionRow[] }) {
    const { locale, t, localized } = useI18n();
    const { errors } = usePage<{ errors: Record<string, string> }>().props;
    const [editingId, setEditingId] = useState<number | null>(null);
    const form = useForm({
        name_bn: '',
        name_en: '',
        slug: '',
        phone: '',
        address_bn: '',
    });

    return (
        <>
            <Head title={t('nav.institutions', 'Madrasas')} />

            <div className="flex flex-col gap-6 p-4 md:p-6">
                <div>
                    <h1 className="text-2xl font-bold tracking-tight">{t('nav.institutions', 'Madrasas')}</h1>
                    <p className="text-sm text-muted-foreground">
                        {locale === 'bn' ? 'সুপার অ্যাডমিন থেকে নতুন মাদ্রাসা তৈরি ও পরিচালনা করুন।' : 'Manage all tenant madrasas.'}
                    </p>
                </div>

                {errors.delete && (
                    <div className="rounded-lg border border-destructive/30 bg-destructive/10 px-4 py-2.5 text-sm text-destructive">
                        {errors.delete}
                    </div>
                )}

                <div className="grid gap-6 lg:grid-cols-3">
                    <div className="minimal-card p-6">
                        <div className="mb-4 flex items-center gap-2">
                            <Building2 className="h-5 w-5 text-primary" />
                            <h2 className="font-semibold">
                                {editingId !== null
                                    ? locale === 'bn'
                                        ? 'মাদ্রাসা সম্পাদনা'
                                        : 'Edit Madrasa'
                                    : locale === 'bn'
                                      ? 'নতুন মাদ্রাসা যোগ'
                                      : 'Add New Madrasa'}
                            </h2>
                        </div>
                        <form
                            onSubmit={(e) => {
                                e.preventDefault();
                                if (editingId !== null) {
                                    form.put(SystemAdminController.updateInstitution.url(editingId), {
                                        onSuccess: () => {
                                            setEditingId(null);
                                            form.reset();
                                        },
                                    });
                                } else {
                                    form.submit(SystemAdminController.storeInstitution(), {
                                        onSuccess: () => form.reset(),
                                    });
                                }
                            }}
                            className="space-y-3"
                        >
                            <div className="space-y-1">
                                <Label>{locale === 'bn' ? 'নাম (বাংলা)' : 'Name (Bangla)'}</Label>
                                <Input value={form.data.name_bn} onChange={(e) => form.setData('name_bn', e.target.value)} required />
                            </div>
                            <div className="space-y-1">
                                <Label>{locale === 'bn' ? 'নাম (ইংরেজি)' : 'Name (English)'}</Label>
                                <Input value={form.data.name_en} onChange={(e) => form.setData('name_en', e.target.value)} />
                            </div>
                            <div className="space-y-1">
                                <Label>{locale === 'bn' ? 'ফোন' : 'Phone'}</Label>
                                <Input value={form.data.phone} onChange={(e) => form.setData('phone', e.target.value)} />
                            </div>
                            <div className="flex gap-2">
                                <Button type="submit" disabled={form.processing} className="flex-1">
                                    <Plus className="mr-1.5 h-4 w-4" />
                                    {editingId !== null
                                        ? locale === 'bn'
                                            ? 'আপডেট করুন'
                                            : 'Update Madrasa'
                                        : locale === 'bn'
                                          ? 'মাদ্রাসা তৈরি করুন'
                                          : 'Create Madrasa'}
                                </Button>
                                {editingId !== null && (
                                    <Button
                                        type="button"
                                        variant="outline"
                                        onClick={() => {
                                            setEditingId(null);
                                            form.reset();
                                        }}
                                    >
                                        {t('common.cancel', 'Cancel')}
                                    </Button>
                                )}
                            </div>
                        </form>
                    </div>

                    <div className="minimal-card overflow-x-auto p-6 lg:col-span-2">
                        <table className="w-full text-left text-sm">
                            <thead className="border-b bg-muted/40 text-xs uppercase text-muted-foreground">
                                <tr>
                                    <th className="px-4 py-2">{locale === 'bn' ? 'মাদ্রাসা' : 'Madrasa'}</th>
                                    <th className="px-4 py-2">Slug</th>
                                    <th className="px-4 py-2">{locale === 'bn' ? 'ফোন' : 'Phone'}</th>
                                    <th className="px-4 py-2">{locale === 'bn' ? 'অবস্থা' : 'Status'}</th>
                                    <th className="px-4 py-2 text-right">{locale === 'bn' ? 'অ্যাকশন' : 'Actions'}</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y">
                                {institutions.map((inst) => (
                                    <tr key={inst.id}>
                                        <td className="px-4 py-2.5 font-medium">{localized(inst, 'name')}</td>
                                        <td className="px-4 py-2.5 text-muted-foreground">{inst.slug}</td>
                                        <td className="px-4 py-2.5">{inst.phone ?? '—'}</td>
                                        <td className="px-4 py-2.5 uppercase text-xs font-semibold text-primary">{inst.status}</td>
                                        <td className="px-4 py-2.5 text-right">
                                            <div className="inline-flex items-center gap-1">
                                                <Button
                                                    type="button"
                                                    size="icon"
                                                    variant="ghost"
                                                    title={locale === 'bn' ? 'সম্পাদনা' : 'Edit'}
                                                    onClick={() => {
                                                        setEditingId(inst.id);
                                                        form.setData({
                                                            name_bn: inst.name_bn,
                                                            name_en: inst.name_en ?? '',
                                                            slug: inst.slug,
                                                            phone: inst.phone ?? '',
                                                            address_bn: inst.address_bn ?? '',
                                                        });
                                                    }}
                                                >
                                                    <Pencil className="size-4" />
                                                </Button>
                                                <Button
                                                    type="button"
                                                    size="icon"
                                                    variant="ghost"
                                                    className="text-destructive hover:text-destructive"
                                                    title={locale === 'bn' ? 'মুছে ফেলুন' : 'Delete'}
                                                    onClick={() => {
                                                        if (confirm(locale === 'bn' ? 'আপনি কি নিশ্চিতভাবে এটি মুছে ফেলতে চান?' : 'Delete this madrasa?')) {
                                                            router.delete(SystemAdminController.destroyInstitution.url(inst.id));
                                                        }
                                                    }}
                                                >
                                                    <Trash2 className="size-4" />
                                                </Button>
                                            </div>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </>
    );
}
