'use client';

import { useState } from 'react';
import Link from 'next/link';
import { useSearchParams } from 'next/navigation';
import axios from 'axios';
import { useTranslations } from 'next-intl';

const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';

/** Password strength requirements — mirrors the backend validation */
const PASSWORD_RULES = [
  { key: 'length',  label: 'At least 8 characters',        test: (pw: string) => pw.length >= 8 },
  { key: 'upper',   label: 'One uppercase letter',          test: (pw: string) => /[A-Z]/.test(pw) },
  { key: 'lower',   label: 'One lowercase letter',          test: (pw: string) => /[a-z]/.test(pw) },
  { key: 'number',  label: 'One number',                    test: (pw: string) => /[0-9]/.test(pw) },
  { key: 'special', label: 'One special character (!@#$…)', test: (pw: string) => /[^A-Za-z0-9]/.test(pw) },
];

function getStrengthScore(pw: string) {
  return PASSWORD_RULES.filter((r) => r.test(pw)).length;
}

function strengthLabel(score: number): { label: string; color: string } {
  if (score <= 1) return { label: 'Very weak', color: '#ef4444' };
  if (score === 2) return { label: 'Weak',      color: '#f97316' };
  if (score === 3) return { label: 'Fair',      color: '#eab308' };
  if (score === 4) return { label: 'Strong',    color: '#22c55e' };
  return            { label: 'Very strong', color: '#16a34a' };
}

