import React, { useState } from "react";
import { useAuth } from "../src/contexts/AuthContext";
import logo from "/assets/logo2.svg?url";
import icon from "../assets/icone.svg";
import { Input } from "../components/ui/input";
import { Button } from "../components/ui/button";
import { Label } from "../components/ui/label";

interface LoginViewProps {
  onLogin: () => void;
}

const LoginView: React.FC<LoginViewProps> = ({ onLogin }) => {
  const { login, isLoading } = useAuth();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [showPassword, setShowPassword] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);

    if (!email.trim() || !password.trim()) {
      setError("Por favor, preencha todos os campos");
      return;
    }

    if (password.length < 3) {
      setError("A senha deve ter no mínimo 3 caracteres");
      return;
    }

    try {
      await login(email, password);
      // O redirecionamento será feito automaticamente pelo useEffect no App.tsx
      // quando isAuthenticated mudar para true
    } catch (err: any) {
      setError(
        err.message || "Erro ao realizar login. Verifique suas credenciais."
      );
    }
  };

  return (
    <div className="min-h-screen flex">
      {/* Lado Esquerdo - Info & Imagem */}
      <div className="hidden lg:flex w-1/2 bg-[#002147] relative p-10 flex-col justify-between overflow-hidden">
        <div className="absolute top-[-10%] right-[-10%] w-96 h-96 bg-orange-500/20 rounded-full blur-[120px]"></div>
        <div className="absolute bottom-[-10%] left-[-10%] w-96 h-96 bg-blue-400/10 rounded-full blur-[120px]"></div>

        <div className="relative z-10">
          <div className="flex items-center space-x-2 mb-8">
            <div className="bg-white p-1.5 rounded-lg">
              <img src={icon} alt="Jurunense Icon" className="w-6 h-6" />
            </div>
            <span className="text-lg font-black text-white tracking-tight">
              PLATAFORMA <span className="text-orange-500">VENDAS WEB</span>
            </span>
          </div>

          <h1 className="text-5xl font-extrabold text-white leading-tight mb-4">
            Gestão inteligente para sua operação de vendas
            <span className="text-orange-500"> Jurunense Home Center</span>
          </h1>
          <p className="text-slate-300 text-sm max-w-lg leading-relaxed">
            Acesse as ferramentas de venda e dashboard da Jurunense Home Center
            em um único lugar.
          </p>
        </div>

        <div className="relative z-10 flex items-center space-x-4 opacity-50">
          <span className="text-sm font-bold text-white uppercase tracking-widest">
            © 2025 Jurunense Tecnologia
          </span>
        </div>
      </div>

      {/* Lado Direito - Formulário */}
      <div className="w-full lg:w-1/2 flex items-center justify-center p-4 lg:p-6 bg-white">
        <div className="w-full max-w-md">
          <div className="mb-6 lg:hidden">
            <span className="text-lg font-black text-[#002147] tracking-tight">
              SMART <span className="text-orange-500">PLATFORM</span>
            </span>
          </div>

          <div className="mb-1 flex justify-center">
            <img src={logo} alt="Jurunense Logo" className="h-40 w-auto" />
          </div>

          <h2 className="text-2xl font-extrabold text-slate-900 mb-1">
            Bem-vindo de volta
          </h2>
          <p className="text-slate-500 mb-6 text-sm font-medium">
            Por favor, insira suas credenciais de acesso.
          </p>

          {error && (
            <div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-2xl">
              <p className="text-red-600 text-sm font-medium">{error}</p>
            </div>
          )}

          <form className="space-y-6" onSubmit={handleSubmit}>
            <div className="space-y-2">
              <Label className="text-sm font-bold text-slate-700 uppercase tracking-wide">
                Usuário/e-mail de Acesso
              </Label>
              <Input
                type="text"
                placeholder="nome@jurunense.com.br"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                disabled={isLoading}
                className="bg-slate-50 border-slate-200 focus:border-orange-500 focus:ring-orange-500/10"
                autoComplete="username"
              />
            </div>

            <div className="space-y-2">
              <div className="flex justify-between items-center">
                <Label className="text-sm font-bold text-slate-700 uppercase tracking-wide">
                  Senha de Acesso
                </Label>
                <a
                  href="#"
                  className="text-xs font-bold text-orange-600 hover:text-orange-700"
                >
                  Esqueceu a senha?
                </a>
              </div>
              <div className="relative">
                <Input
                  type={showPassword ? "text" : "password"}
                  placeholder="••••••••"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  disabled={isLoading}
                  className="bg-slate-50 border-slate-200 focus:border-orange-500 focus:ring-orange-500/10 pr-12"
                  autoComplete="current-password"
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-4 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
                  disabled={isLoading}
                >
                  {showPassword ? (
                    <svg
                      className="w-5 h-5"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth="2"
                        d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"
                      />
                    </svg>
                  ) : (
                    <svg
                      className="w-5 h-5"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth="2"
                        d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
                      />
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth="2"
                        d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"
                      />
                    </svg>
                  )}
                </button>
              </div>
            </div>

            <Button
              type="submit"
              disabled={isLoading}
              className="w-full py-3.5 font-extrabold uppercase text-sm tracking-widest transform hover:-translate-y-0.5 active:translate-y-0 shadow-lg shadow-blue-900/20 disabled:transform-none"
            >
              {isLoading ? (
                <>
                  <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>
                  Autenticando...
                </>
              ) : (
                "Acessar Plataforma"
              )}
            </Button>
          </form>

          <div className="mt-8 pt-6 border-t border-slate-100 flex items-center justify-between">
            <span className="text-xs text-slate-400">Problemas no acesso?</span>
            <button className="text-sm font-bold text-[#002147] flex items-center hover:underline">
              Suporte TI
              <svg
                className="w-4 h-4 ml-1"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth="2"
                  d="M14 5l7 7m0 0l-7 7m7-7H3"
                />
              </svg>
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default LoginView;
