'use client';

import React, { useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Header } from '@/components/Header';
import { Footer } from '@/components/Footer';
import api, { getCsrfCookie } from '@/lib/api';
import { Loader2, Lock, CheckCircle2, AlertCircle, Eye, EyeOff, User, PenSquare } from 'lucide-react';

export default function ForgotPasswordPage() {
  const router = useRouter();
  
  // Step 1: Request Reset Code
  // Step 2: Verification Code & New Password
  const [step, setStep] = useState(1);
  const [emailOrPhone, setEmailOrPhone] = useState('');
  const [verificationCode, setVerificationCode] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);

  const [error, setError] = useState('');
  const [successMessage, setSuccessMessage] = useState('');
  const [submitting, setSubmitting] = useState(false);

  // Handle Step 1 Submit
  const handleRequestCode = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setSuccessMessage('');

    if (!emailOrPhone) {
      setError('দয়া করে আপনার ইমেইল বা মোবাইল নম্বর দিন।');
      return;
    }

    setSubmitting(true);
    try {
      await getCsrfCookie();
      const res = await api.post('/api/password/forgot', {
        email_or_phone: emailOrPhone,
      });
      setSuccessMessage(res.data.message || 'Verification code sent.');
      setStep(2);
    } catch (err: any) {
      setError(err.response?.data?.message || err.message || 'Verification code sending failed.');
    } finally {
      setSubmitting(false);
    }
  };

  // Handle Step 2 Submit
  const handleResetPassword = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setSuccessMessage('');

    if (!verificationCode) {
      setError('দয়া করে ভেরিফিকেশন কোড দিন।');
      return;
    }
    if (newPassword.length < 8) {
      setError('পাসওয়ার্ডটি অন্তত ৮ অক্ষরের হতে হবে।');
      return;
    }

    setSubmitting(true);
    try {
      await getCsrfCookie();
      const res = await api.post('/api/password/reset', {
        email_or_phone: emailOrPhone,
        code: verificationCode,
        password: newPassword,
      });
      alert(res.data.message || 'Password updated successfully!');
      router.push('/login');
    } catch (err: any) {
      setError(err.response?.data?.message || err.message || 'Password reset failed. Please check the code.');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <>
      <Header />
      {/* Aligned to top (justify-start) instead of vertical center (justify-center) to reduce top gap */}
      <main className="bg-slate-50 min-h-[60vh] sm:min-h-screen pt-4 sm:pt-12 pb-8 sm:pb-16 flex flex-col items-center justify-start">
        <div className="max-w-md w-full px-4">
          
          {/* Card Container - Greenish cyan pastel background, rounded [36px], absolute badge overlapping (Exactly as screenshots) */}
          <div className="relative bg-[#ebf5f2] px-8 py-10 rounded-[36px] shadow-xs text-center mt-10 sm:mt-12 space-y-6 border border-slate-100/10">
            
            {/* Circle Overlapping Badge (Top Middle) - Using direct key icon from user */}
            <div className="absolute -top-10 left-1/2 -translate-x-1/2 h-20 w-20 rounded-full bg-white flex items-center justify-center shadow-md border-4 border-white overflow-hidden p-1">
              <img 
                src="/images/key-icon.png" 
                alt="Key Icon" 
                className="h-12 w-12 object-contain"
              />
            </div>
            
            {/* Title Section */}
            <div className="pt-6">
              <h1 className="text-2xl font-bold text-slate-800 tracking-tight">
                {step === 1 ? 'Forgotten Password?' : 'Change Password'}
              </h1>
            </div>

            {/* Error alerts */}
            {error && (
              <div className="bg-rose-50 border border-rose-250 text-rose-600 px-4 py-3 rounded-2xl text-xs font-medium flex items-center gap-2.5">
                <AlertCircle className="h-5 w-5 shrink-0" />
                <span className="text-left">{error}</span>
              </div>
            )}

            {/* Success alerts */}
            {successMessage && (
              <div className="bg-emerald-50 border border-emerald-250 text-emerald-700 px-4 py-3 rounded-2xl text-xs font-medium flex items-start gap-2.5">
                <CheckCircle2 className="h-5 w-5 shrink-0 text-emerald-600 mt-0.5" />
                <span className="text-left">{successMessage}</span>
              </div>
            )}

            {/* Step 1: Input Email/Phone */}
            {step === 1 ? (
              <form onSubmit={handleRequestCode} className="space-y-4">
                
                {/* Email or Phone Input (White box, orange profile icon on the left) */}
                <div className="relative">
                  <span className="absolute left-3.5 top-3.5 text-slate-400">
                    <User className="h-5 w-5 text-secondary" />
                  </span>
                  <input
                    type="text"
                    required
                    placeholder="Email or Phone Number"
                    value={emailOrPhone}
                    onChange={(e) => setEmailOrPhone(e.target.value)}
                    className="w-full text-sm pl-11 pr-4 py-3 bg-white border border-slate-200 rounded-xl focus:border-secondary focus:ring-1 focus:ring-secondary focus:outline-none placeholder:text-slate-400"
                  />
                </div>

                {/* Orange Button Next */}
                <button
                  type="submit"
                  disabled={submitting}
                  className="w-full py-3.5 bg-secondary hover:bg-secondary-dark disabled:opacity-50 text-white text-sm font-semibold rounded-xl shadow-xs transition-colors cursor-pointer"
                >
                  {submitting ? (
                    <span className="flex items-center justify-center gap-2">
                      <Loader2 className="h-4 w-4 animate-spin" />
                      Loading...
                    </span>
                  ) : (
                    <span>Next</span>
                  )}
                </button>

                <div className="text-center pt-2 text-xs text-slate-500 font-normal">
                  Remember credentials?{' '}
                  <Link href="/login" className="font-semibold text-secondary hover:underline">
                    Sign in
                  </Link>
                </div>

              </form>
            ) : (
              // Step 2: Verification Code & New Password
              <form onSubmit={handleResetPassword} className="space-y-4">
                
                {/* Verification Code (White box, orange pencil icon on the left) */}
                <div className="relative">
                  <span className="absolute left-3.5 top-3.5 text-slate-400">
                    <svg className="h-5 w-5 stroke-secondary fill-none" viewBox="0 0 24 24" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                      <path d="M12 20h9" />
                      <path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z" />
                    </svg>
                  </span>
                  <input
                    type="text"
                    required
                    placeholder="Verification Code"
                    value={verificationCode}
                    onChange={(e) => setVerificationCode(e.target.value)}
                    className="w-full text-sm pl-11 pr-4 py-3 bg-white border border-slate-200 rounded-xl focus:border-secondary focus:ring-1 focus:ring-secondary focus:outline-none tracking-wider font-semibold font-mono placeholder:text-slate-400 text-center"
                  />
                </div>

                {/* Set New Password (White box, orange lock icon on the left) */}
                <div className="relative">
                  <span className="absolute left-3.5 top-3.5 text-slate-400">
                    <Lock className="h-5 w-5 text-secondary" />
                  </span>
                  <input
                    type={showPassword ? 'text' : 'password'}
                    required
                    placeholder="Set New Password"
                    value={newPassword}
                    onChange={(e) => setNewPassword(e.target.value)}
                    className="w-full text-sm pl-11 pr-10 py-3 bg-white border border-slate-200 rounded-xl focus:border-secondary focus:ring-1 focus:ring-secondary focus:outline-none placeholder:text-slate-400"
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute right-3 top-3.5 text-slate-400 hover:text-slate-600 focus:outline-none"
                  >
                    {showPassword ? (
                      <EyeOff className="h-5 w-5" />
                    ) : (
                      <Eye className="h-5 w-5" />
                    )}
                  </button>
                </div>

                <div className="flex gap-2">
                  <button
                    type="button"
                    onClick={() => {
                      setStep(1);
                      setVerificationCode('');
                      setNewPassword('');
                      setError('');
                      setSuccessMessage('');
                    }}
                    className="w-1/3 py-3.5 border border-slate-200 hover:bg-slate-50 text-slate-600 text-sm font-semibold rounded-xl transition-colors cursor-pointer bg-white"
                  >
                    Back
                  </button>
                  <button
                    type="submit"
                    disabled={submitting}
                    className="w-2/3 py-3.5 bg-secondary hover:bg-secondary-dark disabled:opacity-50 text-white text-sm font-semibold rounded-xl shadow-xs transition-colors cursor-pointer"
                  >
                    {submitting ? (
                      <span className="flex items-center justify-center gap-2">
                        <Loader2 className="h-4 w-4 animate-spin" />
                        Updating...
                      </span>
                    ) : (
                      <span>Update</span>
                    )}
                  </button>
                </div>

              </form>
            )}

          </div>
        </div>
      </main>
      <Footer />
    </>
  );
}
