<template>
  <div class="login-container">
    <div class="login-card">

      <div class="login-header">
        <div class="logo">
          <img src="/logotiny.png" alt="Logo" />
        </div>
        <h2>{{ isRegister ? 'Crear Cuenta' : 'Iniciar Sesión' }}</h2>
        <p class="subtitle">
          {{ isRegister 
            ? 'Complete el formulario para registrarse' 
            : 'Ingrese sus credenciales para continuar' 
          }}
        </p>
      </div>

      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        @finish="handleSubmit"
        layout="vertical"
        class="login-form"
      >

<a-form-item v-if="isRegister" label="Nombre completo" name="name">
  <a-input
    v-model:value="formState.name"
    placeholder="Ingrese su nombre"
    size="large"
    autocomplete="name"
  >
    <template #prefix>
      <UserOutlined />
    </template>
  </a-input>
</a-form-item>


<a-form-item label="Correo electrónico" name="email">
  <a-input
    v-model:value="formState.email"
    placeholder="ejemplo@correo.com"
    size="large"
    autocomplete="email"
  >
    <template #prefix>
      <MailOutlined />
    </template>
  </a-input>
</a-form-item>


<a-form-item label="Contraseña" name="password">
  <a-input-password
    v-model:value="formState.password"
    placeholder="Ingrese su contraseña"
    size="large"
    autocomplete="current-password"
  >
    <template #prefix>
      <LockOutlined />
    </template>
  </a-input-password>
</a-form-item>


<a-form-item v-if="isRegister" label="Confirmar contraseña" name="password_confirmation">
  <a-input-password
    v-model:value="formState.password_confirmation"
    placeholder="Confirme su contraseña"
    size="large"
    autocomplete="new-password"
  >
    <template #prefix>
      <LockOutlined />
    </template>
  </a-input-password>
</a-form-item>


        <div v-if="!isRegister" class="remember-forgot">
          <a-checkbox v-model:checked="rememberMe">
            Recordarme
          </a-checkbox>
          <a-button type="link" size="small" @click="handleForgotPassword">
            ¿Olvidó su contraseña?
          </a-button>
        </div>

        <a-form-item>
          <a-button
            type="primary"
            html-type="submit"
            :loading="loading"
            block
            size="large"
            class="submit-btn"
          >
            {{ isRegister ? 'Registrarse' : 'Iniciar Sesión' }}
          </a-button>
        </a-form-item>

        <div class="toggle-mode">
          <span>
            {{ isRegister 
              ? '¿Ya tiene una cuenta?' 
              : '¿No tiene una cuenta?' 
            }}
          </span>
          <a-button type="link" @click="toggleMode">
            {{ isRegister ? 'Iniciar sesión' : 'Registrarse' }}
          </a-button>
        </div>

        <div v-if="isRegister" class="terms">
          <p>
            Al registrarse, acepta nuestros 
            <a href="#">Términos</a> y 
            <a href="#">Política de privacidad</a>
          </p>
        </div>
      </a-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../store/user'
import { UserOutlined, MailOutlined, LockOutlined } from '@ant-design/icons-vue'
import { notification } from 'ant-design-vue'

const router = useRouter()
const userStore = useUserStore()
const formRef = ref()

const isRegister = ref(false)
const loading = ref(false)
const rememberMe = ref(false)

const formState = reactive({
  name: '',
  email: '',
  password: '',
  password_confirmation: ''
})

notification.config({
  placement: 'top',
  duration: 2,
  maxCount: 1,
})


const showToast = (type, message, description = '') => {
  const config = {
    message,
    description,
    duration: 2, 
    placement: 'top',
  }

  switch (type) {
    case 'success':
      notification.success(config)
      break
    case 'error':
      notification.error(config)
      break
    case 'warning':
      notification.warning(config)
      break
    case 'info':
      notification.info(config)
      break
    default:
      notification.open(config)
  }
}

