'use client';

import { useEffect, useState } from 'react';
import { Loader2, Plus, ShieldCheck } from 'lucide-react';
import { AdminShell } from '@/components/id/admin-shell';
import { useAuth } from '@/components/id/auth-provider';
import { useToast } from '@/components/id/toast-provider';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { AdminPermission, AdminRole, apiFetch } from '@/lib/api';

export default function AdminRbacPage() {
  const { token, user } = useAuth();
  const { showToast } = useToast();
  const [roles, setRoles] = useState<AdminRole[]>([]);
  const [permissions, setPermissions] = useState<AdminPermission[]>([]);
  const [loading, setLoading] = useState(true);
  const [creating, setCreating] = useState(false);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [form, setForm] = useState({ slug: '', name: '', description: '', permissionSlugs: [] as string[] });

  useEffect(() => {
    if (!token || !user?.canManageRoles) return;
    Promise.all([
      apiFetch<{ roles: AdminRole[] }>('/admin/rbac/roles', {}, token),
      apiFetch<{ permissions: AdminPermission[] }>('/admin/rbac/permissions', {}, token)
    ])
      .then(([rolesResponse, permissionsResponse]) => {
        setRoles(rolesResponse.roles ?? []);
        setPermissions(permissionsResponse.permissions ?? []);
      })
      .catch((error) => showToast(error instanceof Error ? error.message : 'Не удалось загрузить роли'))
      .finally(() => setLoading(false));
  }, [showToast, token, user?.canManageRoles]);

  async function handleCreateRole() {
    if (!token) return;
    setCreating(true);
    try {
      await apiFetch('/admin/rbac/roles', {
        method: 'POST',
        body: JSON.stringify(form)
      }, token);
      showToast('Роль создана');
      setDialogOpen(false);
      setForm({ slug: '', name: '', description: '', permissionSlugs: [] });
      const response = await apiFetch<{ roles: AdminRole[] }>('/admin/rbac/roles', {}, token);
      setRoles(response.roles ?? []);
    } catch (error) {
      showToast(error instanceof Error ? error.message : 'Не удалось создать роль');
    } finally {
      setCreating(false);
    }
  }

  if (!user?.canManageRoles) {
    return (
      <AdminShell active="/admin/rbac">
        <p className="text-[#667085]">Управление ролями доступно только супер-администратору.</p>
      </AdminShell>
    );
  }

  return (
    <AdminShell active="/admin/rbac">
      <div className="mb-6 flex items-center justify-between gap-4">
        <div>
          <h2 className="text-2xl font-medium">Роли и права</h2>
          <p className="text-sm text-[#667085]">Только супер-администратор может создавать роли и назначать их пользователям</p>
        </div>
        <Button onClick={() => setDialogOpen(true)}>
          <Plus className="h-4 w-4" />
          Создать роль
        </Button>
      </div>

      {loading ? (
        <div className="flex items-center justify-center gap-2 py-16 text-[#667085]">
          <Loader2 className="h-5 w-5 animate-spin" />
          Загрузка...
        </div>
      ) : (
        <div className="grid gap-4 md:grid-cols-3">
          {roles.map((role) => (
            <Card key={role.id} className="bg-[#f8f9fb] shadow-none">
              <CardHeader>
                <ShieldCheck className="h-6 w-6" />
                <CardTitle>{role.name}</CardTitle>
                <CardDescription>{role.permissions.length} прав · {role.slug}</CardDescription>
              </CardHeader>
              <CardContent className="space-y-2">
                {role.permissions.map((permission) => (
                  <div key={permission.id} className="rounded-xl bg-white px-3 py-2 text-sm">
                    <div className="font-medium">{permission.name}</div>
                    <div className="text-xs text-[#667085]">{permission.slug}</div>
                  </div>
                ))}
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Новая роль</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <Input value={form.slug} onChange={(event) => setForm((current) => ({ ...current, slug: event.target.value }))} placeholder="slug, например support" />
            <Input value={form.name} onChange={(event) => setForm((current) => ({ ...current, name: event.target.value }))} placeholder="Название роли" />
            <Input value={form.description} onChange={(event) => setForm((current) => ({ ...current, description: event.target.value }))} placeholder="Описание" />
            <div className="space-y-2">
              <p className="text-sm font-medium">Права</p>
              {permissions.map((permission) => (
                <label key={permission.id} className="flex items-center gap-2 rounded-xl bg-[#f4f5f8] px-3 py-2 text-sm">
                  <input
                    type="checkbox"
                    checked={form.permissionSlugs.includes(permission.slug)}
                    onChange={(event) =>
                      setForm((current) => ({
                        ...current,
                        permissionSlugs: event.target.checked
                          ? [...current.permissionSlugs, permission.slug]
                          : current.permissionSlugs.filter((item) => item !== permission.slug)
                      }))
                    }
                  />
                  <span>{permission.name}</span>
                </label>
              ))}
            </div>
            <Button className="w-full" disabled={creating} onClick={() => void handleCreateRole()}>
              {creating ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Создать роль'}
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </AdminShell>
  );
}
