import React, { useState } from "react";
import { User, Mail, Lock, Eye, EyeOff } from "lucide-react";
import toast from "react-hot-toast";
import { useNavigate } from "react-router-dom";
import { useAuth } from "../hooks/useAuth";
import { authService, patientService, userService } from "../services";

const LoginPaciente: React.FC = () => {
  const [formData, setFormData] = useState({
    email: "",
    senha: "",
  });
  const [loading, setLoading] = useState(false);
  const [showCadastro, setShowCadastro] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [cadastroData, setCadastroData] = useState({
    nome: "",
    email: "",
    telefone: "",
    cpf: "",
    dataNascimento: "",
  });

  const navigate = useNavigate();

  const { loginPaciente } = useAuth();

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);

    try {
      console.log("[LoginPaciente] Fazendo login com email:", formData.email);

      // Fazer login via API Supabase
      const loginResponse = await authService.login({
        email: formData.email,
        password: formData.senha,
      });

      console.log("[LoginPaciente] Login bem-sucedido!", loginResponse);

      // Buscar informações completas do usuário (profile + roles)
      let userName = loginResponse.user.email?.split("@")[0] || "Paciente";

      try {
        const userInfo = await userService.getUserInfo();
        console.log("[LoginPaciente] UserInfo obtido:", userInfo);

        // Pegar o nome do profile
        if (userInfo.profile?.full_name) {
          userName = userInfo.profile.full_name;
        }
      } catch {
        console.warn(
          "[LoginPaciente] Não foi possível obter user-info, usando dados básicos"
        );
      }

      // Tentar buscar dados do paciente da tabela patients
      const pacientes = await patientService.list({ email: formData.email });
      const paciente = pacientes && pacientes.length > 0 ? pacientes[0] : null;

      console.log("[LoginPaciente] Paciente encontrado:", paciente);

      // Usar nome do paciente se disponível, senão usar do profile
      const finalName = paciente?.full_name || userName;

      // IMPORTANTE: Usar sempre loginResponse.user.id (auth user_id do Supabase)
      // Este é o ID correto para vincular ao Storage e outras tabelas
      console.log("[LoginPaciente] IDs:", {
        authUserId: loginResponse.user.id,
        patientId: paciente?.id,
        patientUserId: paciente?.user_id,
        usingId: loginResponse.user.id,
      });

      const ok = await loginPaciente({
        id: loginResponse.user.id, // ✅ Sempre usar o auth user_id
        nome: finalName,
        email: loginResponse.user.email || formData.email,
      });

      if (ok) {
        console.log("[LoginPaciente] Navegando para /acompanhamento");
        toast.success(`Bem-vindo, ${finalName}!`);
        navigate("/acompanhamento");
      } else {
        console.error("[LoginPaciente] loginPaciente retornou false");
        toast.error("Erro ao processar login");
      }
    } catch (error: unknown) {
      console.error("[LoginPaciente] Erro no login:", error);
      const err = error as {
        response?: { data?: { error_description?: string; message?: string } };
        message?: string;
      };
      const errorMessage =
        err?.response?.data?.error_description ||
        err?.response?.data?.message ||
        err?.message ||
        "Erro ao fazer login. Verifique suas credenciais.";
      toast.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  const handleCadastro = async (e: React.FormEvent) => {
    e.preventDefault();

    // Validações básicas
    if (!cadastroData.nome.trim()) {
      toast.error("Nome completo é obrigatório");
      return;
    }

    if (!cadastroData.email.trim()) {
      toast.error("Email é obrigatório");
      return;
    }

    if (!cadastroData.cpf.trim()) {
      toast.error("CPF é obrigatório");
      return;
    }

    if (!cadastroData.telefone.trim()) {
      toast.error("Telefone celular é obrigatório");
      return;
    }

    setLoading(true);

    try {
      // Usar novo endpoint register-patient (público, validações rigorosas)
      const registerData = {
        email: cadastroData.email.trim(),
        full_name: cadastroData.nome.trim(),
        cpf: cadastroData.cpf.trim().replace(/\D/g, ""),
        phone_mobile: cadastroData.telefone.trim().replace(/\D/g, ""),
        birth_date: cadastroData.dataNascimento || undefined,
        redirect_url:
          "https://mediconnectbrasil.netlify.app/paciente/agendamento",
      };

      console.log("[LoginPaciente] Dados que serão enviados:", registerData);

      await patientService.register(registerData);

      toast.success(
        "Cadastro realizado! Verifique seu email para ativar a conta e definir sua senha.",
        { duration: 6000 }
      );

      // Limpar formulário e voltar para tela de login
      setCadastroData({
        nome: "",
        email: "",
        telefone: "",
        cpf: "",
        dataNascimento: "",
      });

      // Preencher email no formulário de login
      setFormData({
        email: cadastroData.email,
        senha: "",
      });

      setShowCadastro(false);
    } catch (error: unknown) {
      const err = error as {
        response?: { data?: { error?: string; message?: string } };
        message?: string;
      };
      console.error("[LoginPaciente] Erro ao cadastrar:", {
        error,
        response: err?.response,
        data: err?.response?.data,
      });
      const errorMessage =
        err?.response?.data?.error ||
        err?.response?.data?.message ||
        err?.message ||
        "Erro ao realizar cadastro";
      toast.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-white dark:from-gray-900 dark:to-gray-950 flex items-center justify-center p-4 transition-colors">
      <div className="max-w-md w-full">
        {/* Header */}
        <div className="text-center mb-8">
          <div className="bg-gradient-to-r from-blue-700 to-blue-400 dark:from-blue-800 dark:to-blue-500 w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-4 shadow-md">
            <User className="w-8 h-8 text-white" />
          </div>
          <h1 className="text-3xl font-bold text-gray-900 dark:text-gray-100 mb-2">
            {showCadastro ? "Criar Conta" : "Área do Paciente"}
          </h1>
          <p className="text-gray-600 dark:text-gray-400">
            {showCadastro
              ? "Preencha seus dados para criar sua conta"
              : "Faça login para acompanhar suas consultas"}
          </p>
        </div>

        {/* Formulário */}
        <div
          className="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-8 border border-transparent dark:border-gray-700 transition-colors"
          aria-live="polite"
        >
          {!showCadastro ? (
            /* Formulário de Login */
            <form onSubmit={handleLogin} className="space-y-6" noValidate>
              <div>
                <label
                  htmlFor="login_email"
                  className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
                >
                  Email
                </label>
                <div className="relative">
                  <Mail className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
                  <input
                    id="login_email"
                    type="email"
                    value={formData.email}
                    onChange={(e) =>
                      setFormData((prev) => ({
                        ...prev,
                        email: e.target.value,
                      }))
                    }
                    className="form-input pl-10 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-gray-100"
                    placeholder="seu@email.com"
                    required
                    autoComplete="email"
                  />
                </div>
              </div>

              <div>
                <label
                  htmlFor="login_password"
                  className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
                >
                  Senha
                </label>
                <div className="relative">
                  <Lock className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
                  <input
                    id="login_password"
                    type={showPassword ? "text" : "password"}
                    value={formData.senha}
                    onChange={(e) =>
                      setFormData((prev) => ({
                        ...prev,
                        senha: e.target.value,
                      }))
                    }
                    className="form-input pl-10 pr-10 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-gray-100"
                    placeholder="Sua senha"
                    required
                    autoComplete="current-password"
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                    title={showPassword ? "Ocultar senha" : "Mostrar senha"}
                  >
                    {showPassword ? (
                      <EyeOff className="w-5 h-5" />
                    ) : (
                      <Eye className="w-5 h-5" />
                    )}
                  </button>
                </div>
                <div className="text-right mt-2">
                  <button
                    type="button"
                    onClick={async () => {
                      if (!formData.email.trim()) {
                        toast.error("Digite seu email primeiro");
                        return;
                      }
                      try {
                        await authService.requestPasswordReset(formData.email);
                        toast.success(
                          "Email de recuperação enviado! Verifique sua caixa de entrada."
                        );
                      } catch {
                        toast.error("Erro ao enviar email de recuperação");
                      }
                    }}
                    className="text-sm text-blue-600 dark:text-blue-400 hover:underline transition-colors"
                  >
                    Esqueceu a senha?
                  </button>
                </div>
              </div>

              <button
                type="submit"
                disabled={loading}
                className="w-full bg-gradient-to-r from-blue-600 to-cyan-500 dark:from-blue-700 dark:to-cyan-600 text-white py-3 rounded-lg font-semibold hover:from-blue-700 hover:to-cyan-600 dark:hover:from-blue-800 dark:hover:to-cyan-700 transition-all transform hover:scale-105 disabled:opacity-50 disabled:cursor-not-allowed disabled:transform-none shadow-md"
              >
                {loading ? "Entrando..." : "Entrar"}
              </button>

              {/* Divisor OU */}
              <div className="relative my-6">
                <div className="absolute inset-0 flex items-center">
                  <div className="w-full border-t border-gray-300 dark:border-gray-600"></div>
                </div>
                <div className="relative flex justify-center text-sm">
                  <span className="px-2 bg-white dark:bg-gray-800 text-gray-500 dark:text-gray-400">
                    OU
                  </span>
                </div>
              </div>

              {/* Botão Magic Link */}
              <button
                type="button"
                onClick={async () => {
                  if (!formData.email.trim()) {
                    toast.error("Digite seu email primeiro");
                    return;
                  }
                  setLoading(true);
                  try {
                    // Salvar contexto para redirecionamento correto após magic link
                    localStorage.setItem(
                      "magic_link_redirect",
                      "/acompanhamento"
                    );

                    await authService.sendMagicLink(formData.email);
                    toast.success(
                      "Link de acesso enviado para seu email! Verifique sua caixa de entrada.",
                      { duration: 6000 }
                    );
                  } catch (error: unknown) {
                    const err = error as { message?: string };
                    toast.error(err?.message || "Erro ao enviar link");
                  } finally {
                    setLoading(false);
                  }
                }}
                disabled={loading}
                className="w-full bg-white dark:bg-gray-700 text-blue-700 dark:text-blue-400 border-2 border-blue-700 dark:border-blue-400 py-3 px-4 rounded-lg font-medium hover:bg-blue-50 dark:hover:bg-gray-600 hover:scale-105 active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:scale-100 transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2"
              >
                {loading ? "Enviando..." : "Entrar sem senha (Magic Link)"}
              </button>

              <div className="text-center mt-4">
                <button
                  type="button"
                  onClick={() => setShowCadastro(true)}
                  className="text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 font-medium text-sm transition-colors"
                >
                  Não tem conta? Cadastre-se aqui
                </button>
              </div>
            </form>
          ) : (
            /* Formulário de Cadastro - Apenas campos da API */
            <form onSubmit={handleCadastro} className="space-y-4" noValidate>
              {/* Nome Completo */}
              <div>
                <label
                  htmlFor="cad_nome"
                  className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
                >
                  Nome Completo *
                </label>
                <input
                  id="cad_nome"
                  type="text"
                  value={cadastroData.nome}
                  onChange={(e) =>
                    setCadastroData((prev) => ({
                      ...prev,
                      nome: e.target.value,
                    }))
                  }
                  className="form-input dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-gray-100"
                  required
                  autoComplete="name"
                  placeholder="João Silva"
                />
              </div>

              {/* Email */}
              <div>
                <label
                  htmlFor="cad_email"
                  className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
                >
                  Email *
                </label>
                <input
                  id="cad_email"
                  type="email"
                  value={cadastroData.email}
                  onChange={(e) =>
                    setCadastroData((prev) => ({
                      ...prev,
                      email: e.target.value,
                    }))
                  }
                  className="form-input dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-gray-100"
                  required
                  autoComplete="email"
                  placeholder="seu@email.com"
                />
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {/* CPF */}
                <div>
                  <label
                    htmlFor="cad_cpf"
                    className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
                  >
                    CPF *
                  </label>
                  <input
                    id="cad_cpf"
                    type="text"
                    value={cadastroData.cpf}
                    onChange={(e) =>
                      setCadastroData((prev) => ({
                        ...prev,
                        cpf: e.target.value,
                      }))
                    }
                    className="form-input dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-gray-100"
                    placeholder="000.000.000-00"
                    required
                    inputMode="numeric"
                    pattern="^\d{3}\.\d{3}\.\d{3}-\d{2}$|^\d{11}$"
                  />
                </div>

                {/* Telefone Celular */}
                <div>
                  <label
                    htmlFor="cad_telefone"
                    className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
                  >
                    Telefone Celular *
                  </label>
                  <input
                    id="cad_telefone"
                    type="tel"
                    value={cadastroData.telefone}
                    onChange={(e) =>
                      setCadastroData((prev) => ({
                        ...prev,
                        telefone: e.target.value,
                      }))
                    }
                    className="form-input dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-gray-100"
                    placeholder="(11) 99999-9999"
                    required
                    inputMode="numeric"
                    pattern="^\(?\d{2}\)?\s?9?\d{4}-?\d{4}$"
                    autoComplete="tel"
                  />
                </div>
              </div>

              {/* Data de Nascimento */}
              <div>
                <label
                  htmlFor="cad_data_nasc"
                  className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
                >
                  Data de Nascimento (opcional)
                </label>
                <input
                  id="cad_data_nasc"
                  type="date"
                  value={cadastroData.dataNascimento}
                  onChange={(e) =>
                    setCadastroData((prev) => ({
                      ...prev,
                      dataNascimento: e.target.value,
                    }))
                  }
                  className="form-input dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-gray-100"
                  autoComplete="bday"
                />
              </div>

              {/* Info sobre Magic Link */}
              <div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-3">
                <p className="text-sm text-blue-800 dark:text-blue-200">
                  ℹ️ Após o cadastro, você receberá um email com link para
                  ativar sua conta e definir sua senha.
                </p>
              </div>

              {/* Botões */}
              <div className="flex space-x-4">
                <button
                  type="button"
                  onClick={() => setShowCadastro(false)}
                  className="flex-1 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 py-3 px-4 rounded-lg font-medium hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"
                >
                  Voltar
                </button>
                <button
                  type="submit"
                  disabled={loading}
                  className="flex-1 bg-gradient-to-r from-blue-700 to-blue-400 text-white py-3 px-4 rounded-lg font-medium hover:from-blue-800 hover:to-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-all"
                >
                  {loading ? "Cadastrando..." : "Cadastrar"}
                </button>
              </div>
            </form>
          )}
        </div>
      </div>
    </div>
  );
};

export default LoginPaciente;
