import { useState } from 'react';
import { Link, useSearchParams, useNavigate } from 'react-router-dom';
import { useLanguage } from '../contexts/LanguageContext';
import { Lock, ArrowRight, Loader2, CheckCircle, XCircle } from 'lucide-react';
import BrandLogo from '../components/BrandLogo';
import api from '../services/api';
import toast from 'react-hot-toast';

const MIN_PASSWORD_LENGTH = 8;

export default function ResetPassword() {
  const [searchParams] = useSearchParams();
  const token = searchParams.get('token');
  const { t } = useLanguage();
  const navigate = useNavigate();

  const [password, setPassword] = useState('');
  const [confirm, setConfirm] = useState('');
  const [loading, setLoading] = useState(false);
  const [done, setDone] = useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (password.length < MIN_PASSWORD_LENGTH) {
      toast.error(t('auth.passwordMinLength'));
      return;
    }
    if (password !== confirm) {
      toast.error(t('auth.passwordMismatch'));
      return;
    }
    setLoading(true);
    try {
      await api.post('/auth/reset-password', { token, password });
      setDone(true);
      toast.success(t('auth.resetPasswordSuccess'));
      setTimeout(() => navigate('/login'), 2500);
    } catch (err) {
      toast.error(err.response?.data?.error || t('auth.resetPasswordFailed'));
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center p-6 relative overflow-hidden">
      {/* Animated background */}
      <div className="absolute inset-0 bg-th-bg">
        <div className="absolute inset-0 opacity-30">
          <div className="absolute top-1/4 left-1/4 w-96 h-96 bg-th-accent rounded-full blur-[128px] animate-pulse" />
          <div className="absolute bottom-1/4 right-1/4 w-80 h-80 bg-purple-500 rounded-full blur-[128px] animate-pulse" style={{ animationDelay: '2s' }} />
          <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-64 h-64 bg-pink-500 rounded-full blur-[128px] animate-pulse" style={{ animationDelay: '4s' }} />
        </div>
      </div>

      <div className="relative w-full max-w-md">
        <div className="card p-8 backdrop-blur-xl bg-th-card/80 border border-th-border shadow-2xl rounded-2xl">
          <div className="flex justify-center mb-8">
            <BrandLogo size="lg" />
          </div>

          {!token ? (
            <div className="text-center space-y-4">
              <XCircle size={48} className="mx-auto text-red-400" />
              <h2 className="text-2xl font-bold text-th-text">{t('auth.resetPasswordFailed')}</h2>
              <p className="text-th-text-s">{t('auth.resetTokenMissing')}</p>
              <Link to="/forgot-password" className="btn-primary inline-flex items-center gap-2 mt-4">
                {t('auth.forgotPasswordTitle')}
              </Link>
            </div>
          ) : done ? (
            <div className="text-center space-y-4">
              <CheckCircle size={48} className="mx-auto text-green-400" />
              <h2 className="text-2xl font-bold text-th-text">{t('auth.resetPasswordSuccessTitle')}</h2>
              <p className="text-th-text-s">{t('auth.resetPasswordSuccess')}</p>
              <Link to="/login" className="btn-primary inline-flex items-center gap-2 mt-4">
                {t('auth.login')}
              </Link>
            </div>
          ) : (
            <>
              <div className="mb-8">
                <h2 className="text-2xl font-bold text-th-text mb-2">{t('auth.resetPasswordTitle')}</h2>
                <p className="text-th-text-s">{t('auth.resetPasswordSubtitle')}</p>
              </div>

              <form onSubmit={handleSubmit} className="space-y-5">
                <div>
                  <label htmlFor="reset-password" className="block text-sm font-medium text-th-text mb-1.5">{t('auth.newPassword')}</label>
                  <div className="relative">
                    <Lock size={18} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-th-text-s" aria-hidden="true" />
                    <input
                      id="reset-password"
                      type="password"
                      autoComplete="new-password"
                      value={password}
                      onChange={e => setPassword(e.target.value)}
                      className="input-field pl-11"
                      placeholder={t('auth.passwordPlaceholder')}
                      required
                    />
                  </div>
                </div>

                <div>
                  <label htmlFor="reset-confirm" className="block text-sm font-medium text-th-text mb-1.5">{t('auth.confirmPassword')}</label>
                  <div className="relative">
                    <Lock size={18} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-th-text-s" aria-hidden="true" />
                    <input
                      id="reset-confirm"
                      type="password"
                      autoComplete="new-password"
                      value={confirm}
                      onChange={e => setConfirm(e.target.value)}
                      className="input-field pl-11"
                      placeholder={t('auth.passwordPlaceholder')}
                      required
                    />
                  </div>
                </div>

                <button
                  type="submit"
                  disabled={loading}
                  className="btn-primary w-full py-3"
                >
                  {loading ? (
                    <Loader2 size={18} className="animate-spin" />
                  ) : (
                    <>
                      {t('auth.resetPasswordSubmit')}
                      <ArrowRight size={18} />
                    </>
                  )}
                </button>
              </form>
            </>
          )}

          <Link to="/login" className="block mt-6 text-center text-sm text-th-text-s hover:text-th-text transition-colors">
            {t('auth.backToLogin')}
          </Link>
        </div>
      </div>
    </div>
  );
}
