import { FormEvent, useState } from 'react'
import { useNavigate, Link } from 'react-router-dom'
import axios from 'axios'
import { useAuth, UserRole } from '@/context/AuthContext'
import { authService } from '@/services/auth'
import { formatCNPJ, validateCNPJ } from '@/utils/cnpj'
import { decodeJwtPayload } from '@/utils/jwt'
import logoImg from '@/assets/logo.png'

interface RegistrationFormData {
  email: string
  username: string
  password: string
  passwordConfirm: string
  name: string
  company_name: string
  cnpj: string
}

export function RegisterPage() {
  const navigate = useNavigate()
  const { login } = useAuth()
  const [formData, setFormData] = useState<RegistrationFormData>({
    email: '',
    username: '',
    password: '',
    passwordConfirm: '',
    name: '',
    company_name: '',
    cnpj: '',
  })
  const [showPassword, setShowPassword] = useState(false)
  const [showPasswordConfirm, setShowPasswordConfirm] = useState(false)
  const [loading, setLoading] = useState(false)
  const [errorMessage, setErrorMessage] = useState<string | null>(null)
  const [validationErrors, setValidationErrors] = useState<Record<string, string>>({})

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target

    if (name === 'cnpj') {
      setFormData({
        ...formData,
        [name]: formatCNPJ(value),
      })
    } else {
      setFormData({
        ...formData,
        [name]: value,
      })
    }

    // Clear validation error for this field
    if (validationErrors[name]) {
      setValidationErrors({
        ...validationErrors,
        [name]: '',
      })
    }
  }

  const validateForm = (): boolean => {
    const errors: Record<string, string> = {}

    if (!formData.email) errors.email = 'E-mail é obrigatório'
    if (!formData.email.includes('@')) errors.email = 'E-mail inválido'

    if (!formData.username) errors.username = 'Usuário é obrigatório'
    if (formData.username.length < 3) errors.username = 'Usuário deve ter pelo menos 3 caracteres'

    if (!formData.password) errors.password = 'Senha é obrigatória'
    if (formData.password.length < 8) errors.password = 'Senha deve ter pelo menos 8 caracteres'

    if (formData.password !== formData.passwordConfirm) errors.passwordConfirm = 'As senhas não correspondem'

    if (!formData.name) errors.name = 'Nome é obrigatório'
    if (formData.name.length < 3) errors.name = 'Nome deve ter pelo menos 3 caracteres'

    if (!formData.company_name) errors.company_name = 'Razão Social é obrigatória'

    if (!formData.cnpj) {
      errors.cnpj = 'CNPJ é obrigatório'
    } else if (formData.cnpj.replace(/\D/g, '').length !== 14) {
      errors.cnpj = 'CNPJ deve ter 14 dígitos'
    } else if (!validateCNPJ(formData.cnpj)) {
      errors.cnpj = 'CNPJ inválido. Verifique o dígito verificador'
    }

    setValidationErrors(errors)
    return Object.keys(errors).length === 0
  }

  const resolveRole = (role?: string): UserRole => {
    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()
    
    if (!validateForm()) {
      setErrorMessage('Por favor, corrija os erros no formulário.')
      return
    }

    setLoading(true)
    setErrorMessage(null)

    try {
      const response = await authService.register({
        email: formData.email,
        username: formData.username,
        password: formData.password,
        name: formData.name,
        company_name: formData.company_name,
        cnpj: formData.cnpj.replace(/\D/g, ''),
      })

      // Auto login after successful registration
      const { token } = response
      if (!token) throw new Error('Resposta de registro inválida.')

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

      // Login automatically and redirect to dashboard
      login(token, role, formData.name, payload?.sub || '', payload?.company_id, formData.email, formData.username)
    } catch (error) {
      const fallback = 'Não foi possível criar a conta. Tente novamente.'
      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-[500px] 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">Criar Nova Conta</p>
        </div>

        {/* Form Content */}
        <form onSubmit={onSubmit} className="p-8 space-y-4">
          {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>{errorMessage}</span>
            </div>
          )}

          {/* Personal Information */}
          <div className="border-b border-gray-200 pb-4">
            <h3 className="text-sm font-semibold text-gray-700 mb-3">Informações Pessoais</h3>
            
            <div className="space-y-3">
              <div>
                <label className="text-sm font-medium text-gray-700 ml-1">Nome Completo *</label>
                <input
                  type="text"
                  name="name"
                  placeholder="João Silva"
                  className={`w-full rounded-lg border py-2.5 px-3 text-gray-800 placeholder-gray-400 focus:ring-2 focus:ring-blue-100 transition-all outline-none ${
                    validationErrors.name ? 'border-red-500 focus:border-red-500' : 'border-gray-200 focus:border-blue-500'
                  }`}
                  value={formData.name}
                  onChange={handleChange}
                />
                {validationErrors.name && <p className="text-xs text-red-600 mt-1">{validationErrors.name}</p>}
              </div>

              <div>
                <label className="text-sm font-medium text-gray-700 ml-1">Email *</label>
                <input
                  type="email"
                  name="email"
                  placeholder="seu@email.com"
                  className={`w-full rounded-lg border py-2.5 px-3 text-gray-800 placeholder-gray-400 focus:ring-2 focus:ring-blue-100 transition-all outline-none ${
                    validationErrors.email ? 'border-red-500 focus:border-red-500' : 'border-gray-200 focus:border-blue-500'
                  }`}
                  value={formData.email}
                  onChange={handleChange}
                />
                {validationErrors.email && <p className="text-xs text-red-600 mt-1">{validationErrors.email}</p>}
              </div>

              <div>
                <label className="text-sm font-medium text-gray-700 ml-1">Usuário *</label>
                <input
                  type="text"
                  name="username"
                  placeholder="joaosilva"
                  className={`w-full rounded-lg border py-2.5 px-3 text-gray-800 placeholder-gray-400 focus:ring-2 focus:ring-blue-100 transition-all outline-none ${
                    validationErrors.username ? 'border-red-500 focus:border-red-500' : 'border-gray-200 focus:border-blue-500'
                  }`}
                  value={formData.username}
                  onChange={handleChange}
                />
                {validationErrors.username && <p className="text-xs text-red-600 mt-1">{validationErrors.username}</p>}
              </div>
            </div>
          </div>

          {/* Company Information */}
          <div className="border-b border-gray-200 pb-4">
            <h3 className="text-sm font-semibold text-gray-700 mb-3">Informações da Empresa</h3>
            
            <div className="space-y-3">
              <div>
                <label className="text-sm font-medium text-gray-700 ml-1">Razão Social *</label>
                <input
                  type="text"
                  name="company_name"
                  placeholder="Farmácia Central LTDA"
                  className={`w-full rounded-lg border py-2.5 px-3 text-gray-800 placeholder-gray-400 focus:ring-2 focus:ring-blue-100 transition-all outline-none ${
                    validationErrors.company_name ? 'border-red-500 focus:border-red-500' : 'border-gray-200 focus:border-blue-500'
                  }`}
                  value={formData.company_name}
                  onChange={handleChange}
                />
                {validationErrors.company_name && <p className="text-xs text-red-600 mt-1">{validationErrors.company_name}</p>}
              </div>

              <div>
                <label className="text-sm font-medium text-gray-700 ml-1">CNPJ (Formatação esperada: 00.000.000/0000-00) *</label>
                <input
                  type="text"
                  name="cnpj"
                  placeholder="00.000.000/0000-00"
                  maxLength={18}
                  className={`w-full rounded-lg border py-2.5 px-3 text-gray-800 placeholder-gray-400 focus:ring-2 focus:ring-blue-100 transition-all outline-none font-mono ${
                    validationErrors.cnpj ? 'border-red-500 focus:border-red-500' : 'border-gray-200 focus:border-blue-500'
                  }`}
                  value={formData.cnpj}
                  onChange={handleChange}
                />
                {validationErrors.cnpj && <p className="text-xs text-red-600 mt-1">{validationErrors.cnpj}</p>}
              </div>
            </div>
          </div>

          {/* Password Information */}
          <div className="pb-4">
            <h3 className="text-sm font-semibold text-gray-700 mb-3">Definir Senha</h3>
            
            <div className="space-y-3">
              <div>
                <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
                    type={showPassword ? "text" : "password"}
                    name="password"
                    placeholder="••••••••"
                    className={`w-full rounded-lg border py-2.5 pl-10 pr-10 text-gray-800 placeholder-gray-400 focus:ring-2 focus:ring-blue-100 transition-all outline-none ${
                      validationErrors.password ? 'border-red-500 focus:border-red-500' : 'border-gray-200 focus:border-blue-500'
                    }`}
                    value={formData.password}
                    onChange={handleChange}
                  />
                  <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 ? (
                      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} 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>
                    ) : (
                      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} 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" /></svg>
                    )}
                  </button>
                </div>
                {validationErrors.password && <p className="text-xs text-red-600 mt-1">{validationErrors.password}</p>}
              </div>

              <div>
                <label className="text-sm font-medium text-gray-700 ml-1">Confirmar 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
                    type={showPasswordConfirm ? "text" : "password"}
                    name="passwordConfirm"
                    placeholder="••••••••"
                    className={`w-full rounded-lg border py-2.5 pl-10 pr-10 text-gray-800 placeholder-gray-400 focus:ring-2 focus:ring-blue-100 transition-all outline-none ${
                      validationErrors.passwordConfirm ? 'border-red-500 focus:border-red-500' : 'border-gray-200 focus:border-blue-500'
                    }`}
                    value={formData.passwordConfirm}
                    onChange={handleChange}
                  />
                  <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={() => setShowPasswordConfirm(!showPasswordConfirm)}
                  >
                    {showPasswordConfirm ? (
                      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} 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>
                    ) : (
                      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} 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" /></svg>
                    )}
                  </button>
                </div>
                {validationErrors.passwordConfirm && <p className="text-xs text-red-600 mt-1">{validationErrors.passwordConfirm}</p>}
              </div>
            </div>
          </div>

          <div className="pt-4">
            <button
              type="submit"
              className="w-full rounded-xl bg-blue-600 py-3 font-semibold text-white shadow-lg shadow-blue-200 hover:bg-blue-700 hover:shadow-xl active:translate-y-0.5 focus:ring-2 focus:ring-blue-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>
                  Criando conta...
                </>
              ) : (
                <>
                  <svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z" /></svg>
                  Criar Conta
                </>
              )}
            </button>
          </div>

          <div className="text-center">
            <p className="text-sm text-gray-600">
              Já tenho uma conta{' '}
              <Link to="/login" className="text-blue-600 hover:underline font-medium">
                Entrar
              </Link>
            </p>
          </div>
        </form>
      </div>
    </div>
  )
}
