// src/app/(root)/forgot-password/ForgotPasswordForm.tsx
'use client';

import { useState } from 'react';
import Link from 'next/link';
import {
  Mail, AlertCircle, Loader2,
  Shield, CheckCircle, ArrowRight, KeyRound,
} from 'lucide-react';
import toast from 'react-hot-toast';

type Errors = Record<string, string>;

export default function ForgotPasswordForm() {
  const [email,       setEmail]       = useState('');
  const [isLoading,   setIsLoading]   = useState(false);
  const [isSubmitted, setIsSubmitted] = useState(false);
  const [errors,      setErrors]      = useState<Errors>({});

  const validate = (): boolean => {
    const e: Errors = {};
    if (!email)                          e.email = 'Email is required';
    else if (!/\S+@\S+\.\S+/.test(email)) e.email = 'Enter a valid email';
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const handleSubmit = async (ev: React.FormEvent) => {
    ev.preventDefault();
    if (!validate()) return;
    setIsLoading(true);
    try {
      const res  = await fetch('/api/frontend/user/auth/forgot-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email }),
      });
      const data = await res.json();
      if (data.success) {
        setIsSubmitted(true);
        toast.success('Reset instructions sent!');
      } else {
        setErrors({ submit: data.message || 'Failed to send reset instructions' });
      }
    } catch {
      setErrors({ submit: 'An error occurred. Please try again.' });
    } finally {
      setIsLoading(false);
    }
  };

  const handleReset = () => {
    setEmail('');
    setIsSubmitted(false);
    setErrors({});
  };

  /* ── Success state ── */
  if (isSubmitted) {
    return (
      <div>
        {/* Header */}
        <div className="text-center mb-7">
          <div className="lg:hidden flex justify-center mb-5">
            <Link href="/">
              <div className="h-11 w-11 rounded-xl bg-linear-to-br from-[#0066FF] to-[#00D4FF] flex items-center justify-center">
                <span className="text-white font-bold text-lg">OE</span>
              </div>
            </Link>
          </div>
          <div className="flex justify-center mb-4">
            <div className="h-16 w-16 rounded-2xl bg-green-100 flex items-center justify-center">
              <CheckCircle className="h-8 w-8 text-green-600" />
            </div>
          </div>
          <h2 className="text-2xl font-bold text-text-primary">Check your email</h2>
          <p className="mt-1.5 text-sm text-text-secondary">
            We sent reset instructions to your inbox
          </p>
        </div>

        {/* Email pill */}
        <div className="mb-5 py-3 px-4 rounded-xl bg-black/3 border border-black/8 text-center">
          <p className="text-xs text-text-secondary mb-0.5">Instructions sent to</p>
          <p className="text-sm font-semibold text-text-primary truncate">{email}</p>
        </div>

        {/* Next steps */}
        <div className="mb-6 p-3.5 rounded-xl bg-[#0066FF]/5 border border-[#0066FF]/15 space-y-2">
          <div className="flex items-center gap-2 mb-1">
            <Mail className="h-3.5 w-3.5 text-[#0066FF]" />
            <p className="text-xs font-semibold text-[#0066FF]">What`s next?</p>
          </div>
          {[
            'Check your email inbox (and spam folder)',
            'Click the reset password link in the email',
            'Create your new password',
            'Link expires in 10 minutes',
          ].map(step => (
            <div key={step} className="flex items-start gap-2">
              <div className="h-1.5 w-1.5 rounded-full bg-[#0066FF]/50 mt-1.5 shrink-0" />
              <p className="text-xs text-text-secondary">{step}</p>
            </div>
          ))}
        </div>

        {/* Actions */}
        <div className="grid grid-cols-2 gap-3">
          <button
            onClick={handleReset}
            className="flex items-center justify-center gap-2 py-3 px-4 rounded-xl
              border border-black/10 hover:bg-black/3 active:scale-[0.99]
              text-sm font-medium text-text-primary transition-all"
          >
            Try another
          </button>
          <Link
            href="/login"
            className="flex items-center justify-center gap-2 py-3 px-4 rounded-xl
              bg-[#0066FF] hover:bg-[#0052cc] active:scale-[0.99]
              text-sm font-semibold text-white transition-all"
          >
            Back to login
          </Link>
        </div>

        {/* Footer */}
        <div className="mt-6 pt-5 border-t border-black/8 space-y-2.5">
          <div className="flex items-start gap-2.5 text-xs text-text-secondary">
            <Shield className="h-3.5 w-3.5 shrink-0 mt-0.5 text-text-secondary/60" />
            <span>Reset links expire after 10 minutes. Only the most recent link will work.</span>
          </div>
          <div className="flex items-start gap-2.5 text-xs text-text-secondary">
            <Mail className="h-3.5 w-3.5 shrink-0 mt-0.5 text-text-secondary/60" />
            <span>
              Still no email?{' '}
              <Link href="/contact" className="text-[#0066FF] hover:text-[#0052cc] transition-colors">
                Contact support
              </Link>
            </span>
          </div>
        </div>
      </div>
    );
  }

  /* ── Form state ── */
  return (
    <div>
      {/* Header */}
      <div className="text-center mb-7">
        <div className="lg:hidden flex justify-center mb-5">
          <Link href="/">
            <div className="h-11 w-11 rounded-xl bg-linear-to-br from-[#0066FF] to-[#00D4FF] flex items-center justify-center">
              <span className="text-white font-bold text-lg">OE</span>
            </div>
          </Link>
        </div>
        <div className="flex justify-center mb-4">
          <div className="h-16 w-16 rounded-2xl bg-[#0066FF]/10 flex items-center justify-center">
            <KeyRound className="h-8 w-8 text-[#0066FF]" />
          </div>
        </div>
        <h2 className="text-2xl font-bold text-text-primary">Forgot password?</h2>
        <p className="mt-1.5 text-sm text-text-secondary">
          Enter your email and we`ll send you a reset link
        </p>
      </div>

      {/* Submit error */}
      {errors.submit && (
        <div className="mb-5 flex items-start gap-3 p-3.5 rounded-xl bg-red-50 border border-red-200">
          <AlertCircle className="h-4 w-4 text-red-500 shrink-0 mt-0.5" />
          <p className="text-sm text-red-700">{errors.submit}</p>
        </div>
      )}

      <form onSubmit={handleSubmit} className="space-y-4">

        {/* Email */}
        <div>
          <label className="block text-xs font-medium text-text-primary mb-1.5">
            Email address
          </label>
          <div className="relative">
            <Mail className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-text-secondary" />
            <input
              type="email"
              value={email}
              onChange={e => {
                setEmail(e.target.value);
                if (errors.email) setErrors(prev => ({ ...prev, email: '' }));
              }}
              placeholder="you@company.com"
              autoComplete="email"
              disabled={isLoading}
              className={`w-full pl-10 pr-3 py-3 text-sm border rounded-xl bg-background
                text-text-primary placeholder-text-secondary/40 outline-none transition-all
                focus:ring-2 focus:ring-[#0066FF]/20 disabled:opacity-60
                ${errors.email
                  ? 'border-red-300 focus:border-red-400'
                  : 'border-black/10 focus:border-[#0066FF]'
                }`}
            />
          </div>
          {errors.email && (
            <p className="mt-1.5 text-xs text-red-500 flex items-center gap-1">
              <AlertCircle className="h-3 w-3" />{errors.email}
            </p>
          )}
        </div>

        {/* Submit */}
        <button
          type="submit"
          disabled={isLoading}
          className="w-full flex items-center justify-center gap-2 py-3 px-4 rounded-xl
            bg-[#0066FF] hover:bg-[#0052cc] active:scale-[0.99] text-white text-sm font-semibold
            transition-all disabled:opacity-60 disabled:cursor-not-allowed"
        >
          {isLoading
            ? <><Loader2 className="h-4 w-4 animate-spin" /> Sending instructions...</>
            : <>Send reset link <ArrowRight className="h-4 w-4" /></>
          }
        </button>

      </form>

      {/* Below form */}
      <div className="mt-6 space-y-4">

        {/* Back to login */}
        <Link
          href="/login"
          className="w-full flex items-center justify-center gap-2 py-3 px-4 rounded-xl
            border border-black/10 hover:bg-black/3 active:scale-[0.99]
            text-sm font-medium text-text-primary transition-all"
        >
          ← Back to login
        </Link>

        {/* Info tips */}
        <div className="pt-4 border-t border-black/8 space-y-2.5">
          <div className="flex items-start gap-2.5 text-xs text-text-secondary">
            <Shield className="h-3.5 w-3.5 shrink-0 mt-0.5 text-text-secondary/60" />
            <span>Reset links expire after 10 minutes. Only the most recent link will work.</span>
          </div>
          <div className="flex items-start gap-2.5 text-xs text-text-secondary">
            <Mail className="h-3.5 w-3.5 shrink-0 mt-0.5 text-text-secondary/60" />
            <span>
              Still having trouble?{' '}
              <Link href="/contact" className="text-[#0066FF] hover:text-[#0052cc] transition-colors">
                Contact support
              </Link>
            </span>
          </div>
        </div>

      </div>
    </div>
  );
}