import { Head, router, useForm, usePage } from '@inertiajs/react';
import { Pencil, Plus, Trash2, Users } 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 UserRow = {
    id: number;
    name: string;
    email: string;
    phone: string | null;
    locale: string;
    role_id: number | null;
    role_name: string | null;
    role_slug: string | null;
};

type RoleItem = { id: number; name: string; slug: string };

export default function SystemUsers({ users, roles }: { users: UserRow[]; roles: RoleItem[] }) {
    const { locale, t } = useI18n();
    const { errors } = usePage<{ errors: Record<string, string> }>().props;
    const [editingId, setEditingId] = useState<number | null>(null);
    const form = useForm({
        name: '',
        email: '',
        phone: '',
        password: '',
        role_id: roles[0]?.id ? String(roles[0].id) : '',
        locale: 'bn',
    });

    return (
        <>
            <Head title={t('nav.users', 'Users & Roles')} />

            <div className="flex flex-col gap-6 p-4 md:p-6">
                <div>
                    <h1 className="text-2xl font-bold tracking-tight">{t('nav.users', 'Users & Roles')}</h1>
                    <p className="text-sm text-muted-foreground">
                        {locale === 'bn' ? 'মাদ্রাসার স্টাফ, শিক্ষক ও হিসাবরক্ষক যুক্ত করুন।' : 'Manage institution staff and roles.'}
                    </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">
                            <Users className="h-5 w-5 text-primary" />
                            <h2 className="font-semibold">
                                {editingId !== null
                                    ? locale === 'bn'
                                        ? 'ব্যবহারকারী সম্পাদনা'
                                        : 'Edit Staff User'
                                    : locale === 'bn'
                                      ? 'নতুন ব্যবহারকারী'
                                      : 'Add Staff User'}
                            </h2>
                        </div>
                        <form
                            onSubmit={(e) => {
                                e.preventDefault();
                                if (editingId !== null) {
                                    form.put(SystemAdminController.updateUser.url(editingId), {
                                        onSuccess: () => {
                                            setEditingId(null);
                                            form.reset('name', 'email', 'phone', 'password');
                                        },
                                    });
                                } else {
                                    form.submit(SystemAdminController.storeUser(), {
                                        onSuccess: () => form.reset('name', 'email', 'phone', 'password'),
                                    });
                                }
                            }}
                            className="space-y-3"
                        >
                            <div className="space-y-1">
                                <Label>{locale === 'bn' ? 'নাম' : 'Name'}</Label>
                                <Input value={form.data.name} onChange={(e) => form.setData('name', e.target.value)} required />
                            </div>
                            <div className="space-y-1">
                                <Label>{locale === 'bn' ? 'ইমেইল' : 'Email'}</Label>
                                <Input type="email" value={form.data.email} onChange={(e) => form.setData('email', e.target.value)} required />
                            </div>
                            <div className="space-y-1">
                                <Label>{locale === 'bn' ? 'পাসওয়ার্ড' : 'Password'}</Label>
                                <Input
                                    type="password"
                                    value={form.data.password}
                                    onChange={(e) => form.setData('password', e.target.value)}
                                    required={editingId === null}
                                    placeholder={editingId !== null ? (locale === 'bn' ? 'অপরিবর্তিত রাখতে খালি রাখুন' : 'Leave blank to keep unchanged') : undefined}
                                />
                            </div>
                            <div className="space-y-1">
                                <Label>{locale === 'bn' ? 'রোল' : 'Role'}</Label>
                                <select
                                    value={form.data.role_id}
                                    onChange={(e) => form.setData('role_id', e.target.value)}
                                    className="h-9 w-full rounded-md border border-input bg-background px-2.5 text-sm"
                                >
                                    {roles.map((r) => (
                                        <option key={r.id} value={r.id}>
                                            {r.name}
                                        </option>
                                    ))}
                                </select>
                            </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 User'
                                        : locale === 'bn'
                                          ? 'ব্যবহারকারী যোগ করুন'
                                          : 'Create User'}
                                </Button>
                                {editingId !== null && (
                                    <Button
                                        type="button"
                                        variant="outline"
                                        onClick={() => {
                                            setEditingId(null);
                                            form.reset('name', 'email', 'phone', 'password');
                                        }}
                                    >
                                        {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' ? 'নাম' : 'Name'}</th>
                                    <th className="px-4 py-2">{locale === 'bn' ? 'ইমেইল' : 'Email'}</th>
                                    <th className="px-4 py-2">{locale === 'bn' ? 'রোল' : 'Role'}</th>
                                    <th className="px-4 py-2 text-right">{locale === 'bn' ? 'অ্যাকশন' : 'Actions'}</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y">
                                {users.map((u) => (
                                    <tr key={u.id}>
                                        <td className="px-4 py-2.5 font-medium">{u.name}</td>
                                        <td className="px-4 py-2.5 text-muted-foreground">{u.email}</td>
                                        <td className="px-4 py-2.5">
                                            <span className="rounded bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary">
                                                {u.role_name ?? u.role_slug}
                                            </span>
                                        </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(u.id);
                                                        form.setData({
                                                            name: u.name,
                                                            email: u.email,
                                                            phone: u.phone ?? '',
                                                            password: '',
                                                            role_id: u.role_id ? String(u.role_id) : roles[0]?.id ? String(roles[0].id) : '',
                                                            locale: u.locale,
                                                        });
                                                    }}
                                                >
                                                    <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' ? 'আপনি কি নিশ্চিতভাবে এটি মুছে ফেলতে চান?' : 'Remove this user?')) {
                                                            router.delete(SystemAdminController.destroyUser.url(u.id));
                                                        }
                                                    }}
                                                >
                                                    <Trash2 className="size-4" />
                                                </Button>
                                            </div>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </>
    );
}
