'use client';

import { useState, useEffect, Suspense } from 'react';
import { useSearchParams } from 'next/navigation';
import { Link, useRouter } from '@/i18n/navigation';
import Image from 'next/image';
import { useTranslations } from 'next-intl';
import { resetPassword } from '@/lib/api/auth';

function ResetPasswordContent() {
  const t = useTranslations('auth.resetPassword');
  const tFooter = useTranslations('auth.footerLinks');
  const searchParams = useSearchParams();
  const router = useRouter();
  const [token, setToken] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [success, setSuccess] = useState(false);
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const [tokenError, setTokenError] = useState(false);

  useEffect(() => {
    const tokenFromUrl = searchParams.get('token');
    if (tokenFromUrl) {
      setToken(tokenFromUrl);
    } else {
      setTokenError(true);
    }
  }, [searchParams]);

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

    if (password !== confirmPassword) {
      setError(t('errors.passwordsMismatch'));
      return;
    }

    if (password.length < 12) {
      setError(t('errors.passwordMin'));
      return;
    }

    setLoading(true);

    try {
      await resetPassword(token, password);
      setSuccess(true);
      setTimeout(() => router.push('/login'), 3000);
    } catch (err: any) {
      setError(err.message || t('errors.generic'));
    } finally {
      setLoading(false);
    }
  };

  const tips = t.raw('sidePanel.tips') as string[];

  return (
    <div className="min-h-screen flex">
      <div className="w-full lg:w-1/2 flex flex-col justify-center px-8 sm:px-12 lg:px-16 xl:px-24 bg-white">
        <div className="max-w-md w-full mx-auto">
          <div className="mb-10">
            <Link href="/">
              <Image
                src="/assets/logos/logo-black.svg"
                alt="Xpeditis"
                width={50}
                height={60}
                priority
                className="h-auto"
              />
            </Link>
          </div>

          {tokenError ? (
            <>
              <div className="mb-8">
                <div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mb-6">
                  <svg
                    className="w-8 h-8 text-red-600"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
                    />
                  </svg>
                </div>
                <h1 className="text-h1 text-brand-navy mb-2">{t('invalidTokenTitle')}</h1>
                <p className="text-body text-neutral-600">{t('invalidTokenMessage')}</p>
              </div>
              <Link
                href="/forgot-password"
                className="btn-primary w-full text-center block text-lg"
              >
                {t('requestNew')}
              </Link>
            </>
          ) : success ? (
            <>
              <div className="mb-8">
                <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mb-6">
                  <svg
                    className="w-8 h-8 text-green-600"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M5 13l4 4L19 7"
                    />
                  </svg>
                </div>
                <h1 className="text-h1 text-brand-navy mb-2">{t('successTitle')}</h1>
                <p className="text-body text-neutral-600">{t('successMessage')}</p>
              </div>
              <Link href="/login" className="btn-primary w-full text-center block text-lg">
                {t('goToLogin')}
              </Link>
            </>
          ) : (
            <>
              <div className="mb-8">
                <h1 className="text-h1 text-brand-navy mb-2">{t('title')}</h1>
                <p className="text-body text-neutral-600">{t('subtitle')}</p>
              </div>

              {error && (
                <div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg flex items-start gap-3">
                  <svg
                    className="w-5 h-5 text-red-600 flex-shrink-0 mt-0.5"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
                    />
                  </svg>
                  <p className="text-body-sm text-red-800">{error}</p>
                </div>
              )}

              <form onSubmit={handleSubmit} className="space-y-6">
                <div>
                  <label htmlFor="password" className="label">
                    {t('passwordLabel')}
                  </label>
                  <input
                    id="password"
                    type="password"
                    required
                    value={password}
                    onChange={e => setPassword(e.target.value)}
                    className="input w-full"
                    placeholder="••••••••••••"
                    autoComplete="new-password"
                    disabled={loading}
                  />
                  <p className="mt-1.5 text-body-xs text-neutral-500">{t('passwordHint')}</p>
                </div>

                <div>
                  <label htmlFor="confirmPassword" className="label">
                    {t('confirmPasswordLabel')}
                  </label>
                  <input
                    id="confirmPassword"
                    type="password"
                    required
                    value={confirmPassword}
                    onChange={e => setConfirmPassword(e.target.value)}
                    className="input w-full"
                    placeholder="••••••••••••"
                    autoComplete="new-password"
                    disabled={loading}
                  />
                </div>

                <button
                  type="submit"
                  disabled={loading}
                  className="btn-primary w-full text-lg disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {loading ? t('submitting') : t('submit')}
                </button>
              </form>

              <div className="mt-8 text-center">
                <Link
                  href="/login"
                  className="text-body-sm link flex items-center justify-center gap-2"
                >
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M10 19l-7-7m0 0l7-7m-7 7h18"
                    />
                  </svg>
                  {t('backToLogin')}
                </Link>
              </div>
            </>
          )}

          <div className="mt-8 pt-8 border-t border-neutral-200">
            <div className="flex flex-wrap justify-center gap-6 text-body-sm text-neutral-500">
              <Link href="/contact" className="hover:text-accent transition-colors">
                {tFooter('contact')}
              </Link>
              <Link href="/privacy" className="hover:text-accent transition-colors">
                {tFooter('privacy')}
              </Link>
              <Link href="/terms" className="hover:text-accent transition-colors">
                {tFooter('terms')}
              </Link>
            </div>
          </div>
        </div>
      </div>

      <div className="hidden lg:block lg:w-1/2 relative bg-brand-navy">
        <div className="absolute inset-0 bg-gradient-to-br from-brand-navy to-neutral-800 opacity-95"></div>
        <div className="absolute inset-0 flex flex-col justify-center px-16 xl:px-24 text-white">
          <div className="max-w-xl">
            <h2 className="text-display-sm mb-6 text-white">{t('sidePanel.title')}</h2>
            <p className="text-body-lg text-neutral-200 mb-12">{t('sidePanel.description')}</p>
            <div className="space-y-4">
              {tips.map(tip => (
                <div key={tip} className="flex items-center gap-3">
                  <svg
                    className="w-5 h-5 text-brand-turquoise flex-shrink-0"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M5 13l4 4L19 7"
                    />
                  </svg>
                  <p className="text-body-sm text-neutral-300">{tip}</p>
                </div>
              ))}
            </div>
          </div>
        </div>
        <div className="absolute bottom-0 right-0 opacity-10">
          <svg width="400" height="400" viewBox="0 0 400 400" fill="none">
            <circle
              cx="200"
              cy="200"
              r="150"
              stroke="currentColor"
              strokeWidth="2"
              className="text-white"
            />
            <circle
              cx="200"
              cy="200"
              r="100"
              stroke="currentColor"
              strokeWidth="2"
              className="text-white"
            />
            <circle
              cx="200"
              cy="200"
              r="50"
              stroke="currentColor"
              strokeWidth="2"
              className="text-white"
            />
          </svg>
        </div>
      </div>
    </div>
  );
}

export default function ResetPasswordPage() {
  return (
    <Suspense>
      <ResetPasswordContent />
    </Suspense>
  );
}
