import { useState, useEffect } from "react";
import { Save, ArrowLeft } from "lucide-react";
import toast from "react-hot-toast";
import { useNavigate } from "react-router-dom";
import { useAuth } from "../hooks/useAuth";
import { patientService, avatarService } from "../services";
import { AvatarUpload } from "../components/ui/AvatarUpload";

export default function PerfilPaciente() {
  const { user } = useAuth();
  const navigate = useNavigate();
  const [isEditing, setIsEditing] = useState(false);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<
    "personal" | "medical" | "security"
  >("personal");
  const [avatarUrl, setAvatarUrl] = useState<string | undefined>(undefined);

  const [formData, setFormData] = useState({
    full_name: "",
    email: "",
    phone_mobile: "",
    cpf: "",
    birth_date: "",
    sex: "",
    street: "",
    number: "",
    complement: "",
    neighborhood: "",
    city: "",
    state: "",
    cep: "",
    blood_type: "",
    weight_kg: "",
    height_m: "",
  });

  const [passwordData, setPasswordData] = useState({
    currentPassword: "",
    newPassword: "",
    confirmPassword: "",
  });

  useEffect(() => {
    if (user?.id) {
      loadPatientData();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [user?.id]);

  const loadPatientData = async () => {
    if (!user?.id) {
      console.error("[PerfilPaciente] Sem user.id:", user);
      toast.error("Usuário não identificado");
      return;
    }

    try {
      setLoading(true);
      console.log("[PerfilPaciente] 🔍 USER ID:", {
        userId: user.id,
        userName: user.nome,
        userEmail: user.email,
        userRole: user.role,
      });

      try {
        // Buscar paciente por user_id (ID do auth) em vez de id
        const patient = await patientService.getByUserId(user.id);
        console.log("[PerfilPaciente] Dados carregados:", patient);
        setFormData({
          full_name: patient.full_name || "",
          email: patient.email || "",
          phone_mobile: patient.phone_mobile || "",
          cpf: patient.cpf || "",
          birth_date: patient.birth_date || "",
          sex: patient.sex || "",
          street: patient.street || "",
          number: patient.number || "",
          complement: patient.complement || "",
          neighborhood: patient.neighborhood || "",
          city: patient.city || "",
          state: patient.state || "",
          cep: patient.cep || "",
          blood_type: patient.blood_type || "",
          weight_kg: patient.weight_kg?.toString() || "",
          height_m: patient.height_m?.toString() || "",
        });

        // Carrega avatar_url do paciente ou gera URL do Supabase Storage
        if (patient.avatar_url) {
          console.log(
            "[PerfilPaciente] Avatar URL do banco:",
            patient.avatar_url
          );
          // Adiciona timestamp para forçar reload e evitar cache
          const avatarWithTimestamp = `${patient.avatar_url}?t=${Date.now()}`;
          setAvatarUrl(avatarWithTimestamp);
        } else if (user.id) {
          // Se não houver avatar_url salvo, tenta carregar do Storage usando userId
          const avatarStorageUrl = avatarService.getPublicUrl({
            userId: user.id,
            ext: "jpg",
          });
          console.log(
            "[PerfilPaciente] Tentando carregar avatar do Storage:",
            avatarStorageUrl
          );
          // Adiciona timestamp para forçar reload e evitar cache
          const avatarWithTimestamp = `${avatarStorageUrl}?t=${Date.now()}`;
          setAvatarUrl(avatarWithTimestamp);
        } else {
          setAvatarUrl(undefined);
        }
      } catch {
        console.warn(
          "[PerfilPaciente] Paciente não encontrado na tabela patients, usando dados básicos do auth"
        );
        // Se não encontrar o paciente, usar dados básicos do usuário logado
        setFormData({
          full_name: user.nome || "",
          email: user.email || "",
          phone_mobile: "",
          cpf: "",
          birth_date: "",
          sex: "",
          street: "",
          number: "",
          complement: "",
          neighborhood: "",
          city: "",
          state: "",
          cep: "",
          blood_type: "",
          weight_kg: "",
          height_m: "",
        });
        toast("Preencha seus dados para completar o cadastro", { icon: "ℹ️" });
      }
    } catch (error) {
      console.error(
        "[PerfilPaciente] Erro ao carregar dados do paciente:",
        error
      );
      toast.error("Erro ao carregar dados do perfil");
    } finally {
      setLoading(false);
    }
  };

  const handleSave = async () => {
    if (!user?.id) return;

    try {
      const dataToSave = {
        ...formData,
        weight_kg: formData.weight_kg
          ? parseFloat(formData.weight_kg)
          : undefined,
        height_m: formData.height_m ? parseFloat(formData.height_m) : undefined,
      };

      try {
        // Tentar atualizar primeiro
        await patientService.update(user.id, dataToSave);
        toast.success("Perfil atualizado com sucesso!");
      } catch (updateError) {
        console.warn(
          "[PerfilPaciente] Erro ao atualizar, tentando criar:",
          updateError
        );
        // Se falhar, tentar criar o paciente
        try {
          await patientService.create(dataToSave);
          toast.success("Perfil criado com sucesso!");
        } catch (createError) {
          console.error("[PerfilPaciente] Erro ao criar perfil:", createError);
          throw createError;
        }
      }

      setIsEditing(false);
      // Recarregar dados
      await loadPatientData();
    } catch (error) {
      console.error("[PerfilPaciente] Erro ao salvar perfil:", error);
      toast.error("Erro ao salvar perfil");
    }
  };

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

  const handlePasswordChange = async () => {
    if (passwordData.newPassword !== passwordData.confirmPassword) {
      toast.error("As senhas não coincidem");
      return;
    }

    if (passwordData.newPassword.length < 6) {
      toast.error("A senha deve ter pelo menos 6 caracteres");
      return;
    }

    try {
      // TODO: Implementar mudança de senha via API
      toast.success("Senha alterada com sucesso!");
      setPasswordData({
        currentPassword: "",
        newPassword: "",
        confirmPassword: "",
      });
    } catch (error) {
      console.error("Erro ao alterar senha:", error);
      toast.error("Erro ao alterar senha");
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen bg-gray-50">
        <div className="text-center">
          <div className="w-16 h-16 border-4 border-blue-600 border-t-transparent rounded-full animate-spin mx-auto mb-4" />
          <p className="text-gray-600">Carregando perfil...</p>
        </div>
      </div>
    );
  }

  if (!user?.id) {
    return (
      <div className="flex items-center justify-center min-h-screen bg-gray-50">
        <div className="text-center">
          <p className="text-red-600 mb-4">Usuário não identificado</p>
          <button
            onClick={() => navigate("/paciente")}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
          >
            Fazer Login
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 py-4 sm:py-6 lg:py-8 px-4 sm:px-6">
      <div className="max-w-4xl mx-auto space-y-4 sm:space-y-6">
        {/* Botão Voltar */}
        <button
          onClick={() => navigate("/acompanhamento")}
          className="flex items-center gap-2 text-gray-600 hover:text-gray-900 transition-colors mb-2 sm:mb-4 text-sm sm:text-base"
        >
          <ArrowLeft className="w-4 h-4 sm:w-5 sm:h-5" />
          Voltar para o Painel
        </button>

        {/* Header */}
        <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
          <div className="min-w-0 flex-1">
            <h1 className="text-xl sm:text-2xl lg:text-3xl font-bold text-gray-900 truncate">
              Meu Perfil
            </h1>
            <p className="text-xs sm:text-sm text-gray-600 mt-0.5 sm:mt-1">
              Gerencie suas informações pessoais e médicas
            </p>
          </div>
          {!isEditing ? (
            <button
              onClick={() => setIsEditing(true)}
              className="w-full sm:w-auto px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors text-sm sm:text-base whitespace-nowrap"
            >
              Editar Perfil
            </button>
          ) : (
            <div className="flex gap-2 w-full sm:w-auto">
              <button
                onClick={() => {
                  setIsEditing(false);
                  loadPatientData();
                }}
                className="flex-1 sm:flex-none px-3 sm:px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors text-sm sm:text-base"
              >
                Cancelar
              </button>
              <button
                onClick={handleSave}
                className="flex-1 sm:flex-none px-3 sm:px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center justify-center gap-2 text-sm sm:text-base"
              >
                <Save className="w-4 h-4" />
                Salvar
              </button>
            </div>
          )}
        </div>

        {/* Avatar Card */}
        <div className="bg-white rounded-lg shadow p-4 sm:p-6">
          <h2 className="text-base sm:text-lg font-semibold mb-3 sm:mb-4">
            Foto de Perfil
          </h2>
          <div className="flex flex-col sm:flex-row items-center sm:items-start gap-4 sm:gap-6">
            <AvatarUpload
              userId={user?.id}
              currentAvatarUrl={avatarUrl}
              name={formData.full_name || "Paciente"}
              color="blue"
              size="xl"
              editable={true}
              onAvatarUpdate={(url) => setAvatarUrl(url || undefined)}
            />
            <div className="text-center sm:text-left min-w-0 flex-1">
              <p className="font-medium text-gray-900 text-sm sm:text-base truncate">
                {formData.full_name || "Carregando..."}
              </p>
              <p className="text-gray-500 text-xs sm:text-sm truncate">
                {formData.email || "Sem email"}
              </p>
            </div>
          </div>
        </div>

        {/* Tabs */}
        <div className="bg-white rounded-lg shadow">
          <div className="border-b border-gray-200 overflow-x-auto">
            <nav className="flex -mb-px min-w-max">
              <button
                onClick={() => setActiveTab("personal")}
                className={`px-4 sm:px-6 py-2.5 sm:py-3 text-xs sm:text-sm font-medium border-b-2 transition-colors whitespace-nowrap ${
                  activeTab === "personal"
                    ? "border-blue-600 text-blue-600"
                    : "border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"
                }`}
              >
                Dados Pessoais
              </button>
              <button
                onClick={() => setActiveTab("medical")}
                className={`px-4 sm:px-6 py-2.5 sm:py-3 text-xs sm:text-sm font-medium border-b-2 transition-colors whitespace-nowrap ${
                  activeTab === "medical"
                    ? "border-blue-600 text-blue-600"
                    : "border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"
                }`}
              >
                Info. Médicas
              </button>
              <button
                onClick={() => setActiveTab("security")}
                className={`px-4 sm:px-6 py-2.5 sm:py-3 text-xs sm:text-sm font-medium border-b-2 transition-colors whitespace-nowrap ${
                  activeTab === "security"
                    ? "border-blue-600 text-blue-600"
                    : "border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"
                }`}
              >
                Segurança
              </button>
            </nav>
          </div>

          <div className="p-6">
            {/* Tab: Dados Pessoais */}
            {activeTab === "personal" && (
              <div className="space-y-6">
                <div>
                  <h3 className="text-lg font-semibold mb-4 text-gray-900">
                    Informações Pessoais
                  </h3>
                  <p className="text-sm text-gray-500 mb-4">
                    Mantenha seus dados atualizados
                  </p>

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Nome Completo
                      </label>
                      <input
                        type="text"
                        value={formData.full_name}
                        onChange={(e) =>
                          handleChange("full_name", e.target.value)
                        }
                        disabled={!isEditing}
                        className="form-input"
                      />
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Email
                      </label>
                      <input
                        type="email"
                        value={formData.email}
                        onChange={(e) => handleChange("email", e.target.value)}
                        disabled={!isEditing}
                        className="form-input"
                      />
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Telefone
                      </label>
                      <input
                        type="tel"
                        value={formData.phone_mobile}
                        onChange={(e) =>
                          handleChange("phone_mobile", e.target.value)
                        }
                        disabled={!isEditing}
                        className="form-input"
                      />
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        CPF
                      </label>
                      <input
                        type="text"
                        value={formData.cpf}
                        disabled
                        className="form-input"
                      />
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Data de Nascimento
                      </label>
                      <input
                        type="date"
                        value={formData.birth_date}
                        onChange={(e) =>
                          handleChange("birth_date", e.target.value)
                        }
                        disabled={!isEditing}
                        className="form-input"
                      />
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Sexo
                      </label>
                      <select
                        value={formData.sex}
                        onChange={(e) => handleChange("sex", e.target.value)}
                        disabled={!isEditing}
                        className="form-input"
                      >
                        <option value="">Selecione</option>
                        <option value="M">Masculino</option>
                        <option value="F">Feminino</option>
                        <option value="O">Outro</option>
                      </select>
                    </div>
                  </div>
                </div>

                <div>
                  <h3 className="text-lg font-semibold mb-4">Endereço</h3>

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="md:col-span-2">
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Rua
                      </label>
                      <input
                        type="text"
                        value={formData.street}
                        onChange={(e) => handleChange("street", e.target.value)}
                        disabled={!isEditing}
                        className="form-input"
                      />
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Número
                      </label>
                      <input
                        type="text"
                        value={formData.number}
                        onChange={(e) => handleChange("number", e.target.value)}
                        disabled={!isEditing}
                        className="form-input"
                      />
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Complemento
                      </label>
                      <input
                        type="text"
                        value={formData.complement}
                        onChange={(e) =>
                          handleChange("complement", e.target.value)
                        }
                        disabled={!isEditing}
                        className="form-input"
                      />
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Bairro
                      </label>
                      <input
                        type="text"
                        value={formData.neighborhood}
                        onChange={(e) =>
                          handleChange("neighborhood", e.target.value)
                        }
                        disabled={!isEditing}
                        className="form-input"
                      />
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Cidade
                      </label>
                      <input
                        type="text"
                        value={formData.city}
                        onChange={(e) => handleChange("city", e.target.value)}
                        disabled={!isEditing}
                        className="form-input"
                      />
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Estado
                      </label>
                      <input
                        type="text"
                        value={formData.state}
                        onChange={(e) => handleChange("state", e.target.value)}
                        disabled={!isEditing}
                        maxLength={2}
                        className="form-input"
                      />
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        CEP
                      </label>
                      <input
                        type="text"
                        value={formData.cep}
                        onChange={(e) => handleChange("cep", e.target.value)}
                        disabled={!isEditing}
                        className="form-input"
                      />
                    </div>
                  </div>
                </div>
              </div>
            )}

            {/* Tab: Informações Médicas */}
            {activeTab === "medical" && (
              <div className="space-y-6">
                <div>
                  <h3 className="text-lg font-semibold mb-4">
                    Informações Médicas
                  </h3>
                  <p className="text-sm text-gray-500 mb-4">
                    Dados importantes para atendimento médico
                  </p>

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Tipo Sanguíneo
                      </label>
                      <select
                        value={formData.blood_type}
                        onChange={(e) =>
                          handleChange("blood_type", e.target.value)
                        }
                        disabled={!isEditing}
                        className="form-input"
                      >
                        <option value="">Selecione</option>
                        <option value="A+">A+</option>
                        <option value="A-">A-</option>
                        <option value="B+">B+</option>
                        <option value="B-">B-</option>
                        <option value="AB+">AB+</option>
                        <option value="AB-">AB-</option>
                        <option value="O+">O+</option>
                        <option value="O-">O-</option>
                      </select>
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Peso (kg)
                      </label>
                      <input
                        type="number"
                        step="0.1"
                        value={formData.weight_kg}
                        onChange={(e) =>
                          handleChange("weight_kg", e.target.value)
                        }
                        disabled={!isEditing}
                        className="form-input"
                      />
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Altura (m)
                      </label>
                      <input
                        type="number"
                        step="0.01"
                        value={formData.height_m}
                        onChange={(e) =>
                          handleChange("height_m", e.target.value)
                        }
                        disabled={!isEditing}
                        placeholder="Ex: 1.75"
                        className="form-input"
                      />
                    </div>
                  </div>
                </div>
              </div>
            )}

            {/* Tab: Segurança */}
            {activeTab === "security" && (
              <div className="space-y-6">
                <div>
                  <h3 className="text-lg font-semibold mb-4">Alterar Senha</h3>
                  <p className="text-sm text-gray-500 mb-4">
                    Mantenha sua conta segura
                  </p>

                  <div className="max-w-md space-y-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Senha Atual
                      </label>
                      <input
                        type="password"
                        value={passwordData.currentPassword}
                        onChange={(e) =>
                          setPasswordData({
                            ...passwordData,
                            currentPassword: e.target.value,
                          })
                        }
                        placeholder="Digite sua senha atual"
                        className="form-input"
                      />
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Nova Senha
                      </label>
                      <input
                        type="password"
                        value={passwordData.newPassword}
                        onChange={(e) =>
                          setPasswordData({
                            ...passwordData,
                            newPassword: e.target.value,
                          })
                        }
                        placeholder="Digite a nova senha"
                        className="form-input"
                      />
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Confirmar Nova Senha
                      </label>
                      <input
                        type="password"
                        value={passwordData.confirmPassword}
                        onChange={(e) =>
                          setPasswordData({
                            ...passwordData,
                            confirmPassword: e.target.value,
                          })
                        }
                        placeholder="Confirme a nova senha"
                        className="form-input"
                      />
                    </div>

                    <button
                      onClick={handlePasswordChange}
                      className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                    >
                      Alterar Senha
                    </button>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