export default function ResetPasswordPage() {
  const t = useTranslations('auth');
  const tc = useTranslations('common');
  const searchParams = useSearchParams();
  const token = searchParams.get('token') ?? '';

  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [success, setSuccess] = useState(false);
  const [error, setError] = useState('');
  const [showRules, setShowRules] = useState(false);

  const strengthScore = getStrengthScore(password);
  const { label: strengthText, color: strengthColor } = strengthLabel(strengthScore);

  const inputClass =
    'w-full px-4 py-2.5 border border-gray-200 rounded-lg bg-gray-50 text-sm outline-none focus:border-brand-purple focus:ring-1 focus:ring-brand-purple focus:bg-white transition';

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError('');

    if (password !== confirmPassword) {
      setError(t('errors.passwordMismatch'));
      return;
    }
    if (strengthScore < PASSWORD_RULES.length) {
      setError(t('errors.passwordWeak'));
      setShowRules(true);
      return;
    }

    setIsLoading(true);
    try {
      await axios.post(`${API_URL}/api/auth/reset-password`, { token, password });
      setSuccess(true);
    } catch (err: unknown) {
      const apiError = (err as { response?: { data?: { error?: string } } })?.response?.data?.error;
      if (apiError === 'Invalid or expired password reset link') {
        setError(t('resetPasswordInvalidToken'));
      } else {
        setError(apiError || tc('error'));
      }
    } finally {
      setIsLoading(false);
    }
  }

  return (
    <div className="min-h-screen flex">
      {/* ── Left panel — brand ── */}
      <div className="hidden lg:flex lg:w-1/2 bg-[#4C1D95] flex-col justify-between p-12 relative overflow-hidden">
        <div className="absolute top-0 right-0 w-80 h-80 rounded-full bg-gradient-to-br from-purple-500 via-pink-500 to-orange-400 opacity-30 translate-x-24 -translate-y-24" />
        <div className="absolute bottom-0 left-0 w-64 h-64 rounded-full bg-gradient-to-tr from-blue-500 via-purple-500 to-pink-500 opacity-20 -translate-x-16 translate-y-16" />
        <div className="absolute bottom-32 right-8 w-40 h-40 rounded-full bg-gradient-to-br from-teal-400 to-blue-500 opacity-20" />

        <Link href="/" className="flex items-center gap-3 relative z-10">
          <img src="/cahootravel-logo.svg" alt="CahooTravel" className="h-10 w-auto brightness-0 invert" />
        </Link>

        <div className="relative z-10">
          <h2 className="text-3xl font-bold text-white leading-snug mb-4">
            {t('brandPanel.headingPrefix')}{' '}
            <span className="bg-gradient-to-r from-yellow-300 via-pink-300 to-blue-300 bg-clip-text text-transparent">
              {t('brandPanel.headingSpan')}
            </span>
          </h2>
          <p className="text-purple-200 text-sm leading-relaxed">
            {t('brandPanel.subheading')}
          </p>
        </div>

        <p className="text-purple-400 text-xs relative z-10">
          {tc('copyright', { year: new Date().getFullYear() })}
        </p>
      </div>

      {/* ── Right panel ── */}
      <div className="flex-1 flex flex-col items-center justify-center px-8 py-12 bg-white">
        {/* Mobile logo */}
        <div className="lg:hidden mb-8">
          <Link href="/">
            <img src="/cahootravel-logo.svg" alt="CahooTravel" className="h-10 w-auto" />
          </Link>
        </div>

        <div className="w-full max-w-sm">
          {/* No token in URL */}
          {!token ? (
            <div className="text-center">
              <p className="text-red-600 text-sm mb-4">{t('resetPasswordInvalidToken')}</p>
              <Link href="/forgot-password" className="text-brand-purple text-sm font-medium hover:underline">
                {t('forgotPasswordSubmit')}
              </Link>
            </div>
          ) : success ? (
            /* ── Success state ── */
            <div className="text-center">
              <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-green-50 mb-6">
                <svg viewBox="0 0 24 24" className="w-8 h-8 text-green-500 fill-none stroke-current stroke-2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M20 6L9 17l-5-5" />
                </svg>
              </div>
              <h1 className="text-2xl font-bold text-gray-900 mb-2">{t('resetPasswordHeading')}</h1>
              <p className="text-gray-500 text-sm leading-relaxed mb-8">{t('resetPasswordSuccess')}</p>
              <Link
                href="/signin"
                className="inline-block bg-brand-purple hover:bg-purple-700 text-white font-semibold py-2.5 px-6 rounded-lg transition-colors text-sm"
              >
                {t('submitSignIn')}
              </Link>
            </div>
          ) : (
            /* ── Form state ── */
            <>
              <h1 className="text-2xl font-bold text-gray-900 mb-1">{t('resetPasswordHeading')}</h1>
              <p className="text-sm text-gray-500 mb-7">{t('resetPasswordSubheading')}</p>

              {error && (
                <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg mb-5 text-sm">
                  {error}
                </div>
              )}

              <form onSubmit={handleSubmit} className="flex flex-col gap-4">
                <div>
                  <label className="block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1.5">
                    {t('resetPasswordNewLabel')}
                  </label>
                  <input
                    type="password"
                    value={password}
                    onChange={(e) => { setPassword(e.target.value); setShowRules(true); }}
                    onFocus={() => setShowRules(true)}
                    className={inputClass}
                    autoComplete="new-password"
                    placeholder={t('passwordPlaceholderNew')}
                    required
                  />

                  {/* Strength bar */}
                  {password.length > 0 && (
                    <div className="mt-2">
                      <div className="flex gap-1 mb-1">
                        {PASSWORD_RULES.map((_, i) => (
                          <div
                            key={i}
                            className="h-1 flex-1 rounded-full transition-colors duration-200"
                            style={{ backgroundColor: i < strengthScore ? strengthColor : '#e5e7eb' }}
                          />
                        ))}
                      </div>
                      <p className="text-xs font-medium" style={{ color: strengthColor }}>{strengthText}</p>
                    </div>
                  )}

                  {/* Requirements checklist */}
                  {showRules && (
                    <ul className="mt-2 flex flex-col gap-1">
                      {PASSWORD_RULES.map((rule) => {
                        const passed = rule.test(password);
                        return (
                          <li key={rule.key} className="flex items-center gap-1.5 text-xs">
                            {passed ? (
                              <svg viewBox="0 0 16 16" className="w-3.5 h-3.5 text-green-500 flex-shrink-0" fill="currentColor">
                                <path d="M13.78 4.22a.75.75 0 010 1.06l-7.25 7.25a.75.75 0 01-1.06 0L2.22 9.28a.75.75 0 011.06-1.06L6 10.94l6.72-6.72a.75.75 0 011.06 0z" />
                              </svg>
                            ) : (
                              <svg viewBox="0 0 16 16" className="w-3.5 h-3.5 text-gray-300 flex-shrink-0" fill="currentColor">
                                <circle cx="8" cy="8" r="6" />
                              </svg>
                            )}
                            <span className={passed ? 'text-green-600' : 'text-gray-400'}>{rule.label}</span>
                          </li>
                        );
                      })}
                    </ul>
                  )}
                </div>

                <div>
                  <label className="block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1.5">
                    {t('resetPasswordConfirmLabel')}
                  </label>
                  <input
                    type="password"
                    value={confirmPassword}
                    onChange={(e) => setConfirmPassword(e.target.value)}
                    className={inputClass}
                    autoComplete="new-password"
                    placeholder={t('confirmPasswordPlaceholder')}
                    required
                  />
                </div>

                <button
                  type="submit"
                  disabled={isLoading}
                  className="w-full bg-brand-purple hover:bg-purple-700 text-white font-semibold py-2.5 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed mt-1"
                >
                  {isLoading ? t('resetPasswordSubmitting') : t('resetPasswordSubmit')}
                </button>
              </form>

              <p className="mt-6 text-center text-sm text-gray-500">
                <Link href="/signin" className="text-brand-purple font-medium hover:underline">
                  {t('backToSignIn')}
                </Link>
              </p>
            </>
          )}
        </div>
      </div>
    </div>
  );
}
