'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { Button, Card, Input, Select, Loading, TagInput } from '@zen/core/shared/components';
import { useToast } from '@zen/core/toast';

const UserEditPage = ({ userId }) => {
  const router = useRouter();
  const toast = useToast();

  const [userData, setUserData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);

  const [formData, setFormData] = useState({
    name: '',
    email_verified: 'false',
  });
  const [errors, setErrors] = useState({});

  const [allRoles, setAllRoles] = useState([]);
  const [selectedRoleIds, setSelectedRoleIds] = useState([]);
  const [initialRoleIds, setInitialRoleIds] = useState([]);

  const emailVerifiedOptions = [
    { value: 'false', label: 'Non vérifié' },
    { value: 'true', label: 'Vérifié' }
  ];

  useEffect(() => {
    loadAll();
  }, [userId]);

  const loadAll = async () => {
    try {
      setLoading(true);
      const [userRes, rolesRes, userRolesRes] = await Promise.all([
        fetch(`/zen/api/users/${userId}`, { credentials: 'include' }),
        fetch('/zen/api/roles', { credentials: 'include' }),
        fetch(`/zen/api/users/${userId}/roles`, { credentials: 'include' }),
      ]);

      const [userData, rolesData, userRolesData] = await Promise.all([
        userRes.json(),
        rolesRes.json(),
        userRolesRes.json(),
      ]);

      if (userData.user) {
        setUserData(userData.user);
        setFormData({
          name: userData.user.name || '',
          email_verified: userData.user.email_verified ? 'true' : 'false',
        });
      } else {
        toast.error(userData.message || 'Utilisateur introuvable');
      }

      if (rolesData.roles) {
        setAllRoles(rolesData.roles);
      }

      if (userRolesData.roles) {
        const ids = userRolesData.roles.map(r => r.id);
        setSelectedRoleIds(ids);
        setInitialRoleIds(ids);
      }
    } catch {
      toast.error("Impossible de charger l'utilisateur");
    } finally {
      setLoading(false);
    }
  };

  const handleInputChange = (field, value) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    if (errors[field]) {
      setErrors(prev => ({ ...prev, [field]: null }));
    }
  };

  const validateForm = () => {
    const newErrors = {};
    if (!formData.name || !formData.name.trim()) {
      newErrors.name = 'Le nom est requis';
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!validateForm()) return;

    try {
      setSaving(true);

      const userRes = await fetch(`/zen/api/users/${userId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({
          name: formData.name.trim(),
          email_verified: formData.email_verified === 'true',
        })
      });
      const userResData = await userRes.json();
      if (!userRes.ok) {
        toast.error(userResData.message || userResData.error || "Impossible de mettre à jour l'utilisateur");
        return;
      }

      const toAdd = selectedRoleIds.filter(id => !initialRoleIds.includes(id));
      const toRemove = initialRoleIds.filter(id => !selectedRoleIds.includes(id));

      await Promise.all([
        ...toAdd.map(roleId =>
          fetch(`/zen/api/users/${userId}/roles`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            credentials: 'include',
            body: JSON.stringify({ roleId }),
          })
        ),
        ...toRemove.map(roleId =>
          fetch(`/zen/api/users/${userId}/roles/${roleId}`, {
            method: 'DELETE',
            credentials: 'include',
          })
        ),
      ]);

      toast.success('Utilisateur mis à jour avec succès');
      router.push('/admin/users');
    } catch {
      toast.error("Impossible de mettre à jour l'utilisateur");
    } finally {
      setSaving(false);
    }
  };

  const roleOptions = allRoles.map(r => ({
    value: r.id,
    label: r.name,
    color: r.color || '#6b7280',
    description: r.description || undefined,
  }));

  if (loading) {
    return (
      <div className="min-h-64 flex items-center justify-center">
        <Loading />
      </div>
    );
  }

  if (!userData) {
    return (
      <div className="flex flex-col gap-4 sm:gap-6 lg:gap-8">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-lg sm:text-xl font-semibold text-neutral-900 dark:text-white">Modifier l'utilisateur</h1>
            <p className="mt-1 text-xs text-neutral-400">Utilisateur introuvable</p>
          </div>
          <Button variant="secondary" size="sm" onClick={() => router.push('/admin/users')}>
            ← Retour aux utilisateurs
          </Button>
        </div>
        <Card>
          <div className="bg-red-500/10 border border-red-500/20 text-red-400 px-4 py-3 rounded-lg">
            <p className="font-medium">Utilisateur introuvable</p>
            <p className="text-sm mt-1">L'utilisateur que vous recherchez n'existe pas ou a été supprimé.</p>
          </div>
        </Card>
      </div>
    );
  }

  return (
    <div className="flex flex-col gap-4 sm:gap-6 lg:gap-8">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-lg sm:text-xl font-semibold text-neutral-900 dark:text-white">Modifier l'utilisateur</h1>
          <p className="mt-1 text-xs text-neutral-400">{userData.email}</p>
        </div>
        <Button variant="secondary" size="sm" onClick={() => router.push('/admin/users')}>
          ← Retour aux utilisateurs
        </Button>
      </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>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <Input
                label="Nom *"
                value={formData.name}
                onChange={(value) => handleInputChange('name', value)}
                placeholder="Nom de l'utilisateur"
                error={errors.name}
              />

              <Input
                label="Email"
                value={userData.email}
                disabled
              />

              <Select
                label="Email vérifié"
                value={formData.email_verified}
                onChange={(value) => handleInputChange('email_verified', value)}
                options={emailVerifiedOptions}
              />
            </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">Rôles</h2>

            <TagInput
              label="Rôles attribués"
              options={roleOptions}
              value={selectedRoleIds}
              onChange={setSelectedRoleIds}
              placeholder="Rechercher un rôle..."
            />
          </div>
        </Card>

        <div className="flex items-center justify-end gap-3">
          <Button type="button" variant="secondary" onClick={() => router.push('/admin/users')} disabled={saving}>
            Annuler
          </Button>
          <Button type="submit" variant="success" loading={saving} disabled={saving}>
            {saving ? 'Enregistrement...' : 'Mettre à jour'}
          </Button>
        </div>
      </form>
    </div>
  );
};

export default UserEditPage;
