import { FormEvent, useState } from 'react'
import axios from 'axios'
import { useAuth, UserRole } from '../context/AuthContext'
import { authService } from '../services/auth'
import { logger } from '../utils/logger'
import { decodeJwtPayload } from '../utils/jwt'
import logoImg from '../assets/logo.png' // Ensure logo import is handled

// Eye icon components for password visibility toggle
const EyeIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5 text-gray-500">
    <path strokeLinecap="round" strokeLinejoin="round" d="M2.036 12.322a1.012 1.012 0 0 1 0-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178Z" />
    <path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z" />
  </svg>
)

const EyeSlashIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5 text-gray-500">
    <path strokeLinecap="round" strokeLinejoin="round" d="M3.98 8.223A10.477 10.477 0 0 0 1.934 12C3.226 16.338 7.244 19.5 12 19.5c.993 0 1.953-.138 2.863-.395M6.228 6.228A10.451 10.451 0 0 1 12 4.5c4.756 0 8.773 3.162 10.065 7.498a10.522 10.522 0 0 1-4.293 5.774M6.228 6.228 3 3m3.228 3.228 3.65 3.65m7.894 7.894L21 21m-3.228-3.228-3.65-3.65m0 0a3 3 0 1 0-4.243-4.243m4.242 4.242L9.88 9.88" />
  </svg>
)

export function LoginPage() {
  const { login } = useAuth()
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [showPassword, setShowPassword] = useState(false)
  const [errorMessage, setErrorMessage] = useState<string | null>(null)
  const [loading, setLoading] = useState(false)
  const [activeTab, setActiveTab] = useState<'login' | 'register'>('login')

  const resolveRole = (role?: string): UserRole => {
    logger.info('🔐 [Login] Resolving role:', role)
    switch (role?.toLowerCase()) {
      case 'admin': return 'admin'
      case 'dono': return 'owner'
      case 'colaborador': return 'employee'
      case 'entregador': return 'delivery'
      case 'customer': return 'customer'
      case 'seller': default: return 'seller'
    }
  }

  const onSubmit = async (event: FormEvent) => {
    event.preventDefault()
    setLoading(true)
    setErrorMessage(null)

    try {
      const response = await authService.login({ username, password })
      const { token } = response
      if (!token) throw new Error('Resposta de login inválida. Verifique o usuário e a senha.')

      const payload = decodeJwtPayload<{ role?: string, sub: string, company_id?: string }>(token)
      const role = resolveRole(payload?.role)

      login(token, role, username, payload?.sub || '', payload?.company_id, undefined, username)
    } catch (error) {
      const fallback = 'Não foi possível autenticar. Verifique suas credenciais.'
      if (axios.isAxiosError(error)) {
        setErrorMessage(error.response?.data?.error ?? fallback)
      } else if (error instanceof Error) {
        setErrorMessage(error.message)
      } else {
        setErrorMessage(fallback)
      }
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="flex min-h-screen items-center justify-center bg-gray-100 p-4">
      <div className="w-full max-w-[400px] overflow-hidden rounded-2xl bg-white shadow-xl">
        {/* Blue Header with Logo */}
        <div className="flex flex-col items-center bg-blue-600 pb-8 pt-10 text-white">
          <div className="mb-4 flex h-16 w-16 items-center justify-center rounded-2xl bg-white/10 backdrop-blur-sm">
            <img src={logoImg} alt="Logo" className="h-10 w-auto brightness-0 invert" />
          </div>
          <h1 className="text-2xl font-bold">SaveInMed</h1>
          <p className="text-blue-100 text-sm">Plataforma B2B de Medicamentos</p>
        </div>

        {/* Tabs */}
        <div className="flex border-b border-gray-100 p-2 bg-white">
          <button
            onClick={() => setActiveTab('login')}
            className={`flex-1 rounded-lg py-2 text-sm font-medium transition-colors ${activeTab === 'login' ? 'bg-white text-blue-600 shadow-sm border border-gray-100' : 'text-gray-500 hover:text-gray-700'
              }`}
          >
            Entrar
          </button>
          <button
            onClick={() => setActiveTab('register')}
            className={`flex-1 rounded-lg py-2 text-sm font-medium transition-colors ${activeTab === 'register' ? 'bg-white text-blue-600 shadow-sm border border-gray-100' : 'text-gray-500 hover:text-gray-700'
              }`}
          >
            Cadastrar
          </button>
        </div>

        {/* Login Form */}
        {activeTab === 'login' ? (
          <form onSubmit={onSubmit} className="p-8 space-y-5">
            {errorMessage && (
              <div className="flex items-center gap-2 rounded-lg bg-red-50 px-4 py-3 text-sm text-red-600 border border-red-100">
                <svg className="h-5 w-5 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                <span>Ops! Não encontramos esse login. Verifique seu e-mail/usuário e senha.</span>
              </div>
            )}

            <div className="space-y-1.5">
              <label className="text-sm font-medium text-gray-700 ml-1">Email ou Usuário</label>
              <div className="relative">
                <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none text-gray-400">
                  <span className="text-lg">@</span>
                </div>
                <input
                  id="username"
                  name="username"
                  autoComplete="username"
                  placeholder="seu@email.com"
                  className="w-full rounded-xl border border-gray-200 py-2.5 pl-10 pr-3 text-gray-800 placeholder-gray-400 focus:border-blue-500 focus:ring-2 focus:ring-blue-100 transition-all outline-none"
                  value={username}
                  onChange={(e) => setUsername(e.target.value)}
                />
              </div>
            </div>

            <div className="space-y-1.5">
              <label className="text-sm font-medium text-gray-700 ml-1">Senha</label>
              <div className="relative">
                <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none text-gray-400">
                  <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" /></svg>
                </div>
                <input
                  id="password"
                  name="password"
                  type={showPassword ? "text" : "password"}
                  autoComplete="current-password"
                  placeholder="••••••••"
                  className="w-full rounded-xl border border-gray-200 py-2.5 pl-10 pr-10 text-gray-800 placeholder-gray-400 focus:border-blue-500 focus:ring-2 focus:ring-blue-100 transition-all outline-none"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                />
                <button
                  type="button"
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 focus:outline-none transition-colors"
                  onClick={() => setShowPassword(!showPassword)}
                >
                  {showPassword ? <EyeSlashIcon /> : <EyeIcon />}
                </button>
              </div>
            </div>

            <div className="pt-2">
              <button
                type="submit"
                className="w-full rounded-xl bg-slate-600 py-3 font-semibold text-white shadow-lg shadow-slate-200 hover:bg-slate-700 hover:shadow-xl active:translate-y-0.5 focus:ring-2 focus:ring-slate-200 transition-all disabled:opacity-70 flex items-center justify-center gap-2"
                disabled={loading}
              >
                {loading ? (
                  <>
                    <svg className="animate-spin h-5 w-5 text-white" 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...
                  </>
                ) : (
                  <>
                    <svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 16l-4-4m0 0l4-4m-4 4h14m-5 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h7a3 3 0 013 3v1" /></svg>
                    Entrar
                  </>
                )}
              </button>
            </div>
          </form>
        ) : (
          <div className="p-8 text-center text-gray-500 py-12">
            <p>Funcionalidade de cadastro em breve.</p>
            <button
              onClick={() => setActiveTab('login')}
              className="mt-4 text-blue-600 hover:underline text-sm"
            >
              Voltar para login
            </button>
          </div>
        )}

      </div>
    </div>
  )
}
