'use client';

import { useState, useEffect } from 'react';
import { useRouter, useParams } 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 { Lock, Eye, EyeOff, CheckCircle, XCircle, Loader2 } from 'lucide-react';
import api from '@/lib/axios';

const schema = z.object({
  password: z.string().min(6, 'Password minimal 6 karakter'),
  password_confirmation: z.string().min(6, 'Konfirmasi password minimal 6 karakter'),
}).refine((data) => data.password === data.password_confirmation, {
  message: 'Konfirmasi password tidak cocok',
  path: ['password_confirmation'],
});
type FormData = z.infer<typeof schema>;

export default function ResetPasswordPage() {
  const router = useRouter();
  const params = useParams();
  const token = params.token as string;

  const [loading, setLoading] = useState(false);
  const [verifying, setVerifying] = useState(true);
  const [tokenValid, setTokenValid] = useState(false);
  const [email, setEmail] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirm, setShowConfirm] = useState(false);
  const [success, setSuccess] = useState(false);

  const { register, handleSubmit, formState: { errors } } = useForm<FormData>({
    resolver: zodResolver(schema),
  });

  useEffect(() => {
    verifyToken();
  }, [token]);

  const verifyToken = async () => {
    setVerifying(true);
    try {
      const res = await api.get(`/end-user/verify-reset-token/${token}`);
      setTokenValid(true);
      setEmail(res.data.data.email);
    } catch (err: any) {
      setTokenValid(false);
      const message = err.response?.data?.message ?? 'Token tidak valid';
      toast.error(message);
    } finally {
      setVerifying(false);
    }
  };

  const onSubmit = async (data: FormData) => {
    setLoading(true);
    try {
      const res = await api.post('/end-user/reset-password', {
        token,
        password: data.password,
        password_confirmation: data.password_confirmation,
      });
      setSuccess(true);
      toast.success(res.data.message || 'Password berhasil diubah!');
      
      // Redirect to login after 3 seconds
      setTimeout(() => {
        router.push('/login');
      }, 3000);
    } catch (err: any) {
      toast.error(err.response?.data?.message ?? 'Gagal reset password');
    } finally {
      setLoading(false);
    }
  };

  // Loading state
  if (verifying) {
    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">
        <div className="text-center text-white">
          <Loader2 className="w-12 h-12 animate-spin mx-auto mb-4" />
          <p className="text-lg">Memverifikasi token...</p>
        </div>
      </div>
    );
  }

  // Invalid token
  if (!tokenValid) {
    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">
        <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">
          <div className="bg-white/15 backdrop-blur-md border border-white/20 rounded-3xl p-8 shadow-2xl text-white text-center">
            <div className="inline-flex items-center justify-center w-20 h-20 bg-red-500/20 backdrop-blur-sm rounded-full mb-6">
              <XCircle className="w-10 h-10 text-red-300" />
            </div>
            
            <h1 className="text-2xl font-extrabold text-white mb-3">Token Tidak Valid</h1>
            
            <p className="text-white/80 text-sm mb-6">
              Link reset password tidak valid atau sudah kadaluarsa.
            </p>
            
            <div className="space-y-3">
              <Link
                href="/forgot-password"
                className="block w-full h-11 bg-white text-indigo-700 font-bold rounded-xl shadow-lg hover:bg-white/90 transition flex items-center justify-center"
              >
                Request Link Baru
              </Link>
              
              <Link
                href="/login"
                className="block w-full h-11 bg-white/10 border border-white/30 text-white font-semibold rounded-xl hover:bg-white/20 transition flex items-center justify-center"
              >
                Kembali ke Login
              </Link>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // Success state
  if (success) {
    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">
        <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">
          <div className="bg-white/15 backdrop-blur-md border border-white/20 rounded-3xl p-8 shadow-2xl text-white text-center">
            <div className="inline-flex items-center justify-center w-20 h-20 bg-green-500/20 backdrop-blur-sm rounded-full mb-6">
              <CheckCircle className="w-10 h-10 text-green-300" />
            </div>
            
            <h1 className="text-2xl font-extrabold text-white mb-3">Password Berhasil Diubah!</h1>
            
            <p className="text-white/80 text-sm mb-6">
              Password Anda telah berhasil diubah. Anda akan diarahkan ke halaman login...
            </p>
            
            <Link
              href="/login"
              className="inline-flex items-center justify-center w-full h-11 bg-white text-indigo-700 font-bold rounded-xl shadow-lg hover:bg-white/90 transition"
            >
              Login Sekarang
            </Link>
          </div>
        </div>
      </div>
    );
  }

  // Reset password form
  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">
            <Lock className="w-8 h-8 text-white" />
          </div>
          <h1 className="text-3xl font-extrabold text-white">Buat Password Baru</h1>
          <p className="text-white/70 text-sm mt-1">Untuk akun: {email}</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">
                <Lock className="h-4 w-4" /> Password Baru
              </label>
              <div className="relative">
                <input
                  {...register('password')}
                  type={showPassword ? 'text' : 'password'}
                  placeholder="Minimal 6 karakter"
                  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>
              <label className="flex items-center gap-2 text-sm font-medium text-white/90 mb-1.5">
                <Lock className="h-4 w-4" /> Konfirmasi Password
              </label>
              <div className="relative">
                <input
                  {...register('password_confirmation')}
                  type={showConfirm ? 'text' : 'password'}
                  placeholder="Ulangi password baru"
                  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={() => setShowConfirm(!showConfirm)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-white/60 hover:text-white"
                >
                  {showConfirm ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                </button>
              </div>
              {errors.password_confirmation && <p className="text-red-300 text-xs mt-1">{errors.password_confirmation.message}</p>}
            </div>

            <div className="bg-blue-500/20 border border-blue-300/30 rounded-xl p-3">
              <p className="text-white/80 text-xs">
                💡 Gunakan password yang kuat dengan kombinasi huruf, angka, dan simbol.
              </p>
            </div>

            <button
              type="submit"
              disabled={loading}
              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" />
                  Menyimpan...
                </>
              ) : (
                <>
                  <CheckCircle className="h-4 w-4" />
                  Ubah Password
                </>
              )}
            </button>
          </form>
        </div>
      </div>
    </div>
  );
}
