'use client';

/**
 * Reusable "Edit account" section: display name, email (read-only), avatar upload/remove.
 * Use on a protected dashboard page. Requires session cookie (user must be logged in).
 *
 * @param {Object} props
 * @param {Object} [props.initialUser] - Initial user from server (e.g. getSession().user). If omitted, fetches from API.
 * @param {function} [props.onUpdate] - Called after profile or avatar update with the new user object (e.g. to refresh layout)
 */

import React, { useState, useEffect, useRef } from 'react';
import { Card, Input, Button } from '@zen/core/shared/components';
import { useToast } from '@zen/core/toast';
import { useCurrentUser } from './useCurrentUser.js';
import UserAvatar from './UserAvatar.js';

const API_BASE = '/zen/api';

function getImageUrl(imageKey) {
  if (!imageKey) return null;
  return `/zen/api/storage/${imageKey}`;
}

export default function AccountSection({ initialUser, onUpdate }) {
  const toast = useToast();
  const { user: fetchedUser, loading: fetchLoading, refetch } = useCurrentUser();

  const user = initialUser ?? fetchedUser;
  const [formData, setFormData] = useState({ name: user?.name ?? '' });
  const [saving, setSaving] = useState(false);
  const [uploadingImage, setUploadingImage] = useState(false);
  const [imagePreview, setImagePreview] = useState(null);
  const fileInputRef = useRef(null);

  useEffect(() => {
    if (user) {
      setFormData((prev) => ({ ...prev, name: user.name ?? '' }));
      setImagePreview(user.image ? getImageUrl(user.image) : null);
    }
  }, [user]);

  const handleNameChange = (value) => {
    setFormData((prev) => ({ ...prev, name: value }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!formData.name?.trim()) {
      toast.error('Le nom est requis');
      return;
    }
    setSaving(true);
    try {
      const res = await fetch(`${API_BASE}/users/profile`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ name: formData.name.trim() }),
      });
      const data = await res.json();
      if (!res.ok || !data.success) {
        throw new Error(data.message || data.error || 'Échec de la mise à jour du profil');
      }
      toast.success('Profil mis à jour avec succès');
      onUpdate?.(data.user);
      refetch();
    } catch (err) {
      toast.error(err.message || 'Échec de la mise à jour du profil');
    } finally {
      setSaving(false);
    }
  };

  const handleReset = () => {
    setFormData({ name: user?.name ?? '' });
  };

  const handleImageSelect = async (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    if (!file.type.startsWith('image/')) {
      toast.error('Veuillez sélectionner un fichier image');
      return;
    }
    if (file.size > 5 * 1024 * 1024) {
      toast.error("L'image doit faire moins de 5MB");
      return;
    }
    const reader = new FileReader();
    reader.onloadend = () => setImagePreview(reader.result);
    reader.readAsDataURL(file);

    setUploadingImage(true);
    try {
      const fd = new FormData();
      fd.append('file', file);
      const res = await fetch(`${API_BASE}/users/profile/picture`, {
        method: 'POST',
        credentials: 'include',
        body: fd,
      });
      const data = await res.json();
      if (!res.ok || !data.success) {
        throw new Error(data.message || data.error || 'Upload failed');
      }
      setImagePreview(getImageUrl(data.user?.image));
      toast.success('Photo de profil mise à jour avec succès');
      onUpdate?.(data.user);
      refetch();
    } catch (err) {
      toast.error(err.message || 'Upload failed');
      setImagePreview(user?.image ? getImageUrl(user.image) : null);
    } finally {
      setUploadingImage(false);
    }
  };

  const handleRemoveImage = async () => {
    if (!user?.image) return;
    setUploadingImage(true);
    try {
      const res = await fetch(`${API_BASE}/users/profile/picture`, {
        method: 'DELETE',
        credentials: 'include',
      });
      const data = await res.json();
      if (!res.ok || !data.success) {
        throw new Error(data.message || data.error || 'Remove failed');
      }
      setImagePreview(null);
      toast.success('Photo de profil supprimée avec succès');
      onUpdate?.(data.user);
      refetch();
    } catch (err) {
      toast.error(err.message || 'Remove failed');
    } finally {
      setUploadingImage(false);
    }
  };

  const created_at = user?.created_at ?? user?.createdAt;
  const hasChanges = formData.name?.trim() !== (user?.name ?? '');

  if (fetchLoading && !initialUser) {
    return (
      <Card variant="lightDark">
        <div className="animate-pulse space-y-4">
          <div className="h-24 rounded-xl bg-neutral-200 dark:bg-neutral-700" />
          <div className="h-32 rounded-xl bg-neutral-200 dark:bg-neutral-700" />
        </div>
      </Card>
    );
  }

  if (!user) {
    return null;
  }

  return (
    <div className="space-y-6">
      <Card variant="lightDark">
        <div className="space-y-4">
          <h2 className="text-lg font-semibold text-neutral-900 dark:text-white">
            Photo de profil
          </h2>
          <div className="flex flex-wrap items-center gap-6">
            <div className="relative">
              {imagePreview ? (
                <img
                  src={imagePreview}
                  alt="Profile"
                  className="w-24 h-24 rounded-full object-cover border-2 border-neutral-200 dark:border-neutral-700"
                />
              ) : (
                <UserAvatar user={user} size="lg" className="w-24 h-24" />
              )}
              {uploadingImage && (
                <div className="absolute inset-0 rounded-full bg-black/50 flex items-center justify-center">
                  <div className="w-8 h-8 border-2 border-white border-t-transparent rounded-full animate-spin" />
                </div>
              )}
            </div>
            <div className="flex flex-col gap-2">
              <p className="text-sm text-neutral-500 dark:text-neutral-400">
                Téléchargez une nouvelle photo de profil. Taille max 5MB.
              </p>
              <div className="flex gap-2">
                <input
                  ref={fileInputRef}
                  type="file"
                  accept="image/*"
                  onChange={handleImageSelect}
                  className="hidden"
                />
                <Button
                  type="button"
                  variant="secondary"
                  onClick={() => fileInputRef.current?.click()}
                  disabled={uploadingImage}
                >
                  {uploadingImage ? 'Téléchargement...' : 'Télécharger une image'}
                </Button>
                {imagePreview && (
                  <Button
                    type="button"
                    variant="secondary"
                    onClick={handleRemoveImage}
                    disabled={uploadingImage}
                  >
                    Supprimer
                  </Button>
                )}
              </div>
            </div>
          </div>
        </div>
      </Card>

      <Card variant="lightDark">
        <form onSubmit={handleSubmit} className="space-y-6">
          <h2 className="text-lg font-semibold text-neutral-900 dark:text-white">
            Informations personnelles
          </h2>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <Input
              label="Nom complet"
              type="text"
              value={formData.name}
              onChange={handleNameChange}
              placeholder="Entrez votre nom complet"
              required
              disabled={saving}
            />
            <Input
              label="Courriel"
              type="email"
              value={user.email ?? ''}
              disabled
              readOnly
              description="L'email ne peut pas être modifié"
            />
          </div>
          {created_at && (
            <Input
              label="Compte créé"
              type="text"
              value={new Date(created_at).toLocaleDateString('fr-FR', {
                year: 'numeric',
                month: 'long',
                day: 'numeric',
              })}
              disabled
              readOnly
            />
          )}
          <div className="flex justify-end gap-3 pt-4 border-t border-neutral-200 dark:border-neutral-700">
            <Button
              type="button"
              variant="secondary"
              onClick={handleReset}
              disabled={saving || !hasChanges}
            >
              Réinitialiser
            </Button>
            <Button
              type="submit"
              variant="primary"
              disabled={saving || !hasChanges}
              loading={saving}
            >
              {saving ? 'Enregistrement...' : 'Enregistrer les modifications'}
            </Button>
          </div>
        </form>
      </Card>
    </div>
  );
}
