import React, { useState, useEffect, useRef } from 'react';
import { Camera, Save, Mail, User as UserIcon, Building, Shield, Loader2, CheckCircle2 } from 'lucide-react';
import { getUserById, getTenants, updateUser, uploadAvatar } from '../services/dataService';
import { User, Tenant } from '../types';

export const UserProfile: React.FC = () => {
  const [user, setUser] = useState<User | null>(null);
  const [tenant, setTenant] = useState<Tenant | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [isSuccess, setIsSuccess] = useState(false);
  const [isUploading, setIsUploading] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  
  const [name, setName] = useState('');
  const [bio, setBio] = useState('');
  
  useEffect(() => {
    const fetchUserAndTenant = async () => {
      const storedUserId = localStorage.getItem('ctms_user_id');
      if (storedUserId) {
        try {
          const fetchedUser = await getUserById(storedUserId);
          if (fetchedUser) {
            setUser(fetchedUser);
            setName(fetchedUser.name);
            setBio(fetchedUser.bio || '');

            // Fetch tenant info
            const tenants = await getTenants();
            const userTenant = tenants.find(t => t.id === fetchedUser.tenant_id);
            if (userTenant) {
              setTenant(userTenant);
            }
          }
        } catch (err) {
          console.error("Error fetching profile data:", err);
        }
      }
    };
    fetchUserAndTenant();
  }, []);

  const handleAvatarClick = () => {
    fileInputRef.current?.click();
  };

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file || !user) return;

    if (file.size > 2 * 1024 * 1024) {
      alert('Arquivo muito grande. Máximo de 2MB.');
      return;
    }

    setIsUploading(true);
    try {
      const newUrl = await uploadAvatar(user.id, file);
      if (newUrl) {
        setUser({ ...user, avatar_url: newUrl });
        window.location.reload();
      } else {
        alert('Erro ao fazer upload da imagem.');
      }
    } catch (err) {
      console.error(err);
      alert('Erro ao conectar ao servidor.');
    } finally {
      setIsUploading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!user) return;

    setIsLoading(true);
    setIsSuccess(false);

    try {
      const success = await updateUser(user.id, { name, bio });
      if (success) {
        setIsSuccess(true);
        setUser({ ...user, name, bio });
        setTimeout(() => setIsSuccess(false), 3000);
      } else {
        alert('Erro ao salvar alterações no servidor.');
      }
    } catch (err) {
      console.error("Submit failed:", err);
      alert('Erro ao conectar ao servidor.');
    } finally {
      setIsLoading(false);
    }
  };

  if (!user) return <div className="p-8 text-center text-zinc-500 dark:text-zinc-400 transition-colors">Carregando perfil...</div>;

  const backendUrl = import.meta.env.PROD ? '' : 'http://localhost:3001';
  const displayAvatar = user.avatar_url 
    ? (user.avatar_url.startsWith('http') ? user.avatar_url : `${backendUrl}${user.avatar_url}`)
    : `https://ui-avatars.com/api/?name=${encodeURIComponent(user.name)}&background=random`;

  return (
    <div className="max-w-4xl mx-auto space-y-6 pb-12 transition-colors duration-300">
      <div>
        <h1 className="text-2xl font-bold text-zinc-900 dark:text-zinc-50 tracking-tight">Meu Perfil</h1>
        <p className="text-zinc-500 dark:text-zinc-400 text-sm">Gerencie suas informações pessoais e preferências.</p>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
        {/* Left Column: Avatar & Basic Info */}
        <div className="md:col-span-1 space-y-6">
          <div className="bg-white dark:bg-zinc-900 p-6 rounded-2xl shadow-sm border border-zinc-200 dark:border-zinc-800 flex flex-col items-center text-center">
            <input 
              type="file" 
              ref={fileInputRef} 
              onChange={handleFileChange} 
              accept="image/jpeg,image/png,image/webp"
              className="hidden" 
            />
            <div className="relative group cursor-pointer" onClick={handleAvatarClick}>
              <div className="w-32 h-32 rounded-full overflow-hidden border-4 border-zinc-50 dark:border-zinc-800 shadow-sm bg-zinc-100 dark:bg-zinc-800 flex items-center justify-center">
                {isUploading ? (
                  <Loader2 className="animate-spin text-zinc-400 dark:text-zinc-500" size={32} />
                ) : (
                  <img src={displayAvatar} alt={user.name} className="w-full h-full object-cover" />
                )}
              </div>
              <div className="absolute inset-0 bg-black/40 rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-200">
                <Camera className="text-white" size={28} />
              </div>
              <button className="absolute bottom-0 right-2 bg-white dark:bg-zinc-800 text-zinc-600 dark:text-zinc-400 p-2 rounded-full shadow-md border border-zinc-100 dark:border-zinc-700 hover:text-yellow-500 dark:hover:text-yellow-400 transition-colors">
                 <Camera size={16} />
              </button>
            </div>
            
            <h2 className="mt-4 text-lg font-bold text-zinc-900 dark:text-zinc-100">{user.name}</h2>
            <p className="text-zinc-500 dark:text-zinc-400 text-sm">{user.email}</p>
            
            <div className="mt-4 flex flex-wrap justify-center gap-2">
              <span className="px-3 py-1 bg-purple-100 text-purple-700 rounded-full text-xs font-semibold capitalize border border-purple-200 dark:bg-purple-900/30 dark:text-purple-400 dark:border-purple-800">
                {user.role === 'admin' ? 'Admin' : user.role === 'manager' ? 'Gerente' : user.role === 'super_admin' ? 'Super Admin' : 'Agente'}
              </span>
              {user.team_id && (
                <span className="px-3 py-1 bg-blue-100 text-blue-700 rounded-full text-xs font-semibold border border-blue-200 dark:bg-blue-900/30 dark:text-blue-400 dark:border-blue-800">
                  {tenant?.name ? `Time ${tenant.name}` : user.team_id}
                </span>
              )}
            </div>
          </div>

          <div className="bg-zinc-100 dark:bg-zinc-900 rounded-xl p-4 border border-zinc-200 dark:border-zinc-800">
            <h3 className="text-xs font-bold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider mb-3">Status da Conta</h3>
            <div className="flex items-center gap-3 text-sm text-zinc-600 dark:text-zinc-300 mb-2">
              <div className={`w-2 h-2 rounded-full ${user.status === 'active' ? 'bg-green-500' : 'bg-zinc-400'}`}></div>
              {user.status === 'active' ? 'Ativo' : 'Inativo'}
            </div>
            <div className="flex items-center gap-3 text-sm text-zinc-600 dark:text-zinc-300">
              <Building size={14} />
              {tenant?.name || 'Organização'}
            </div>
          </div>
        </div>

        {/* Right Column: Edit Form */}
        <div className="md:col-span-2">
          <div className="bg-white dark:bg-zinc-900 rounded-2xl shadow-sm border border-zinc-200 dark:border-zinc-800 overflow-hidden">
            <div className="px-6 py-4 border-b border-zinc-100 dark:border-zinc-800 bg-zinc-50/50 dark:bg-zinc-900/50 flex justify-between items-center">
              <h3 className="font-bold text-zinc-800 dark:text-zinc-100">Informações Pessoais</h3>
              {isSuccess && (
                <span className="flex items-center gap-1.5 text-green-600 dark:text-green-400 text-sm font-medium animate-in fade-in slide-in-from-right-4">
                  <CheckCircle2 size={16} /> Salvo com sucesso
                </span>
              )}
            </div>
            
            <form onSubmit={handleSubmit} className="p-6 space-y-6">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="space-y-2">
                  <label htmlFor="fullName" className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">
                    Nome Completo
                  </label>
                  <div className="relative">
                    <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                      <UserIcon className="h-5 w-5 text-zinc-400 dark:text-zinc-500" />
                    </div>
                    <input
                      type="text"
                      id="fullName"
                      value={name}
                      onChange={(e) => setName(e.target.value)}
                      className="block w-full pl-10 pr-3 py-2 border border-zinc-200 dark:border-zinc-800 rounded-lg bg-white dark:bg-zinc-950 text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 dark:placeholder-zinc-600 focus:outline-none focus:ring-2 focus:ring-yellow-400/20 focus:border-yellow-400 transition-all sm:text-sm"
                    />
                  </div>
                </div>

                <div className="space-y-2">
                  <label htmlFor="email" className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">
                    Endereço de E-mail
                  </label>
                  <div className="relative">
                    <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                      <Mail className="h-5 w-5 text-zinc-400 dark:text-zinc-500" />
                    </div>
                    <input
                      type="email"
                      id="email"
                      value={user.email}
                      disabled
                      className="block w-full pl-10 pr-3 py-2 border border-zinc-200 dark:border-zinc-800 rounded-lg bg-zinc-50 dark:bg-zinc-900/50 text-zinc-500 dark:text-zinc-500 cursor-not-allowed sm:text-sm"
                    />
                  </div>
                  <p className="text-xs text-zinc-400 dark:text-zinc-500 mt-1">Contate o admin para alterar o e-mail.</p>
                </div>
              </div>

              <div className="space-y-2">
                <label htmlFor="role" className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">
                  Função e Permissões
                </label>
                <div className="relative">
                  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <Shield className="h-5 w-5 text-zinc-400 dark:text-zinc-500" />
                  </div>
                  <input
                    type="text"
                    id="role"
                    value={user.role === 'admin' ? 'Administrador' : user.role === 'manager' ? 'Gerente' : user.role === 'super_admin' ? 'Super Admin' : 'Agente'}
                    disabled
                    className="block w-full pl-10 pr-3 py-2 border border-zinc-200 dark:border-zinc-800 rounded-lg bg-zinc-50 dark:bg-zinc-900/50 text-zinc-500 dark:text-zinc-500 cursor-not-allowed sm:text-sm"
                  />
                </div>
              </div>

              <div className="space-y-2">
                <label htmlFor="bio" className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">
                  Bio / Descrição
                </label>
                <textarea
                  id="bio"
                  rows={4}
                  value={bio}
                  onChange={(e) => setBio(e.target.value)}
                  className="block w-full p-3 border border-zinc-200 dark:border-zinc-800 rounded-lg bg-white dark:bg-zinc-950 text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 dark:placeholder-zinc-600 focus:outline-none focus:ring-2 focus:ring-yellow-400/20 focus:border-yellow-400 transition-all sm:text-sm resize-none"
                  placeholder="Escreva uma breve descrição sobre você..."
                />
                <p className="text-xs text-zinc-400 dark:text-zinc-500 text-right">{bio.length}/500 caracteres</p>
              </div>

              <div className="pt-4 flex items-center justify-end border-t border-zinc-100 dark:border-zinc-800 mt-6 transition-colors">
                <button
                  type="button"
                  onClick={() => {
                    setName(user.name);
                    setBio(user.bio || '');
                  }}
                  className="mr-3 px-4 py-2 text-sm font-medium text-zinc-600 dark:text-zinc-400 hover:text-zinc-800 dark:hover:text-zinc-200 hover:bg-zinc-50 dark:hover:bg-zinc-800 rounded-lg transition-colors"
                >
                  Desfazer Alterações
                </button>
                <button
                  type="submit"
                  disabled={isLoading}
                  className="flex items-center gap-2 bg-zinc-900 dark:bg-yellow-400 text-white dark:text-zinc-950 px-6 py-2 rounded-lg text-sm font-medium hover:bg-zinc-800 dark:hover:opacity-90 focus:ring-2 focus:ring-offset-2 focus:ring-zinc-900 dark:focus:ring-yellow-400 transition-all disabled:opacity-70 disabled:cursor-not-allowed"
                >
                  {isLoading ? (
                    <>
                      <Loader2 className="animate-spin h-4 w-4" /> Salvando...
                    </>
                  ) : (
                    <>
                      <Save size={16} /> Salvar Alterações
                    </>
                  )}
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  );
};
