'use client';

import { useState, useEffect, useTransition } from 'react';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { Header } from '@/components/ui/Header';
import { updateProfile, getProfile, applyGravatar } from '@/actions/profile';
import { getGravatarUrl, isGravatarUrl } from '@/lib/gravatar';
import {
  Check,
  User,
  Mail,
  Calendar,
  Shield,
  Save,
  X,
  Loader2,
  Image,
  ExternalLink,
} from 'lucide-react';
import { Avatar } from '@/components/ui/Avatar';

interface UserProfile {
  id: string;
  email: string;
  name: string | null;
  firstName: string | null;
  lastName: string | null;
  avatar: string | null;
  role: string;
  createdAt: string;
  lastLoginAt: string | null;
}

export default function ProfilePage() {
  const { data: session, update } = useSession();
  const router = useRouter();
  const [isPending, startTransition] = useTransition();
  const [profile, setProfile] = useState<UserProfile | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');

  // Form data
  const [formData, setFormData] = useState({
    name: '',
    firstName: '',
    lastName: '',
    avatar: '',
  });

  useEffect(() => {
    if (!session) {
      router.push('/login');
      return;
    }

    fetchProfile();
  }, [session, router]);

  const fetchProfile = async () => {
    try {
      const result = await getProfile();
      if (!result.success || !result.user) {
        throw new Error(result.error || 'Erreur lors du chargement du profil');
      }
      setProfile(result.user);
      setFormData({
        name: result.user.name || '',
        firstName: result.user.firstName || '',
        lastName: result.user.lastName || '',
        avatar: result.user.avatar || '',
      });
    } catch (error) {
      setError(error instanceof Error ? error.message : 'Erreur inconnue');
    } finally {
      setIsLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setSuccess('');

    startTransition(async () => {
      try {
        const result = await updateProfile(formData);

        if (!result.success || !result.user) {
          setError(result.error || 'Erreur lors de la mise à jour');
          return;
        }

        setProfile(result.user);
        setSuccess('Profil mis à jour avec succès');

        // Mettre à jour la session NextAuth
        await update({
          ...session,
          user: {
            ...session?.user,
            name:
              result.user.name ||
              `${result.user.firstName || ''} ${result.user.lastName || ''}`.trim() ||
              result.user.email,
            firstName: result.user.firstName,
            lastName: result.user.lastName,
            avatar: result.user.avatar,
          },
        });
      } catch (error) {
        setError(error instanceof Error ? error.message : 'Erreur inconnue');
      }
    });
  };

  const handleUseGravatar = async () => {
    setError('');
    setSuccess('');

    startTransition(async () => {
      try {
        const result = await applyGravatar();

        if (!result.success || !result.user) {
          setError(result.error || 'Erreur lors de la mise à jour Gravatar');
          return;
        }

        setProfile(result.user);
        setFormData((prev) => ({ ...prev, avatar: result.user!.avatar || '' }));
        setSuccess('Avatar Gravatar appliqué avec succès');

        // Mettre à jour la session NextAuth
        await update({
          ...session,
          user: {
            ...session?.user,
            name:
              result.user.name ||
              `${result.user.firstName || ''} ${result.user.lastName || ''}`.trim() ||
              result.user.email,
            firstName: result.user.firstName,
            lastName: result.user.lastName,
            avatar: result.user.avatar,
          },
        });
      } catch (error) {
        setError(error instanceof Error ? error.message : 'Erreur inconnue');
      }
    });
  };

  const handleChange = (field: string, value: string) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
  };

  if (isLoading) {
    return (
      <div className="min-h-screen bg-[var(--background)]">
        <Header title="TowerControl" subtitle="Profil utilisateur" />
        <div className="container mx-auto px-4 py-8">
          <div className="max-w-2xl mx-auto">
            <div className="text-center text-[var(--muted-foreground)]">
              Chargement du profil...
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (!profile) {
    return (
      <div className="min-h-screen bg-[var(--background)]">
        <Header title="TowerControl" subtitle="Profil utilisateur" />
        <div className="container mx-auto px-4 py-8">
          <div className="max-w-2xl mx-auto">
            <div className="text-center text-[var(--destructive)]">
              Erreur lors du chargement du profil
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-[var(--background)]">
      <Header title="TowerControl" subtitle="Profil utilisateur" />

      <div className="container mx-auto px-4 py-8">
        <div className="max-w-4xl mx-auto">
          {/* Header avec avatar et infos principales */}
          <div className="bg-gradient-to-r from-[var(--primary)]/10 to-[var(--accent)]/10 rounded-xl p-8 mb-8 border border-[var(--primary)]/20">
            <div className="flex flex-col md:flex-row items-center md:items-start gap-6">
              {/* Avatar section */}
              <div className="flex-shrink-0 relative">
                <Avatar
                  url={profile.avatar || undefined}
                  email={profile.email}
                  name={profile.name || undefined}
                  size={96}
                  className="w-24 h-24 border-4 border-[var(--primary)]/30 shadow-lg"
                />
                {profile.avatar && (
                  <div className="absolute -bottom-2 -right-2 w-8 h-8 bg-[var(--success)] rounded-full border-4 border-[var(--card)] flex items-center justify-center">
                    {isGravatarUrl(profile.avatar) ? (
                      <ExternalLink
                        className="w-4 h-4 text-white"
                        aria-label="Avatar Gravatar"
                      />
                    ) : (
                      <Image
                        className="w-4 h-4 text-white"
                        aria-label="Avatar personnalisé"
                      />
                    )}
                  </div>
                )}
              </div>

              {/* User info */}
              <div className="flex-1 text-center md:text-left">
                <h1 className="text-3xl font-mono font-bold text-[var(--foreground)] mb-2">
                  {profile.name ||
                    `${profile.firstName || ''} ${profile.lastName || ''}`.trim() ||
                    profile.email}
                </h1>
                <p className="text-[var(--muted-foreground)] text-lg mb-4">
                  {profile.email}
                </p>

                <div className="flex flex-wrap gap-4 justify-center md:justify-start">
                  <div className="flex items-center gap-2 px-3 py-1 bg-[var(--card)] rounded-full border border-[var(--border)]">
                    <div className="w-2 h-2 bg-[var(--success)] rounded-full"></div>
                    <span className="text-sm font-medium text-[var(--foreground)]">
                      {profile.role}
                    </span>
                  </div>
                  <div className="flex items-center gap-2 px-3 py-1 bg-[var(--card)] rounded-full border border-[var(--border)]">
                    <Calendar className="w-4 h-4 text-[var(--muted-foreground)]" />
                    <span className="text-sm text-[var(--muted-foreground)]">
                      Membre depuis{' '}
                      {new Date(profile.createdAt).toLocaleDateString('fr-FR')}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* Informations générales */}
            <div className="bg-[var(--card)] rounded-xl p-6 border border-[var(--border)]">
              <h2 className="text-xl font-mono font-bold text-[var(--foreground)] mb-6 flex items-center gap-2">
                <User className="w-5 h-5 text-[var(--primary)]" />
                Informations générales
              </h2>

              <div className="space-y-4">
                <div className="flex items-center gap-3 p-3 bg-[var(--input)] rounded-lg border border-[var(--border)]">
                  <Mail className="w-5 h-5 text-[var(--muted-foreground)]" />
                  <div>
                    <div className="text-[var(--foreground)] font-medium">
                      {profile.email}
                    </div>
                    <div className="text-xs text-[var(--muted-foreground)]">
                      Email principal
                    </div>
                  </div>
                </div>

                <div className="flex items-center gap-3 p-3 bg-[var(--input)] rounded-lg border border-[var(--border)]">
                  <Shield className="w-5 h-5 text-[var(--muted-foreground)]" />
                  <div>
                    <div className="text-[var(--foreground)] font-medium">
                      {profile.role}
                    </div>
                    <div className="text-xs text-[var(--muted-foreground)]">
                      Rôle utilisateur
                    </div>
                  </div>
                </div>

                {profile.lastLoginAt && (
                  <div className="flex items-center gap-3 p-3 bg-[var(--input)] rounded-lg border border-[var(--border)]">
                    <Calendar className="w-5 h-5 text-[var(--muted-foreground)]" />
                    <div>
                      <div className="text-[var(--foreground)] font-medium">
                        {new Date(profile.lastLoginAt).toLocaleString('fr-FR')}
                      </div>
                      <div className="text-xs text-[var(--muted-foreground)]">
                        Dernière connexion
                      </div>
                    </div>
                  </div>
                )}
              </div>
            </div>

            {/* Formulaire de modification */}
            <div className="bg-[var(--card)] rounded-xl p-6 border border-[var(--border)]">
              <h2 className="text-xl font-mono font-bold text-[var(--foreground)] mb-6 flex items-center gap-2">
                <User className="w-5 h-5 text-[var(--primary)]" />
                Modifier le profil
              </h2>

              <form onSubmit={handleSubmit} className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <label
                      htmlFor="firstName"
                      className="block text-sm font-medium text-[var(--foreground)] mb-2"
                    >
                      Prénom
                    </label>
                    <Input
                      id="firstName"
                      value={formData.firstName}
                      onChange={(e) =>
                        handleChange('firstName', e.target.value)
                      }
                      placeholder="Votre prénom"
                    />
                  </div>

                  <div>
                    <label
                      htmlFor="lastName"
                      className="block text-sm font-medium text-[var(--foreground)] mb-2"
                    >
                      Nom de famille
                    </label>
                    <Input
                      id="lastName"
                      value={formData.lastName}
                      onChange={(e) => handleChange('lastName', e.target.value)}
                      placeholder="Votre nom de famille"
                    />
                  </div>
                </div>

                <div>
                  <label
                    htmlFor="name"
                    className="block text-sm font-medium text-[var(--foreground)] mb-2"
                  >
                    Nom d&apos;affichage (optionnel)
                  </label>
                  <Input
                    id="name"
                    value={formData.name}
                    onChange={(e) => handleChange('name', e.target.value)}
                    placeholder="Nom d'affichage personnalisé"
                  />
                  <p className="text-xs text-[var(--muted-foreground)] mt-1">
                    Si vide, sera généré automatiquement à partir du prénom et
                    nom
                  </p>
                </div>

                <div>
                  <label
                    htmlFor="avatar"
                    className="block text-sm font-medium text-[var(--foreground)] mb-2"
                  >
                    Avatar
                  </label>

                  {/* Option Gravatar */}
                  <div className="space-y-3">
                    <div className="flex items-center gap-3 p-3 bg-[var(--input)] rounded-lg border border-[var(--border)]">
                      <div className="flex-shrink-0">
                        {profile.email && (
                          /* eslint-disable-next-line @next/next/no-img-element */
                          <img
                            src={getGravatarUrl(profile.email, { size: 40 })}
                            alt="Aperçu Gravatar"
                            className="w-10 h-10 rounded-full object-cover"
                          />
                        )}
                      </div>
                      <div className="flex-1">
                        <div className="text-sm font-medium text-[var(--foreground)]">
                          Gravatar
                        </div>
                        <div className="text-xs text-[var(--muted-foreground)]">
                          Utilise l&apos;avatar lié à votre email
                        </div>
                      </div>
                      <Button
                        type="button"
                        variant={
                          isGravatarUrl(formData.avatar) ? 'primary' : 'ghost'
                        }
                        size="sm"
                        onClick={handleUseGravatar}
                        disabled={isPending}
                        className="text-xs"
                      >
                        {isGravatarUrl(formData.avatar) ? 'Actuel' : 'Utiliser'}
                      </Button>
                    </div>

                    {/* Option URL custom */}
                    <div className="space-y-2">
                      <div className="flex items-center gap-2">
                        <Image
                          className="w-4 h-4 text-[var(--muted-foreground)]"
                          aria-label="URL personnalisée"
                        />
                        <span className="text-sm font-medium text-[var(--foreground)]">
                          URL personnalisée
                        </span>
                      </div>
                      <Input
                        id="avatar"
                        value={formData.avatar}
                        onChange={(e) => handleChange('avatar', e.target.value)}
                        placeholder="https://example.com/avatar.jpg"
                        className={
                          isGravatarUrl(formData.avatar) ? 'opacity-50' : ''
                        }
                      />
                      <p className="text-xs text-[var(--muted-foreground)]">
                        Entrez une URL d&apos;image sécurisée (HTTPS uniquement)
                      </p>
                      {formData.avatar && !isGravatarUrl(formData.avatar) && (
                        <div className="flex items-center gap-2">
                          <span className="text-xs text-[var(--muted-foreground)]">
                            Aperçu:
                          </span>
                          {/* eslint-disable-next-line @next/next/no-img-element */}
                          <img
                            src={formData.avatar}
                            alt="Aperçu avatar personnalisé"
                            className="w-8 h-8 rounded-full object-cover border border-[var(--border)]"
                            onError={(e) => {
                              e.currentTarget.style.display = 'none';
                            }}
                          />
                        </div>
                      )}
                    </div>

                    {/* Reset button */}
                    {formData.avatar && !isGravatarUrl(formData.avatar) && (
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        onClick={() => handleChange('avatar', '')}
                        className="text-xs text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
                      >
                        <X className="w-3 h-3 mr-1" />
                        Supprimer l&apos;avatar custom
                      </Button>
                    )}
                  </div>
                </div>

                {error && (
                  <div className="flex items-center gap-2 p-3 bg-[var(--destructive)]/10 border border-[var(--destructive)]/30 rounded-lg">
                    <X className="w-5 h-5 text-[var(--destructive)]" />
                    <span className="text-[var(--destructive)] text-sm">
                      {error}
                    </span>
                  </div>
                )}

                {success && (
                  <div className="flex items-center gap-2 p-3 bg-[var(--success)]/10 border border-[var(--success)]/30 rounded-lg">
                    <Check className="w-5 h-5 text-[var(--success)]" />
                    <span className="text-[var(--success)] text-sm">
                      {success}
                    </span>
                  </div>
                )}

                <div className="pt-4">
                  <Button
                    type="submit"
                    disabled={isPending}
                    className="w-full bg-[var(--primary)] hover:bg-[var(--primary)]/90 text-[var(--primary-foreground)]"
                  >
                    {isPending ? (
                      <div className="flex items-center gap-2">
                        <Loader2 className="w-4 h-4 animate-spin" />
                        Sauvegarde...
                      </div>
                    ) : (
                      <div className="flex items-center gap-2">
                        <Save className="w-4 h-4" />
                        Sauvegarder les modifications
                      </div>
                    )}
                  </Button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