const rules = {
  name: [
    { 
      required: isRegister.value, 
      message: 'Ingrese su nombre',
      trigger: 'blur' 
    }
  ],
  email: [
    { 
      required: true, 
      message: 'Ingrese su correo',
      trigger: 'blur' 
    },
    { 
      type: 'email', 
      message: 'Correo inválido',
      trigger: 'blur' 
    }
  ],
  password: [
    { 
      required: true, 
      message: 'Ingrese su contraseña',
      trigger: 'blur' 
    },
    { 
      min: 6, 
      message: 'Mínimo 6 caracteres',
      trigger: 'blur' 
    }
  ],
  password_confirmation: [
    { 
      required: isRegister.value, 
      message: 'Confirme su contraseña',
      trigger: 'blur' 
    },
    ({ getFieldValue }) => ({
      validator(_, value) {
        if (!value || getFieldValue('password') === value) {
          return Promise.resolve()
        }
        return Promise.reject('Las contraseñas no coinciden')
      }
    })
  ]
}

const toggleMode = () => {
  isRegister.value = !isRegister.value
  formRef.value?.resetFields()
}

const handleForgotPassword = () => {
  showToast('info', 'Recuperación de contraseña', 'Contacte al administrador del sistema')
}

const handleSubmit = async () => {
  try {
    loading.value = true
    
    if (isRegister.value) {
      await userStore.register(formState)
      showToast('success', 
        '¡Registro exitoso!', 
        'Tu cuenta ha sido creada correctamente'
      )
      toggleMode() 
    } else {
      await userStore.login(formState.email, formState.password)
      showToast('success', '¡Bienvenido!', 'Inicio de sesión exitoso')
    }
  } catch (error) {
    console.error('Error:', error)
    

    let errorMessage = 'Ocurrió un error inesperado'
    let errorDetails = ''
    
    if (error.response) {
      const status = error.response.status
      const data = error.response.data
      
      switch (status) {
        case 400:
          errorMessage = 'Error en la solicitud'
          if (data.errors) {
            const firstError = Object.values(data.errors)[0]
            errorDetails = Array.isArray(firstError) ? firstError[0] : firstError
          } else if (data.message) {
            errorDetails = data.message
          }
          break
        case 401:
          errorMessage = 'Credenciales incorrectas'
          errorDetails = 'Verifique su correo electrónico y contraseña'
          break
        case 403:
          errorMessage = 'Acceso denegado'
          errorDetails = 'No tiene permisos para acceder'
          break
        case 422:
          errorMessage = 'Error de validación'
          if (data.errors) {
            const firstError = Object.values(data.errors)[0]
            errorDetails = Array.isArray(firstError) ? firstError[0] : firstError
          } else if (data.message) {
            errorDetails = data.message
          }
          break
        case 500:
          errorMessage = 'Error del servidor'
          errorDetails = 'Por favor, intente más tarde'
          break
        default:
          errorMessage = `Error ${status}`
          if (data.message) {
            errorDetails = data.message
          }
      }
    } else if (error.message) {
      errorMessage = 'Error de conexión'
      errorDetails = 'Verifique su conexión a internet'
    }
    

    showToast('error', errorMessage, errorDetails)
    
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  background-color: #f8f9fa;
  position: relative;
}

.login-card {
  width: 100%;
  max-width: 420px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  padding: 40px;
  z-index: 1;
}

.login-header {
  text-align: center;
  margin-bottom: 32px;
}

.logo {
  margin-bottom: 16px;
}

.logo img {
  height: 48px;
  width: auto;
}

.login-header h2 {
  margin: 0 0 8px 0;
  color: #262626;
  font-weight: 500;
}

.subtitle {
  margin: 0;
  color: #8c8c8c;
  font-size: 14px;
}

.login-form {
  margin-bottom: 16px;
}

.remember-forgot {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.submit-btn {
  height: 44px;
  font-weight: 500;
  margin-top: 8px;
}

.toggle-mode {
  text-align: center;
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #f0f0f0;
  color: #595959;
  font-size: 14px;
}

.toggle-mode span {
  margin-right: 8px;
}

.terms {
  margin-top: 24px;
  text-align: center;
  font-size: 12px;
  color: #8c8c8c;
}

.terms a {
  color: #1890ff;
  text-decoration: none;
}

.terms a:hover {
  text-decoration: underline;
}

@media (max-width: 480px) {
  .login-card {
    padding: 24px;
    box-shadow: none;
    border: 1px solid #f0f0f0;
  }
  
  .remember-forgot {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
}
</style>