import React, { useState } from "react";
import { LogIn, Mail, Lock, AlertCircle } from "lucide-react";
import { authService, patientService, doctorService } from "../services";
import { useAuth } from "../hooks/useAuth";
import toast from "react-hot-toast";

const Login: React.FC = () => {
  const { loginPaciente } = useAuth();
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState({
    email: "",
    password: "",
  });

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value,
    });
  };

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

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

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

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

      const userName =
        loginResponse.user.email?.split("@")[0] || "Usuário";
      const userId = loginResponse.user.id;

      // Tentar detectar o tipo de usuário buscando nas tabelas
      console.log("[Login] Detectando tipo de usuário...");

      // Verificar se é paciente
      try {
        const paciente = await patientService.getByUserId(userId);
        if (paciente) {
          console.log("[Login] Usuário identificado como PACIENTE");
          await loginPaciente({
            id: userId,
            nome: paciente.full_name || userName,
            email: loginResponse.user.email || formData.email,
          });
          toast.success(`Bem-vindo, ${paciente.full_name || userName}!`);
          // Forçar reload da página para garantir que o AuthContext detecte
          window.location.href = "/acompanhamento";
          return;
        }
      } catch (e) {
        console.log("[Login] Não é paciente");
      }

      // Verificar se é médico
      try {
        const medico = await doctorService.getByUserId(userId);
        if (medico) {
          console.log("[Login] Usuário identificado como MÉDICO");
          // Salvar dados do médico no localStorage (padrão do sistema)
          const medicoSession = {
            id: userId, // usar userId do auth para consistência
            nome: medico.full_name || userName,
            email: loginResponse.user.email || formData.email,
            role: "medico" as const,
            crm: medico.crm,
            especialidade: medico.specialty,
            roles: ["medico" as const],
            permissions: {},
          };
          
          // Salvar no localStorage com o formato esperado pelo AuthContext
          const sessionData = {
            user: medicoSession,
            token: loginResponse.access_token,
            refreshToken: loginResponse.refresh_token,
            savedAt: new Date().toISOString(),
          };
          localStorage.setItem("appSession", JSON.stringify(sessionData));
          
          // Também salvar nos formatos legados para compatibilidade
          localStorage.setItem("mediconnect_user", JSON.stringify({
            user: { id: userId, email: loginResponse.user.email },
            ...medicoSession
          }));
          localStorage.setItem("mediconnect_medico", JSON.stringify(medicoSession));
          
          toast.success(`Bem-vindo, Dr(a). ${medico.full_name || userName}!`);
          
          // Forçar reload da página para o AuthContext detectar a mudança
          window.location.href = "/painel-medico";
          return;
        }
      } catch (e) {
        console.log("[Login] Não é médico", e);
      }

      // Se não for paciente nem médico, assume secretária
      console.log("[Login] Usuário identificado como SECRETÁRIA");
      // Salvar dados da secretária no localStorage
      const secretariaSession = {
        id: userId,
        nome: userName,
        email: loginResponse.user.email || formData.email,
        role: "secretaria" as const,
        roles: ["secretaria" as const],
        permissions: {},
      };
      
      // Salvar no localStorage com o formato esperado pelo AuthContext
      const sessionData = {
        user: secretariaSession,
        token: loginResponse.access_token,
        refreshToken: loginResponse.refresh_token,
        savedAt: new Date().toISOString(),
      };
      localStorage.setItem("appSession", JSON.stringify(sessionData));
      
      // Também salvar nos formatos legados
      localStorage.setItem("mediconnect_user", JSON.stringify({
        user: { id: userId, email: loginResponse.user.email },
        ...secretariaSession
      }));
      localStorage.setItem("mediconnect_secretaria", JSON.stringify(secretariaSession));
      
      toast.success(`Bem-vindo, ${userName}!`);
      
      // Forçar reload da página para o AuthContext detectar a mudança
      window.location.href = "/painel-secretaria";
    } catch (error: any) {
      console.error("[Login] Erro no login:", error);
      const errorMessage =
        error?.response?.data?.error_description ||
        error?.response?.data?.message ||
        error?.message ||
        "Email ou senha incorretos";
      toast.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 flex items-center justify-center px-4 py-12">
      <div className="max-w-md w-full space-y-8">
        {/* Header */}
        <div className="text-center">
          <div className="mx-auto h-16 w-16 bg-blue-600 rounded-full flex items-center justify-center mb-4">
            <LogIn className="h-8 w-8 text-white" />
          </div>
          <h2 className="text-3xl font-bold text-gray-900">Fazer Login</h2>
          <p className="mt-2 text-sm text-gray-600">
            Entre com suas credenciais para acessar o sistema
          </p>
        </div>

        {/* Form */}
        <div className="bg-white rounded-xl shadow-lg p-8">
          <form onSubmit={handleSubmit} className="space-y-6">
            {/* Email */}
            <div>
              <label
                htmlFor="email"
                className="block text-sm font-medium text-gray-700 mb-2"
              >
                Email
              </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-gray-400" />
                </div>
                <input
                  id="email"
                  name="email"
                  type="email"
                  autoComplete="email"
                  required
                  value={formData.email}
                  onChange={handleChange}
                  className="block w-full pl-10 pr-3 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-gray-900 placeholder-gray-400"
                  placeholder="seu@email.com"
                />
              </div>
            </div>

            {/* Senha */}
            <div>
              <label
                htmlFor="password"
                className="block text-sm font-medium text-gray-700 mb-2"
              >
                Senha
              </label>
              <div className="relative">
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <Lock className="h-5 w-5 text-gray-400" />
                </div>
                <input
                  id="password"
                  name="password"
                  type="password"
                  autoComplete="current-password"
                  required
                  value={formData.password}
                  onChange={handleChange}
                  className="block w-full pl-10 pr-3 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-gray-900 placeholder-gray-400"
                  placeholder="••••••••"
                />
              </div>
            </div>

            {/* Info */}
            <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
              <div className="flex">
                <div className="flex-shrink-0">
                  <AlertCircle className="h-5 w-5 text-blue-400" />
                </div>
                <div className="ml-3">
                  <p className="text-sm text-blue-700">
                    O sistema detectará automaticamente seu tipo de usuário
                    (Paciente, Médico ou Secretária) e redirecionará para a
                    página apropriada.
                  </p>
                </div>
              </div>
            </div>

            {/* Submit */}
            <button
              type="submit"
              disabled={loading}
              className="w-full flex justify-center items-center py-3 px-4 border border-transparent rounded-lg shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              {loading ? (
                <>
                  <svg
                    className="animate-spin -ml-1 mr-3 h-5 w-5 text-white"
                    xmlns="http://www.w3.org/2000/svg"
                    fill="none"
                    viewBox="0 0 24 24"
                  >
                    <circle
                      className="opacity-25"
                      cx="12"
                      cy="12"
                      r="10"
                      stroke="currentColor"
                      strokeWidth="4"
                    ></circle>
                    <path
                      className="opacity-75"
                      fill="currentColor"
                      d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                    ></path>
                  </svg>
                  Entrando...
                </>
              ) : (
                <>
                  <LogIn className="h-5 w-5 mr-2" />
                  Entrar
                </>
              )}
            </button>
          </form>

          {/* Footer */}
          <div className="mt-6 text-center">
            <p className="text-sm text-gray-600">
              Esqueceu sua senha?{" "}
              <a
                href="/reset-password"
                className="font-medium text-blue-600 hover:text-blue-500"
              >
                Recuperar senha
              </a>
            </p>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Login;
