<template>
  <div class="min-h-screen bg-gradient-to-br from-orange-50 to-orange-100 flex items-center justify-center p-4">
    <div class="bg-white p-8 rounded-2xl shadow-2xl w-full max-w-md relative">
      <!-- Close Button -->
      <button @click="$router.push('/')" class="absolute top-4 right-4 text-gray-400 hover:text-gray-600 transition">
        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
        </svg>
      </button>

      <!-- Logo & Title -->
      <div class="text-center mb-8">
        <div class="text-5xl mb-3">🍔</div>
        <h1 class="text-3xl font-bold text-gray-800 mb-2">Welcome Back!</h1>
        <p class="text-gray-600">Login to order delicious food</p>
      </div>

      <!-- Error Message -->
      <div v-if="error" class="mb-4 p-4 bg-red-50 border border-red-200 rounded-lg">
        <div class="flex items-center gap-2 text-red-700">
          <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
            <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"/>
          </svg>
          <span class="text-sm font-medium">{{ error }}</span>
        </div>
      </div>

      <!-- Success Message -->
      <div v-if="success" class="mb-4 p-4 bg-green-50 border border-green-200 rounded-lg">
        <div class="flex items-center gap-2 text-green-700">
          <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
            <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"/>
          </svg>
          <span class="text-sm font-medium">{{ success }}</span>
        </div>
      </div>
      
      <form @submit.prevent="handleLogin">
        <div class="mb-4">
          <label class="block text-gray-700 mb-2 font-medium">Email Address</label>
          <div class="relative">
            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
              <svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 12a4 4 0 10-8 0 4 4 0 008 0zm0 0v1.5a2.5 2.5 0 005 0V12a9 9 0 10-9 9m4.5-1.206a8.959 8.959 0 01-4.5 1.207"/>
              </svg>
            </div>
            <input v-model="form.email" type="email" required :disabled="loading" placeholder="your@email.com" class="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500 focus:border-transparent transition disabled:bg-gray-100">
          </div>
        </div>

        <div class="mb-6">
          <label class="block text-gray-700 mb-2 font-medium">Password</label>
          <div class="relative">
            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
              <svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="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 v-model="form.password" :type="showPassword ? 'text' : 'password'" required :disabled="loading" placeholder="Enter your password" class="w-full pl-10 pr-12 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500 focus:border-transparent transition disabled:bg-gray-100">
            <button @click="showPassword = !showPassword" type="button" class="absolute inset-y-0 right-0 pr-3 flex items-center">
              <svg v-if="!showPassword" class="w-5 h-5 text-gray-400 hover:text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="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>
              <svg v-else class="w-5 h-5 text-gray-400 hover:text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="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>
            </button>
          </div>
        </div>

        <div class="flex items-center justify-between mb-6">
          <label class="flex items-center">
            <input type="checkbox" v-model="rememberMe" class="w-4 h-4 text-orange-600 border-gray-300 rounded focus:ring-orange-500">
            <span class="ml-2 text-sm text-gray-600">Remember me</span>
          </label>
          <button @click="showForgotPassword = true" type="button" class="text-sm text-orange-600 hover:underline">Forgot password?</button>
        </div>

        <button type="submit" :disabled="loading" class="w-full bg-gradient-to-r from-orange-500 to-orange-600 text-white py-3 rounded-lg font-semibold hover:from-orange-600 hover:to-orange-700 transition shadow-lg hover:shadow-xl disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2">
          <svg v-if="loading" class="animate-spin h-5 w-5 text-white" fill="none" viewBox="0 0 24 24">
            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
            <path class="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>
          <span>{{ loading ? 'Logging in...' : 'Login' }}</span>
        </button>
      </form>

      <div class="mt-6 text-center">
        <p class="text-gray-600">
          Don't have an account? 
          <router-link to="/register" class="text-orange-600 font-semibold hover:underline">Sign up now</router-link>
        </p>
      </div>
    </div>

    <!-- Forgot Password Modal -->
    <div v-if="showForgotPassword" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4" @click.self="closeForgotPassword">
      <div class="bg-white rounded-2xl max-w-md w-full p-8 relative">
        <button @click="closeForgotPassword" class="absolute top-4 right-4 text-gray-400 hover:text-gray-600 transition">
          <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
          </svg>
        </button>

        <div class="text-center mb-6">
          <div class="text-5xl mb-3">🔐</div>
          <h2 class="text-2xl font-bold text-gray-800 mb-2">Reset Password</h2>
          <p class="text-gray-600 text-sm">Enter your email or phone number to receive a reset code</p>
        </div>

        <div v-if="forgotPasswordError" class="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm">
          {{ forgotPasswordError }}
        </div>

        <div v-if="forgotPasswordSuccess" class="mb-4 p-3 bg-green-50 border border-green-200 rounded-lg text-green-700 text-sm">
          {{ forgotPasswordSuccess }}
        </div>

        <form @submit.prevent="handleForgotPassword" v-if="!resetCodeSent">
          <div class="mb-4">
            <label class="block text-gray-700 mb-2 font-medium text-sm">Email or Phone Number</label>
            <input v-model="forgotPasswordIdentifier" type="text" required placeholder="email@example.com or 0771234567" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500 focus:border-transparent">
          </div>

          <button type="submit" :disabled="forgotPasswordLoading" class="w-full bg-gradient-to-r from-orange-500 to-orange-600 text-white py-3 rounded-lg font-semibold hover:from-orange-600 hover:to-orange-700 transition disabled:opacity-50 flex items-center justify-center gap-2">
            <svg v-if="forgotPasswordLoading" class="animate-spin h-5 w-5 text-white" fill="none" viewBox="0 0 24 24">
              <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
              <path class="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>
            <span>{{ forgotPasswordLoading ? 'Sending...' : 'Send Reset Code' }}</span>
          </button>
        </form>

        <form @submit.prevent="handleResetPassword" v-else>
          <div class="mb-4">
            <label class="block text-gray-700 mb-2 font-medium text-sm">Reset Code</label>
            <input v-model="resetCode" type="text" required placeholder="Enter 6-digit code" maxlength="6" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500 focus:border-transparent text-center text-2xl tracking-widest">
          </div>

          <div class="mb-4">
            <label class="block text-gray-700 mb-2 font-medium text-sm">New Password</label>
            <input v-model="newPassword" type="password" required placeholder="Enter new password" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500 focus:border-transparent">
          </div>

          <div class="mb-6">
            <label class="block text-gray-700 mb-2 font-medium text-sm">Confirm Password</label>
            <input v-model="confirmPassword" type="password" required placeholder="Confirm new password" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500 focus:border-transparent">
          </div>

          <button type="submit" :disabled="forgotPasswordLoading" class="w-full bg-gradient-to-r from-orange-500 to-orange-600 text-white py-3 rounded-lg font-semibold hover:from-orange-600 hover:to-orange-700 transition disabled:opacity-50 flex items-center justify-center gap-2">
            <svg v-if="forgotPasswordLoading" class="animate-spin h-5 w-5 text-white" fill="none" viewBox="0 0 24 24">
              <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
              <path class="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>
            <span>{{ forgotPasswordLoading ? 'Resetting...' : 'Reset Password' }}</span>
          </button>

          <button @click="resetCodeSent = false" type="button" class="w-full mt-3 text-orange-600 text-sm hover:underline">
            ← Back to send code
          </button>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { useAuthStore } from '../../stores/auth';

