import React, { useState, useEffect } from 'react';
import { Camera, Save, Mail, User as UserIcon, Building, Shield, Loader2, CheckCircle2 } from 'lucide-react';
import { getUserById, getTenants, updateUser } 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 [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 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);
        // Update local state
        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-slate-500">Carregando perfil...</div>;

  return (
    <div className="max-w-4xl mx-auto space-y-6 pb-12">
      <div>
        <h1 className="text-2xl font-bold text-slate-900 tracking-tight">Meu Perfil</h1>
        <p className="text-slate-500 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 p-6 rounded-2xl shadow-sm border border-slate-200 flex flex-col items-center text-center">
            <div className="relative group cursor-pointer">
              <div className="w-32 h-32 rounded-full overflow-hidden border-4 border-slate-50 shadow-sm">
                <img src={user.avatar_url || `https://ui-avatars.com/api/?name=${encodeURIComponent(user.name)}&background=random`} 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 text-slate-600 p-2 rounded-full shadow-md border border-slate-100 hover:text-blue-600 transition-colors">
                 <Camera size={16} />
              </button>
            </div>
            
            <h2 className="mt-4 text-lg font-bold text-slate-900">{user.name}</h2>
            <p className="text-slate-500 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">
                {user.role}
              </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">
                  {user.team_id === 'sales_1' ? 'Vendas Alpha' : user.team_id === 'sales_2' ? 'Vendas Beta' : user.team_id}
                </span>
              )}
            </div>
          </div>

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

        {/* Right Column: Edit Form */}
        <div className="md:col-span-2">
          <div className="bg-white rounded-2xl shadow-sm border border-slate-200 overflow-hidden">
            <div className="px-6 py-4 border-b border-slate-100 bg-slate-50/50 flex justify-between items-center">
              <h3 className="font-bold text-slate-800">Informações Pessoais</h3>
              {isSuccess && (
                <span className="flex items-center gap-1.5 text-green-600 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-slate-700">
                    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-slate-400" />
                    </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-slate-200 rounded-lg bg-white text-slate-900 placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-500 sm:text-sm transition-all"
                    />
                  </div>
                </div>

                <div className="space-y-2">
                  <label htmlFor="email" className="block text-sm font-medium text-slate-700">
                    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-slate-400" />
                    </div>
                    <input
                      type="email"
                      id="email"
                      value={user.email}
                      disabled
                      className="block w-full pl-10 pr-3 py-2 border border-slate-200 rounded-lg bg-slate-50 text-slate-500 cursor-not-allowed sm:text-sm"
                    />
                  </div>
                  <p className="text-xs text-slate-400 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-slate-700">
                  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-slate-400" />
                  </div>
                  <input
                    type="text"
                    id="role"
                    value={user.role.charAt(0).toUpperCase() + user.role.slice(1)}
                    disabled
                    className="block w-full pl-10 pr-3 py-2 border border-slate-200 rounded-lg bg-slate-50 text-slate-500 cursor-not-allowed sm:text-sm"
                  />
                </div>
              </div>

              <div className="space-y-2">
                <label htmlFor="bio" className="block text-sm font-medium text-slate-700">
                  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-slate-200 rounded-lg text-slate-900 placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-500 sm:text-sm transition-all resize-none"
                  placeholder="Escreva uma breve descrição sobre você..."
                />
                <p className="text-xs text-slate-400 text-right">{bio.length}/500 caracteres</p>
              </div>

              <div className="pt-4 flex items-center justify-end border-t border-slate-100 mt-6">
                <button
                  type="button"
                  onClick={() => {
                    setName(user.name);
                    setBio(user.bio || '');
                  }}
                  className="mr-3 px-4 py-2 text-sm font-medium text-slate-600 hover:text-slate-800 hover:bg-slate-50 rounded-lg transition-colors"
                >
                  Desfazer Alterações
                </button>
                <button
                  type="submit"
                  disabled={isLoading}
                  className="flex items-center gap-2 bg-slate-900 text-white px-6 py-2 rounded-lg text-sm font-medium hover:bg-slate-800 focus:ring-2 focus:ring-offset-2 focus:ring-slate-900 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>
  );
};