'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 { LogIn, Phone, Lock, Eye, EyeOff, Gift, Sparkles } from 'lucide-react';
import api from '@/lib/axios';
import { useAuthStore } from '@/store/auth';
import MathCaptcha from '@/components/MathCaptcha';

const schema = z.object({
  phone: z.string().min(9, 'Nomor HP tidak valid'),
  password: z.string().min(6, 'Password minimal 6 karakter'),
});
type FormData = z.infer<typeof schema>;

export default function LoginPage() {
  const router = useRouter();
  const setAuth = useAuthStore((s) => s.setAuth);
  const [loading, setLoading] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [captchaOk, setCaptchaOk] = useState(false);
  const [captchaKey, setCaptchaKey] = useState(0);

  const { register, handleSubmit, formState: { errors } } = useForm<FormData>({
    resolver: zodResolver(schema),
  });

  const onSubmit = async (data: FormData) => {
    if (!captchaOk) { toast.error('Selesaikan verifikasi CAPTCHA terlebih dahulu.'); return; }
    setLoading(true);
    try {
      const res = await api.post('/end-user/login', data);
      setAuth(res.data.data, res.data.token);
      toast.success('Login berhasil!');
      router.push('/dashboard');
    } catch (err: any) {
      toast.error(err.response?.data?.message ?? 'Login gagal');
      setCaptchaOk(false);
      setCaptchaKey(k => k + 1);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="relative min-h-screen w-full bg-gradient-to-br from-blue-600 via-indigo-600 to-purple-700 flex items-center justify-center px-4 py-8 overflow-hidden">
      {/* Decorative blobs */}
      <div className="absolute top-0 left-0 w-72 h-72 bg-white/10 rounded-full blur-3xl -translate-x-1/2 -translate-y-1/2 pointer-events-none" />
      <div className="absolute bottom-0 right-0 w-96 h-96 bg-pink-500/20 rounded-full blur-3xl translate-x-1/3 translate-y-1/3 pointer-events-none" />

      <div className="relative w-full max-w-md">
        {/* Logo */}
        <div className="text-center mb-8">
          <div className="inline-flex items-center justify-center w-16 h-16 bg-white/20 backdrop-blur-sm rounded-2xl mb-4 shadow-lg">
            <Gift className="w-8 h-8 text-white" />
          </div>
          <h1 className="text-3xl font-extrabold text-white">Masuk</h1>
          <p className="text-white/70 text-sm mt-1">Selamat datang kembali!</p>
        </div>

        {/* Card */}
        <div className="bg-white/15 backdrop-blur-md border border-white/20 rounded-3xl p-7 shadow-2xl text-white">
          <form onSubmit={handleSubmit(onSubmit)} className="space-y-5">
            <div>
              <label className="flex items-center gap-2 text-sm font-medium text-white/90 mb-1.5">
                <Phone className="h-4 w-4" /> Nomor HP
              </label>
              <input {...register('phone')} type="tel" placeholder="08xxxxxxxxxx"
                className="w-full h-11 bg-white/20 border border-white/30 rounded-xl px-4 text-sm text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-white/50 transition" />
              {errors.phone && <p className="text-red-300 text-xs mt-1">{errors.phone.message}</p>}
            </div>

            <div>
              <label className="flex items-center gap-2 text-sm font-medium text-white/90 mb-1.5">
                <Lock className="h-4 w-4" /> Password
              </label>
              <div className="relative">
                <input {...register('password')} type={showPassword ? 'text' : 'password'} placeholder="Password"
                  className="w-full h-11 bg-white/20 border border-white/30 rounded-xl px-4 pr-11 text-sm text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-white/50 transition" />
                <button type="button" onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-white/60 hover:text-white">
                  {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                </button>
              </div>
              {errors.password && <p className="text-red-300 text-xs mt-1">{errors.password.message}</p>}
            </div>

            <div className="flex justify-end">
              <Link href="/forgot-password" className="text-xs text-white/70 hover:text-white underline">Lupa password?</Link>
            </div>

            <MathCaptcha key={captchaKey} onVerified={setCaptchaOk} />

            <button type="submit" disabled={loading || !captchaOk}
              className="w-full h-11 bg-white text-indigo-700 font-bold rounded-xl shadow-lg hover:bg-white/90 disabled:opacity-50 transition flex items-center justify-center gap-2">
              {loading ? <span className="h-4 w-4 animate-spin rounded-full border-2 border-indigo-600 border-t-transparent" /> : <LogIn className="h-4 w-4" />}
              {loading ? 'Memproses...' : 'Masuk'}
            </button>
          </form>

          <p className="text-center text-sm text-white/70 mt-5">
            Belum punya akun?{' '}
            <Link href="/register" className="text-white font-semibold hover:underline">Daftar sekarang</Link>
          </p>
        </div>

        <p className="text-center text-white/50 text-xs mt-6">
          <Link href="/" className="hover:text-white transition">← Kembali ke beranda</Link>
        </p>
      </div>
    </div>
  );
}