const router = useRouter();
const authStore = useAuthStore();

const form = reactive({
  email: '',
  password: '',
});

const loading = ref(false);
const error = ref('');
const success = ref('');
const showPassword = ref(false);
const rememberMe = ref(false);

const showForgotPassword = ref(false);
const forgotPasswordIdentifier = ref('');
const forgotPasswordLoading = ref(false);
const forgotPasswordError = ref('');
const forgotPasswordSuccess = ref('');
const resetCodeSent = ref(false);
const resetCode = ref('');
const newPassword = ref('');
const confirmPassword = ref('');

const closeForgotPassword = () => {
  showForgotPassword.value = false;
  forgotPasswordIdentifier.value = '';
  forgotPasswordError.value = '';
  forgotPasswordSuccess.value = '';
  resetCodeSent.value = false;
  resetCode.value = '';
  newPassword.value = '';
  confirmPassword.value = '';
};

const handleForgotPassword = async () => {
  forgotPasswordError.value = '';
  forgotPasswordSuccess.value = '';
  forgotPasswordLoading.value = true;

  try {
    const response = await authStore.forgotPassword(forgotPasswordIdentifier.value);
    forgotPasswordSuccess.value = 'Reset code sent successfully! Check your email or phone.';
    resetCodeSent.value = true;
  } catch (err) {
    forgotPasswordError.value = err.response?.data?.message || 'Failed to send reset code. Please try again.';
  } finally {
    forgotPasswordLoading.value = false;
  }
};

const handleResetPassword = async () => {
  if (newPassword.value !== confirmPassword.value) {
    forgotPasswordError.value = 'Passwords do not match!';
    return;
  }

  if (newPassword.value.length < 6) {
    forgotPasswordError.value = 'Password must be at least 6 characters!';
    return;
  }

  forgotPasswordError.value = '';
  forgotPasswordSuccess.value = '';
  forgotPasswordLoading.value = true;

  try {
    await authStore.resetPassword({
      identifier: forgotPasswordIdentifier.value,
      code: resetCode.value,
      password: newPassword.value
    });
    forgotPasswordSuccess.value = 'Password reset successful! You can now login.';
    setTimeout(() => {
      closeForgotPassword();
    }, 2000);
  } catch (err) {
    forgotPasswordError.value = err.response?.data?.message || 'Failed to reset password. Please check your code.';
  } finally {
    forgotPasswordLoading.value = false;
  }
};

const handleLogin = async () => {
  if (loading.value) return;
  
  error.value = '';
  success.value = '';
  loading.value = true;

  try {
    await authStore.login(form);
    
    success.value = 'Login successful! Redirecting...';
    
    // Wait a bit to show success message
    setTimeout(() => {
      // Redirect based on role
      const role = authStore.userRole;
      console.log('User role:', role);
      if (role === 'super-admin') {
        router.push('/super-admin');
      } else if (role === 'admin') {
        router.push('/admin/dashboard');
      } else if (role === 'manager') {
        router.push('/manager');
      } else if (role === 'delivery-boy' || role === 'delivery_boy') {
        window.location.href = '/delivery-boy';
      } else {
        router.push('/');
      }
    }, 1000);
  } catch (err) {
    console.error('Login error:', err);
    error.value = err.response?.data?.message || 'Login failed. Please check your credentials and try again.';
    loading.value = false;
  }
};
</script>
