'use client';

import { useState, useEffect } from 'react';
import { Mail, AlertCircle, CheckCircle, ArrowLeft } from 'lucide-react';
import { useLanguage } from '@client/contexts/LanguageContext';
import { useAuth } from '@client/contexts/AuthContext';
import { toast } from 'sonner';
import DemoDisabled from '@client/components/demo/DemoDisabled';

interface ChangeEmailFormProps {
  currentEmail: string;
  onEmailChanged?: (newEmail: string) => void;
}

type Step = 'view' | 'enter-email' | 'enter-code';

const RESEND_COOLDOWN_SEC = 60;

export default function ChangeEmailForm({ currentEmail, onEmailChanged }: ChangeEmailFormProps) {
  const { t } = useLanguage();
  const { patchUserEmail } = useAuth();
  const [step, setStep] = useState<Step>('view');
  const [newEmail, setNewEmail] = useState('');
  const [code, setCode] = useState('');
  const [loading, setLoading] = useState(false);
  const [resending, setResending] = useState(false);
  const [error, setError] = useState('');
  const [displayEmail, setDisplayEmail] = useState(currentEmail);
  const [resendCooldown, setResendCooldown] = useState(0);

  useEffect(() => {
    if (resendCooldown <= 0) return;
    const timer = setTimeout(() => setResendCooldown(prev => prev - 1), 1000);
    return () => clearTimeout(timer);
  }, [resendCooldown]);

  const startCooldown = () => {
    setResendCooldown(RESEND_COOLDOWN_SEC);
  };

  const handleSendCode = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      const res = await fetch('/api/auth/me/change-email', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ newEmail }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || t('account.sendCodeError', 'Failed to send verification code'));
      setStep('enter-code');
      startCooldown();
      if (data.alreadySentRecently) {
        toast.info(t('account.codeAlreadySent', 'A code was already sent recently — check your inbox'));
      }
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : t('account.sendCodeError', 'Failed to send verification code'));
    } finally {
      setLoading(false);
    }
  };

  const handleResend = async () => {
    setError('');
    setResending(true);
    try {
      const res = await fetch('/api/auth/me/change-email', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ newEmail }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || t('account.sendCodeError', 'Failed to send verification code'));
      startCooldown();
      if (data.alreadySentRecently) {
        toast.info(t('account.codeAlreadySent', 'A code was already sent recently — check your inbox'));
      } else {
        toast.success(t('account.codeSentAgain', 'Verification code resent'));
      }
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : t('account.sendCodeError', 'Failed to send verification code'));
    } finally {
      setResending(false);
    }
  };

  const handleVerify = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      const res = await fetch('/api/auth/me/change-email/verify', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ code }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || t('account.invalidCode', 'Invalid or expired code'));
      const updated = data.email as string;
      setDisplayEmail(updated);
      patchUserEmail(updated);
      toast.success(t('account.emailUpdated', 'Email updated successfully'));
      onEmailChanged?.(updated);
      setStep('view');
      setNewEmail('');
      setCode('');
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : t('account.invalidCode', 'Invalid or expired code'));
    } finally {
      setLoading(false);
    }
  };

  const resetToView = () => {
    setStep('view');
    setNewEmail('');
    setCode('');
    setError('');
    setResendCooldown(0);
  };

  return (
    <div className="card p-5">
      <div className="flex items-center gap-2 mb-4">
        <Mail size={16} style={{ color: 'hsl(var(--primary))' }} />
        <h3 className="font-semibold" style={{ color: 'hsl(var(--foreground))' }}>
          {t('account.changeEmail', 'Change email')}
        </h3>
      </div>

      {error && (
        <div className="flex items-center gap-2 p-3 rounded-xl text-sm mb-4" style={{ backgroundColor: 'hsl(0, 84%, 97%)', color: 'hsl(0, 84%, 44%)', border: '1px solid hsl(0, 84%, 90%)' }}>
          <AlertCircle size={15} className="shrink-0" />
          {error}
        </div>
      )}

      {step === 'view' && (
        <div className="flex items-center justify-between">
          <div>
            <p className="text-xs font-semibold mb-0.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>
              {t('account.currentEmail', 'Current email')}
            </p>
            <p className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{displayEmail}</p>
          </div>
          <DemoDisabled tooltip="Demo mode is read-only — sign up for a free trial to make changes.">
            <button
              onClick={() => setStep('enter-email')}
              className="btn-secondary text-sm"
            >
              {t('account.changeEmail', 'Change')}
            </button>
          </DemoDisabled>
        </div>
      )}

      {step === 'enter-email' && (
        <form onSubmit={handleSendCode} className="space-y-4">
          <div>
            <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>
              {t('account.newEmail', 'New email address')}
            </label>
            <div className="relative">
              <Mail size={15} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: 'hsl(var(--muted-foreground))' }} />
              <input
                type="email"
                className="input-base pl-9"
                placeholder={t('account.newEmailPlaceholder', 'you@example.com')}
                value={newEmail}
                onChange={e => setNewEmail(e.target.value)}
                required
                autoFocus
              />
            </div>
          </div>
          <div className="flex gap-2">
            <button type="button" onClick={resetToView} className="btn-secondary flex-1">
              {t('common.cancel', 'Cancel')}
            </button>
            <button
              type="submit"
              disabled={loading || !newEmail}
              className="btn-primary flex-1 justify-center disabled:opacity-50"
            >
              {loading ? (
                <span className="flex items-center gap-2 justify-center">
                  <span className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                  {t('common.sending', 'Sending…')}
                </span>
              ) : t('account.sendCode', 'Send verification code')}
            </button>
          </div>
        </form>
      )}

      {step === 'enter-code' && (
        <form onSubmit={handleVerify} className="space-y-4">
          <div className="flex items-center gap-2 p-3 rounded-xl text-sm" style={{ backgroundColor: 'hsl(var(--muted))', color: 'hsl(var(--foreground-secondary))' }}>
            <CheckCircle size={14} style={{ color: 'hsl(var(--success))' }} />
            {t('account.codeSent', 'A 6-digit code was sent to {{email}}').replace('{{email}}', newEmail)}
          </div>
          <div>
            <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>
              {t('account.enterCode', 'Verification code')}
            </label>
            <input
              type="text"
              inputMode="numeric"
              pattern="[0-9]{6}"
              maxLength={6}
              className="input-base tracking-widest text-center text-lg font-mono"
              placeholder="000000"
              value={code}
              onChange={e => setCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
              required
              autoFocus
            />
          </div>
          <div className="flex items-center justify-between">
            <button
              type="button"
              onClick={() => { setStep('enter-email'); setCode(''); setError(''); setResendCooldown(0); }}
              className="btn-ghost text-sm flex items-center gap-1"
              style={{ color: 'hsl(var(--muted-foreground))' }}
            >
              <ArrowLeft size={13} /> {t('account.changeEmailBack', 'Use a different email')}
            </button>
            <button
              type="button"
              onClick={handleResend}
              disabled={resending || resendCooldown > 0}
              className="text-sm disabled:opacity-50"
              style={{ color: resendCooldown > 0 ? 'hsl(var(--muted-foreground))' : 'hsl(var(--primary))' }}
            >
              {resending ? (
                <span className="flex items-center gap-1.5">
                  <span className="w-3 h-3 border-2 border-current/30 border-t-current rounded-full animate-spin" />
                  {t('common.sending', 'Sending…')}
                </span>
              ) : resendCooldown > 0
                ? t('account.resendCodeIn', 'Resend in {{s}}s').replace('{{s}}', String(resendCooldown))
                : t('account.resendCode', 'Resend code')}
            </button>
          </div>
          <button
            type="submit"
            disabled={loading || code.length !== 6}
            className="btn-primary w-full justify-center disabled:opacity-50"
          >
            {loading ? (
              <span className="flex items-center gap-2 justify-center">
                <span className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                {t('common.verifying', 'Verifying…')}
              </span>
            ) : t('account.confirmEmail', 'Confirm new email')}
          </button>
        </form>
      )}
    </div>
  );
}
