'use client';
import React, { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { ShieldCheck, ArrowRight, Loader2 } from 'lucide-react';

export default function ForgotPassword() {
  const [step, setStep] = useState<'email' | 'questions' | 'success'>('email');
  const [email, setEmail] = useState('');
  const [questions, setQuestions] = useState<string[]>([]);
  const [answers, setAnswers] = useState(['', '']);
  const [newPassword, setNewPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const router = useRouter();

  const handleEmailSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError('');
    
    try {
      const res = await fetch('/api/auth/recovery', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ step: 'get_questions', email })
      });
      const data = await res.json();
      
      if (res.ok) {
        setQuestions(data.questions);
        setStep('questions');
      } else {
        setError(data.error || 'Account not found');
      }
    } catch (e) {
      setError('Network error');
    } finally {
      setLoading(false);
    }
  };

  const handleResetSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError('');

    try {
      const res = await fetch('/api/auth/recovery', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ step: 'verify_reset', email, answers, newPassword })
      });
      
      if (res.ok) {
        setStep('success');
      } else {
        const data = await res.json();
        setError(data.error || 'Verification failed');
      }
    } catch (e) {
      setError('Network error');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="w-full max-w-md bg-white rounded-2xl shadow-xl overflow-hidden">
      <div className="bg-slate-900 p-8 text-center">
        <div className="bg-white p-3 rounded-full inline-flex items-center justify-center mb-4 shadow-sm w-16 h-16 text-primary">
           <ShieldCheck size={32} />
        </div>
        <h2 className="text-2xl font-bold text-white">Account Recovery</h2>
        <p className="text-slate-400 mt-2">Secure Password Reset</p>
      </div>
      
      <div className="p-8">
        {step === 'email' && (
          <form onSubmit={handleEmailSubmit} className="space-y-6">
            {error && <div className="bg-red-50 text-red-600 p-3 rounded text-sm">{error}</div>}
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-2">Enter your email address</label>
              <input 
                type="email" 
                required 
                className="w-full px-4 py-3 rounded-lg border border-slate-300 focus:ring-2 focus:ring-primary outline-none"
                value={email}
                onChange={e => setEmail(e.target.value)}
              />
            </div>
            <button type="submit" disabled={loading} className="w-full bg-primary hover:bg-primary-dark text-white font-bold py-3 rounded-lg flex items-center justify-center gap-2">
               {loading ? <Loader2 className="animate-spin" /> : <>Next Step <ArrowRight size={18} /></>}
            </button>
            <div className="text-center">
              <Link href="/admin/login" className="text-sm text-slate-500 hover:text-primary">Back to Login</Link>
            </div>
          </form>
        )}

        {step === 'questions' && (
           <form onSubmit={handleResetSubmit} className="space-y-6">
             {error && <div className="bg-red-50 text-red-600 p-3 rounded text-sm">{error}</div>}
             
             <div>
               <label className="block text-xs font-bold text-slate-500 uppercase mb-1">Security Question 1</label>
               <p className="text-slate-800 font-medium mb-2">{questions[0]}</p>
               <input 
                 required 
                 className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-primary outline-none"
                 placeholder="Your Answer"
                 value={answers[0]}
                 onChange={e => { const newAns = [...answers]; newAns[0] = e.target.value; setAnswers(newAns); }}
               />
             </div>

             <div>
               <label className="block text-xs font-bold text-slate-500 uppercase mb-1">Security Question 2</label>
               <p className="text-slate-800 font-medium mb-2">{questions[1]}</p>
               <input 
                 required 
                 className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-primary outline-none"
                 placeholder="Your Answer"
                 value={answers[1]}
                 onChange={e => { const newAns = [...answers]; newAns[1] = e.target.value; setAnswers(newAns); }}
               />
             </div>

             <div className="border-t pt-4 mt-4">
                <label className="block text-sm font-medium text-slate-700 mb-2">Set New Password</label>
                <input 
                  type="password"
                  required 
                  className="w-full px-4 py-3 rounded-lg border border-slate-300 focus:ring-2 focus:ring-primary outline-none"
                  placeholder="New strong password"
                  value={newPassword}
                  onChange={e => setNewPassword(e.target.value)}
                />
             </div>

             <button type="submit" disabled={loading} className="w-full bg-primary hover:bg-primary-dark text-white font-bold py-3 rounded-lg flex items-center justify-center gap-2">
                {loading ? <Loader2 className="animate-spin" /> : 'Reset Password'}
             </button>
           </form>
        )}

        {step === 'success' && (
          <div className="text-center">
            <div className="w-16 h-16 bg-green-100 text-green-600 rounded-full flex items-center justify-center mx-auto mb-4">
              <ShieldCheck size={32} />
            </div>
            <h3 className="text-xl font-bold text-slate-900 mb-2">Password Reset Successful</h3>
            <p className="text-slate-500 mb-6">You can now log in with your new password.</p>
            <Link href="/admin/login" className="block w-full bg-slate-900 text-white font-bold py-3 rounded-lg hover:bg-slate-800">
              Go to Login
            </Link>
          </div>
        )}
      </div>
    </div>
  );
}