import React, { useState } from "react";
import { Button } from "../components/Button";
import { X } from "lucide-react";
import { verifyAccessCode } from "../services/apiService";

interface HomeProps {
  onEnter: () => void;
}

export const Home: React.FC<HomeProps> = ({ onEnter }) => {
  const [showAccessCodeModal, setShowAccessCodeModal] = useState(false);
  const [accessCode, setAccessCode] = useState("");
  const [showProfessionalPrompt, setShowProfessionalPrompt] = useState(false);
  const [codeError, setCodeError] = useState("");
  const [isProfessionalRegistration, setIsProfessionalRegistration] = useState(false);

  const handleRegisterClick = () => {
    setShowProfessionalPrompt(true);
    setAccessCode("");
    setCodeError("");
  };

  const handleVerifyCode = async () => {
    if (accessCode.trim() === "") {
      setCodeError("Por favor, digite o código de acesso");
      return;
    }

    try {
      const res = await verifyAccessCode(accessCode.toUpperCase());
      if (res.data && res.data.valid) {
        setShowAccessCodeModal(false);
        if (isProfessionalRegistration) {
          window.location.href = "/cadastro-profissional";
        } else {
          window.location.href = "/cadastro";
        }
      } else {
        setCodeError(res.data?.error || "Código de acesso inválido ou expirado");
      }
    } catch (e) {
      setCodeError("Erro ao verificar código");
    }
  };

  const handleProfessionalChoice = (isProfessional: boolean) => {
    setShowProfessionalPrompt(false);
    setIsProfessionalRegistration(isProfessional);
    setShowAccessCodeModal(true);
  };

  return (
    <div
      className="min-h-screen flex items-center justify-center relative overflow-hidden"
      style={{ backgroundColor: "#B9CF33" }}
    >
      <style>{`
        @keyframes fadeInScale {
          from {
            opacity: 0;
            transform: scale(0.9);
          }
          to {
            opacity: 1;
            transform: scale(1);
          }
        }
        @keyframes float {
          0%, 100% {
            transform: translateY(0px);
          }
          50% {
            transform: translateY(-20px);
          }
        }
        .animate-fade-in-scale {
          animation: fadeInScale 0.6s ease-out forwards;
        }
        .animate-float {
          animation: float 6s ease-in-out infinite;
        }
      `}</style>

      {/* Círculos decorativos animados */}
      <div
        className="absolute top-5 sm:top-10 left-5 sm:left-10 w-32 sm:w-48 md:w-64 h-32 sm:h-48 md:h-64 bg-white/20 rounded-full blur-2xl sm:blur-3xl animate-float"
        style={{ animationDelay: "0s" }}
      ></div>
      <div
        className="absolute bottom-10 sm:bottom-20 right-10 sm:right-20 w-48 sm:w-64 md:w-80 h-48 sm:h-64 md:h-80 bg-white/20 rounded-full blur-2xl sm:blur-3xl animate-float"
        style={{ animationDelay: "2s" }}
      ></div>
      <div
        className="absolute top-1/3 right-5 sm:right-10 w-32 sm:w-40 md:w-48 h-32 sm:h-40 md:h-48 bg-white/20 rounded-full blur-xl sm:blur-2xl animate-float"
        style={{ animationDelay: "4s" }}
      ></div>

      <div className="bg-white rounded-xl sm:rounded-2xl shadow-2xl p-6 sm:p-8 md:p-12 max-w-[90%] sm:max-w-md w-full mx-3 sm:mx-4 animate-fade-in-scale relative z-10">
        {/* Logo */}
        <div className="flex justify-center mb-4 sm:mb-6">
          <img
            src="/logo_preta.png"
            alt="Photum Formaturas"
            className="h-16 sm:h-20 md:h-24 lg:h-32 w-auto object-contain"
          />
        </div>

        {/* Botões */}
        <div className="space-y-3 sm:space-y-4">
          <Button onClick={onEnter} className="w-full" size="lg">
            Entrar
          </Button>

          <Button
            onClick={handleRegisterClick}
            variant="outline"
            className="w-full"
            size="lg"
          >
            Cadastre-se agora
          </Button>
        </div>
      </div>

      {/* Modal de Código de Acesso */}
      {showAccessCodeModal && (
        <div
          className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4"
          onClick={() => setShowAccessCodeModal(false)}
        >
          <div
            className="bg-white rounded-2xl shadow-2xl max-w-md w-full p-6 sm:p-8 animate-fade-in-scale"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="flex justify-between items-center mb-6">
              <h2 className="text-2xl font-bold text-gray-900">
                Código de Acesso
              </h2>
              <button
                onClick={() => setShowAccessCodeModal(false)}
                className="text-gray-400 hover:text-gray-600 transition-colors"
              >
                <X size={24} />
              </button>
            </div>

            <p className="text-gray-600 mb-6">
              Digite o código de acesso fornecido pela empresa para continuar
              com o cadastro.
            </p>

            <div className="mb-4">
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Código de Acesso *
              </label>
              <input
                type="text"
                value={accessCode}
                onChange={(e) => {
                  setAccessCode(e.target.value.toUpperCase());
                  setCodeError("");
                }}
                onKeyPress={(e) => e.key === "Enter" && handleVerifyCode()}
                className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#B9CF33] focus:border-transparent uppercase"
                placeholder="Digite o código"
                autoFocus
              />
              {codeError && (
                <p className="text-red-500 text-sm mt-2">{codeError}</p>
              )}
            </div>

            <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4 mb-6">
              <p className="text-sm text-yellow-800">
                <strong>Atenção:</strong> O código de acesso é fornecido pela
                empresa e tem validade temporária.
              </p>
            </div>

            <div className="flex gap-3">
              <Button
                variant="outline"
                onClick={() => setShowAccessCodeModal(false)}
                className="flex-1"
              >
                Cancelar
              </Button>
              <Button onClick={handleVerifyCode} className="flex-1">
                Verificar
              </Button>
            </div>
          </div>
        </div>
      )}

      {/* Modal de Escolha de Tipo de Cadastro */}
      {showProfessionalPrompt && (
        <div
          className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4"
          onClick={() => setShowProfessionalPrompt(false)}
        >
          <div
            className="bg-white rounded-2xl shadow-2xl max-w-md w-full p-6 sm:p-8 animate-fade-in-scale"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="flex justify-between items-center mb-6">
              <h2 className="text-2xl font-bold text-gray-900">
                Tipo de Cadastro
              </h2>
              <button
                onClick={() => setShowProfessionalPrompt(false)}
                className="text-gray-400 hover:text-gray-600 transition-colors"
              >
                <X size={24} />
              </button>
            </div>

            <p className="text-gray-600 mb-6">
              Você é um profissional (fotógrafo/cinegrafista) ou um cliente?
            </p>

            <div className="space-y-3">
              <button
                onClick={() => handleProfessionalChoice(true)}
                className="w-full p-4 border-2 border-[#492E61] bg-[#492E61]/5 hover:bg-[#492E61]/10 rounded-xl transition-colors text-left group"
              >
                <h3 className="font-semibold text-[#492E61] mb-1">
                  Sou Profissional
                </h3>
                <p className="text-sm text-gray-600">
                  Cadastro para fotógrafos e cinegrafistas
                </p>
              </button>

              <button
                onClick={() => handleProfessionalChoice(false)}
                className="w-full p-4 border-2 border-[#B9CF33] bg-[#B9CF33]/5 hover:bg-[#B9CF33]/10 rounded-xl transition-colors text-left group"
              >
                <h3 className="font-semibold text-[#492E61] mb-1">
                  Sou Cliente
                </h3>
                <p className="text-sm text-gray-600">
                  Cadastro para solicitar serviços
                </p>
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};
