'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { Card, Button, Input, Textarea, Switch } from '@zen/core/shared/components';
import { useToast } from '@zen/core/toast';
import { getPermissionGroups } from '@zen/core/users/constants';

const PERMISSION_GROUPS = getPermissionGroups();

const isNewRole = (roleId) => roleId === 'new';

const RoleEditPage = ({ roleId }) => {
  const router = useRouter();
  const toast = useToast();

  const [loading, setLoading] = useState(!isNewRole(roleId));
  const [saving, setSaving] = useState(false);
  const [isSystem, setIsSystem] = useState(false);

  const [name, setName] = useState('');
  const [description, setDescription] = useState('');
  const [color, setColor] = useState('#6b7280');
  const [selectedPerms, setSelectedPerms] = useState([]);

  useEffect(() => {
    if (isNewRole(roleId)) return;

    const fetchRole = async () => {
      try {
        const response = await fetch(`/zen/api/roles/${roleId}`, { credentials: 'include' });
        if (!response.ok) {
          toast.error('Rôle introuvable');
          router.push('/admin/roles');
          return;
        }
        const data = await response.json();
        const role = data.role;
        setName(role.name || '');
        setDescription(role.description || '');
        setColor(role.color || '#6b7280');
        setSelectedPerms(role.permission_keys || []);
        setIsSystem(role.is_system || false);
      } catch {
        toast.error('Impossible de charger ce rôle');
        router.push('/admin/roles');
      } finally {
        setLoading(false);
      }
    };

    fetchRole();
  }, [roleId]);

  const togglePerm = (key) => {
    setSelectedPerms(prev =>
      prev.includes(key) ? prev.filter(k => k !== key) : [...prev, key]
    );
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!name.trim()) {
      toast.error('Le nom du rôle est requis');
      return;
    }

    setSaving(true);
    try {
      const isCreating = isNewRole(roleId);
      const url = isCreating ? '/zen/api/roles' : `/zen/api/roles/${roleId}`;
      const method = isCreating ? 'POST' : 'PUT';

      const body = {
        name: name.trim(),
        description: description.trim() || null,
        color,
        permissionKeys: selectedPerms,
      };

      const response = await fetch(url, {
        method,
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body)
      });

      const data = await response.json();
      if (!response.ok) {
        toast.error(data.message || 'Impossible de sauvegarder ce rôle');
        return;
      }

      toast.success(isCreating ? 'Rôle créé' : 'Rôle mis à jour');
      router.push('/admin/roles');
    } catch {
      toast.error('Impossible de sauvegarder ce rôle');
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="flex flex-col gap-6">
        <div className="h-6 w-48 bg-neutral-200 dark:bg-neutral-700 rounded animate-pulse" />
        <Card variant="default" padding="md">
          <div className="h-40 bg-neutral-100 dark:bg-neutral-800 rounded animate-pulse" />
        </Card>
      </div>
    );
  }

  const title = isNewRole(roleId) ? 'Nouveau rôle' : `Modifier "${name}"`;

  return (
    <div className="flex flex-col gap-4 sm:gap-6 lg:gap-8">
      <div className="flex items-center gap-3">
        <Button variant="secondary" size="sm" onClick={() => router.push('/admin/roles')}>
          ← Retour
        </Button>
        <div>
          <h1 className="text-lg sm:text-xl font-semibold text-neutral-900 dark:text-white">{title}</h1>
          {isSystem && (
            <p className="mt-1 text-xs text-neutral-400">Rôle système — le nom ne peut pas être modifié</p>
          )}
        </div>
      </div>

      <form onSubmit={handleSubmit} className="flex flex-col gap-6">
        <Card variant="default" padding="md">
          <div className="flex flex-col gap-4">
            <h2 className="text-sm font-semibold text-neutral-900 dark:text-white">Informations</h2>

            <Input
              label="Nom du rôle"
              value={name}
              onChange={setName}
              disabled={isSystem}
              placeholder="Éditeur, Modérateur..."
              required
            />

            <Textarea
              label="Description"
              value={description}
              onChange={setDescription}
              rows={2}
              placeholder="Description optionnelle..."
            />

            <div className="flex items-center gap-3">
              <label className="text-xs font-medium text-neutral-700 dark:text-neutral-300">
                Couleur
              </label>
              <input
                type="color"
                value={color}
                onChange={(e) => setColor(e.target.value)}
                className="w-8 h-8 rounded cursor-pointer border border-neutral-200 dark:border-neutral-700"
              />
              <span className="text-xs text-neutral-500">{color}</span>
            </div>
          </div>
        </Card>

        <Card variant="default" padding="md">
          <div className="flex flex-col gap-4">
            <h2 className="text-sm font-semibold text-neutral-900 dark:text-white">Permissions</h2>

            {Object.entries(PERMISSION_GROUPS).map(([group, perms]) => (
              <div key={group} className="flex flex-col">
                <p className="text-xs font-semibold text-neutral-500 dark:text-neutral-400 uppercase tracking-wide py-1">
                  {group}
                </p>
                <div className="flex flex-col divide-y divide-neutral-100 dark:divide-neutral-700/50">
                  {perms.map((perm) => (
                    <Switch
                      key={perm.key}
                      checked={selectedPerms.includes(perm.key)}
                      onChange={() => togglePerm(perm.key)}
                      label={perm.name}
                      description={perm.key}
                    />
                  ))}
                </div>
              </div>
            ))}
          </div>
        </Card>

        <div className="flex justify-end gap-3">
          <Button variant="secondary" type="button" onClick={() => router.push('/admin/roles')}>
            Annuler
          </Button>
          <Button variant="primary" type="submit" loading={saving} disabled={saving}>
            {saving ? 'Sauvegarde...' : 'Sauvegarder'}
          </Button>
        </div>
      </form>
    </div>
  );
};

export default RoleEditPage;
