'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import toast from 'react-hot-toast';
import { ArrowLeft, LogIn, Store, Lock, Eye, EyeOff, Gift, KeyRound } from 'lucide-react';
import outletApi from '@/lib/outlet-axios';
import { useOutletAuthStore } from '@/store/outlet-auth';

const loginSchema = z.object({
  customer_code_bmu: z.string().min(1, 'Kode Customer BMU wajib diisi'),
  password: z.string().min(6, 'Password minimal 6 karakter'),
});
type LoginData = z.infer<typeof loginSchema>;

const changePasswordSchema = z.object({
  current_password: z.string().min(1, 'Password saat ini wajib diisi'),
  new_password: z.string().min(6, 'Password minimal 6 karakter'),
  new_password_confirmation: z.string().min(6, 'Konfirmasi password wajib diisi'),
}).refine((d) => d.new_password === d.new_password_confirmation, {
  message: 'Konfirmasi password tidak cocok',
  path: ['new_password_confirmation'],
});
type ChangePasswordData = z.infer<typeof changePasswordSchema>;

export default function OutletLoginPage() {
  const router = useRouter();
  const setAuth = useOutletAuthStore((s) => s.setAuth);

  const [loading, setLoading] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [showCurrent, setShowCurrent] = useState(false);
  const [showNew, setShowNew] = useState(false);
  const [showConfirm, setShowConfirm] = useState(false);

  // When require_password_change, store the customer_code_bmu here
  const [pendingCode, setPendingCode] = useState<string | null>(null);

  const loginForm = useForm<LoginData>({ resolver: zodResolver(loginSchema) });
  const cpForm = useForm<ChangePasswordData>({ resolver: zodResolver(changePasswordSchema) });

  const onLogin = async (data: LoginData) => {
    setLoading(true);
    try {
      const res = await outletApi.post('/outlet/login', data);

      if (res.data.status === 'require_password_change') {
        setPendingCode(res.data.customer_code_bmu);
        toast('Silakan ganti password Anda terlebih dahulu.', { icon: '🔑' });
        return;
      }

      setAuth(res.data.data, res.data.token);
      toast.success('Login berhasil!');
      router.push('/outlet/dashboard');
    } catch (err: any) {
      toast.error(err.response?.data?.message ?? 'Login gagal');
    } finally {
      setLoading(false);
    }
  };

  const onChangePassword = async (data: ChangePasswordData) => {
    setLoading(true);
    try {
      await outletApi.post('/outlet/first-time-change-password', {
        customer_code_bmu: pendingCode,
        current_password: data.current_password,
        new_password: data.new_password,
        new_password_confirmation: data.new_password_confirmation,
      });
      toast.success('Password berhasil diubah. Silakan login kembali.');
      setPendingCode(null);
      cpForm.reset();
      loginForm.reset();
    } catch (err: any) {
      toast.error(err.response?.data?.message ?? 'Gagal mengganti password');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen gradient-bmu-light">

      {/* Header */}
      <header className="sticky top-0 z-50 glass-card">
        <div className="max-w-6xl mx-auto px-4 py-4 flex items-center justify-between">
          <Link
            href="/"
            className="flex items-center gap-2 text-gray-500 hover:text-gray-800 transition-colors"
          >
            <ArrowLeft className="h-5 w-5" />
            <span className="hidden sm:inline text-sm font-medium">Kembali</span>
          </Link>
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 gradient-bmu rounded-lg flex items-center justify-center">
              <Gift className="w-4 h-4 text-white" />
            </div>
            <span className="font-bold text-gradient-bmu">Bonus-MU</span>
          </div>
          <div className="w-20" />
        </div>
      </header>

      {/* Main */}
      <main className="max-w-6xl mx-auto px-4 py-10 md:py-16">
        <div className="mx-auto max-w-md">

          {/* ── LOGIN FORM ── */}
          {!pendingCode && (
            <div className="rounded-3xl bg-white p-6 md:p-8 shadow-bmu animate-slide-up">
              <div className="text-center mb-8">
                <div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full gradient-bmu">
                  <Store className="h-8 w-8 text-white" />
                </div>
                <h1 className="text-2xl font-bold text-gray-900">Portal Outlet</h1>
                <p className="mt-2 text-sm text-gray-500">Masuk dengan Kode Customer BMU Anda</p>
              </div>

              <form onSubmit={loginForm.handleSubmit(onLogin)} className="space-y-5">
                <div className="space-y-1.5">
                  <label className="flex items-center gap-2 text-sm font-medium text-gray-700">
                    <Store className="h-4 w-4 text-sky-600" />
                    Kode Customer BMU
                  </label>
                  <input
                    {...loginForm.register('customer_code_bmu')}
                    type="text"
                    placeholder="Masukkan kode customer BMU"
                    className="w-full h-12 border border-gray-200 rounded-xl px-4 text-sm focus:outline-none focus:ring-2 focus:ring-sky-500 focus:border-transparent transition"
                  />
                  {loginForm.formState.errors.customer_code_bmu && (
                    <p className="text-red-500 text-xs mt-1">{loginForm.formState.errors.customer_code_bmu.message}</p>
                  )}
                </div>

                <div className="space-y-1.5">
                  <label className="flex items-center gap-2 text-sm font-medium text-gray-700">
                    <Lock className="h-4 w-4 text-sky-600" />
                    Password
                  </label>
                  <div className="relative">
                    <input
                      {...loginForm.register('password')}
                      type={showPassword ? 'text' : 'password'}
                      placeholder="Masukkan password"
                      className="w-full h-12 border border-gray-200 rounded-xl px-4 pr-12 text-sm focus:outline-none focus:ring-2 focus:ring-sky-500 focus:border-transparent transition"
                    />
                    <button
                      type="button"
                      onClick={() => setShowPassword(!showPassword)}
                      className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 transition-colors"
                    >
                      {showPassword ? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}
                    </button>
                  </div>
                  {loginForm.formState.errors.password && (
                    <p className="text-red-500 text-xs mt-1">{loginForm.formState.errors.password.message}</p>
                  )}
                </div>

                <button
                  type="submit"
                  disabled={loading}
                  className="w-full h-12 gradient-bmu text-white font-semibold rounded-xl shadow-bmu hover:opacity-90 transition disabled:opacity-60 flex items-center justify-center gap-2"
                >
                  {loading ? (
                    <>
                      <span className="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent" />
                      Memproses...
                    </>
                  ) : (
                    <>
                      <LogIn className="h-5 w-5" />
                      Masuk
                    </>
                  )}
                </button>
              </form>

              <div className="mt-6 text-center">
                <p className="text-xs text-gray-400">Akun outlet diberikan oleh administrator BMU.</p>
                <p className="text-xs text-gray-400 mt-1">Hubungi admin jika mengalami kendala login.</p>
              </div>
            </div>
          )}

          {/* ── FIRST-TIME CHANGE PASSWORD FORM ── */}
          {pendingCode && (
            <div className="rounded-3xl bg-white p-6 md:p-8 shadow-bmu animate-slide-up">
              <div className="text-center mb-8">
                <div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full gradient-bmu">
                  <KeyRound className="h-8 w-8 text-white" />
                </div>
                <h1 className="text-2xl font-bold text-gray-900">Ganti Password</h1>
                <p className="mt-2 text-sm text-gray-500">
                  Ini adalah login pertama Anda. Silakan buat password baru.
                </p>
              </div>

              <form onSubmit={cpForm.handleSubmit(onChangePassword)} className="space-y-5">
                <div className="space-y-1.5">
                  <label className="flex items-center gap-2 text-sm font-medium text-gray-700">
                    <Lock className="h-4 w-4 text-sky-600" />
                    Password Saat Ini
                  </label>
                  <div className="relative">
                    <input
                      {...cpForm.register('current_password')}
                      type={showCurrent ? 'text' : 'password'}
                      placeholder="Masukkan password saat ini"
                      className="w-full h-12 border border-gray-200 rounded-xl px-4 pr-12 text-sm focus:outline-none focus:ring-2 focus:ring-sky-500 focus:border-transparent transition"
                    />
                    <button
                      type="button"
                      onClick={() => setShowCurrent(!showCurrent)}
                      className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 transition-colors"
                    >
                      {showCurrent ? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}
                    </button>
                  </div>
                  {cpForm.formState.errors.current_password && (
                    <p className="text-red-500 text-xs mt-1">{cpForm.formState.errors.current_password.message}</p>
                  )}
                </div>

                <div className="space-y-1.5">
                  <label className="flex items-center gap-2 text-sm font-medium text-gray-700">
                    <Lock className="h-4 w-4 text-sky-600" />
                    Password Baru
                  </label>
                  <div className="relative">
                    <input
                      {...cpForm.register('new_password')}
                      type={showNew ? 'text' : 'password'}
                      placeholder="Masukkan password baru"
                      className="w-full h-12 border border-gray-200 rounded-xl px-4 pr-12 text-sm focus:outline-none focus:ring-2 focus:ring-sky-500 focus:border-transparent transition"
                    />
                    <button
                      type="button"
                      onClick={() => setShowNew(!showNew)}
                      className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 transition-colors"
                    >
                      {showNew ? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}
                    </button>
                  </div>
                  {cpForm.formState.errors.new_password && (
                    <p className="text-red-500 text-xs mt-1">{cpForm.formState.errors.new_password.message}</p>
                  )}
                </div>

                <div className="space-y-1.5">
                  <label className="flex items-center gap-2 text-sm font-medium text-gray-700">
                    <Lock className="h-4 w-4 text-sky-600" />
                    Konfirmasi Password Baru
                  </label>
                  <div className="relative">
                    <input
                      {...cpForm.register('new_password_confirmation')}
                      type={showConfirm ? 'text' : 'password'}
                      placeholder="Ulangi password baru"
                      className="w-full h-12 border border-gray-200 rounded-xl px-4 pr-12 text-sm focus:outline-none focus:ring-2 focus:ring-sky-500 focus:border-transparent transition"
                    />
                    <button
                      type="button"
                      onClick={() => setShowConfirm(!showConfirm)}
                      className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 transition-colors"
                    >
                      {showConfirm ? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}
                    </button>
                  </div>
                  {cpForm.formState.errors.new_password_confirmation && (
                    <p className="text-red-500 text-xs mt-1">{cpForm.formState.errors.new_password_confirmation.message}</p>
                  )}
                </div>

                <button
                  type="submit"
                  disabled={loading}
                  className="w-full h-12 gradient-bmu text-white font-semibold rounded-xl shadow-bmu hover:opacity-90 transition disabled:opacity-60 flex items-center justify-center gap-2"
                >
                  {loading ? (
                    <>
                      <span className="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent" />
                      Menyimpan...
                    </>
                  ) : (
                    <>
                      <KeyRound className="h-5 w-5" />
                      Simpan Password
                    </>
                  )}
                </button>

                <button
                  type="button"
                  onClick={() => { setPendingCode(null); loginForm.reset(); }}
                  className="w-full text-sm text-gray-400 hover:text-gray-600 transition mt-2"
                >
                  Kembali ke halaman login
                </button>
              </form>
            </div>
          )}

        </div>
      </main>
    </div>
  );
}
