import { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { getProfileByUsername, UserProfile } from '../services/profileService';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { UserAvatar as Avatar } from '@/components/ui/avatar';
import { LoadingSpinner } from '@/components/ui/loading-spinner';
import { Alert } from '@/components/ui/alert';
import { UserRolesSection } from '@/features/roles/components/UserRolesSection';
import { useAuthStore } from '@/stores/auth';

export function UserProfilePage() {
  const { username } = useParams<{ username: string }>();
  const [profile, setProfile] = useState<UserProfile | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const { user } = useAuthStore();
  
  // Déterminer si l'utilisateur actuel est admin
  const isAdmin = user?.role === 'admin' || user?.role === 'super_admin';
  
  useEffect(() => {
    if (!username) {
      setError('Username is required');
      setLoading(false);
      return;
    }
    
    getProfileByUsername(username)
      .then((data) => {
        setProfile(data);
      })
      .catch((err) => {
        setError(err.response?.data?.error || err.message || 'Failed to load profile');
      })
      .finally(() => setLoading(false));
  }, [username]);
  
  if (loading) {
    return (
      <div className="container mx-auto py-8">
        <LoadingSpinner text="Loading profile..." />
      </div>
    );
  }

  if (error) {
    return (
      <div className="container mx-auto py-8">
        <Alert variant="destructive">
          <p>Error: {error}</p>
        </Alert>
      </div>
    );
  }

  if (!profile) {
    return (
      <div className="container mx-auto py-8">
        <Alert>
          <p>User not found</p>
        </Alert>
      </div>
    );
  }
  
  return (
    <div className="container mx-auto py-8">
      <Card>
        <CardHeader>
          <div className="flex items-center space-x-4">
            <Avatar
              src={profile.avatar_url}
              alt={profile.username}
              name={profile.first_name && profile.last_name ? `${profile.first_name} ${profile.last_name}` : profile.username}
              size="xl"
              className="h-24 w-24"
            />
            <div>
              <CardTitle className="text-3xl">{profile.username}</CardTitle>
              {profile.first_name && profile.last_name && (
                <p className="text-muted-foreground mt-1">
                  {profile.first_name} {profile.last_name}
                </p>
              )}
            </div>
          </div>
        </CardHeader>
        <CardContent className="space-y-4">
          {profile.bio && (
            <div>
              <h3 className="font-semibold mb-2">Bio</h3>
              <p className="text-muted-foreground">{profile.bio}</p>
            </div>
          )}
          {profile.location && (
            <div>
              <h3 className="font-semibold mb-2">Location</h3>
              <p className="text-muted-foreground">📍 {profile.location}</p>
            </div>
          )}
          <div>
            <h3 className="font-semibold mb-2">Member Since</h3>
            <p className="text-muted-foreground">
              {new Date(profile.created_at).toLocaleDateString()}
            </p>
          </div>
          
          {profile.id && (
            <div>
              <UserRolesSection userId={profile.id} isAdmin={isAdmin} />
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}

