import type { NextPage } from 'next';
import Head from 'next/head';
import { useState, useEffect } from 'react';
import { useRouter } from 'next/router';
import Link from 'next/link';
import toast from 'react-hot-toast';

const ResetPassword: NextPage = () => {
  const router = useRouter();
  const { token } = router.query;
  
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [isVerifying, setIsVerifying] = useState(true);
  const [error, setError] = useState('');
  const [passwordError, setPasswordError] = useState('');
  const [isTokenValid, setIsTokenValid] = useState(false);

  // Verifikuj token při mountingu
  useEffect(() => {
    if (!token) return;

    const verifyToken = async () => {
      try {
        const response = await fetch(`/api/auth/reset-password?token=${token}`, {
          method: 'GET',
        });

        const data = await response.json();

        if (response.ok && data.valid) {
          setIsTokenValid(true);
        } else {
          setError(data.error || 'Token je neplatný nebo vypršel');
        }
      } catch (err) {
        setError('Chyba při ověřování tokenu');
      } finally {
        setIsVerifying(false);
      }
    };

    verifyToken();
  }, [token]);

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

    // Validace hesel
    if (password !== confirmPassword) {
      setPasswordError('Hesla se neshodují');
      return;
    }

    if (password.length < 8) {
      setPasswordError('Heslo musí mít alespoň 8 znaků');
      return;
    }

    setIsLoading(true);

    try {
      const response = await fetch('/api/auth/reset-password', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          token,
          password,
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        setError(data.error || 'Reset hesla se nezdařil');
        toast.error(data.error || 'Reset hesla se nezdařil');
        return;
      }

      toast.success('Heslo bylo úspěšně resetováno!');
      
      // Přesměr na login po 2 sekundách
      setTimeout(() => {
        router.push('/login');
      }, 2000);
    } catch (err) {
      setError('Reset hesla se nezdařil. Prosím zkuste znovu.');
      toast.error('Reset hesla se nezdařil');
    } finally {
      setIsLoading(false);
    }
  };

  if (isVerifying) {
    return (
      <>
        <Head>
          <title>Reset hesla | Vystříkejto.cz</title>
          <meta name="robots" content="noindex,nofollow,noarchive" />
        </Head>
        <div className="min-h-screen w-full flex items-center justify-center bg-luxury-dark pt-16 pb-8">
          <div className="w-full max-w-md mx-auto px-4">
            <div className="bg-luxury-dark border border-luxury-gold/30 rounded-xl shadow-2xl p-8 text-center">
              <div className="animate-spin rounded-full h-12 w-12 border border-luxury-gold/30 border-t-luxury-gold mx-auto mb-4"></div>
              <p className="text-luxury-light/70">Ověřuji váš reset link...</p>
            </div>
          </div>
        </div>
      </>
    );
  }

  // Token není platný
  if (!isTokenValid) {
    return (
      <>
        <Head>
          <title>Reset hesla | Vystříkejto.cz</title>
          <meta name="robots" content="noindex,nofollow,noarchive" />
        </Head>
        <div className="min-h-screen w-full flex items-center justify-center bg-luxury-dark pt-16 sm:pt-20 md:pt-32 pb-8">
          <div className="w-full max-w-md mx-auto px-4">
            <div className="bg-luxury-dark border border-luxury-gold/30 rounded-xl shadow-2xl p-8">
              <div className="mb-6 p-4 bg-red-500/10 border border-red-500/30 rounded-lg">
                <p className="text-red-400 text-sm font-semibold mb-2">Neplatný nebo vypršený odkaz</p>
                <p className="text-red-400 text-xs">{error}</p>
              </div>

              <div className="space-y-4 text-center">
                <p className="text-luxury-light/70 text-sm">
                  Odkaz pro reset hesla je neplatný nebo vypršel (platnost 24 hodin).
                </p>
                
                <Link
                  href="/forgot-password"
                  className="inline-block w-full py-3 bg-luxury-gold hover:bg-yellow-400 text-luxury-dark font-bold rounded-lg transition-colors duration-300 text-sm"
                >
                  Požádat o nový reset link
                </Link>

                <p className="text-luxury-light/50 text-xs">
                  <Link href="/login" className="text-luxury-gold hover:text-yellow-300 transition-colors">
                    Zpět na přihlášení
                  </Link>
                </p>
              </div>
            </div>
          </div>
        </div>
      </>
    );
  }

  // Form pro reset hesla
  return (
    <>
      <Head>
        <title>Reset hesla | Vystříkejto.cz</title>
        <meta name="robots" content="noindex,nofollow,noarchive" />
      </Head>
      <div className="min-h-screen w-full flex items-center justify-center bg-luxury-dark pt-16 sm:pt-20 md:pt-32 pb-8">
        <div className="w-full max-w-md mx-auto px-4">
          {/* Card Container */}
          <div className="bg-luxury-dark border border-luxury-gold/30 rounded-xl shadow-2xl p-8">
            {/* Header */}
            <div className="mb-8 text-center">
              <h1 className="text-4xl sm:text-5xl font-aptos font-black text-luxury-gold mb-2">
                Nové heslo
              </h1>
              <p className="text-luxury-light/70 text-sm">
                Zadejte nové heslo pro váš účet
              </p>
            </div>

            {/* Error Message */}
            {error && (
              <div className="mb-6 p-4 bg-red-500/10 border border-red-500/30 rounded-lg">
                <p className="text-red-400 text-sm">{error}</p>
              </div>
            )}

            {/* Form */}
            <form onSubmit={handleSubmit} className="space-y-6">
              {/* Password Input */}
              <div>
                <label htmlFor="password" className="block text-luxury-light text-sm font-medium mb-2">
                  Nové heslo <span className="text-red-400">*</span>
                </label>
                <input
                  type="password"
                  id="password"
                  name="password"
                  value={password}
                  onChange={(e) => {
                    setPassword(e.target.value);
                    setPasswordError('');
                  }}
                  placeholder="Minimálně 8 znaků"
                  autoComplete="new-password"
                  className="w-full px-4 py-3 bg-luxury-light/10 border border-luxury-gold/30 rounded-lg text-luxury-light placeholder:text-luxury-light/40 focus:outline-none focus:ring-2 focus:ring-luxury-gold focus:border-transparent transition-all"
                  required
                  disabled={isLoading}
                />
                <p className="text-luxury-light/50 text-xs mt-1">
                  Heslo musí obsahovat alespoň 8 znaků
                </p>
              </div>

              {/* Confirm Password Input */}
              <div>
                <label htmlFor="confirmPassword" className="block text-luxury-light text-sm font-medium mb-2">
                  Potvrzení hesla <span className="text-red-400">*</span>
                </label>
                <input
                  type="password"
                  id="confirmPassword"
                  name="confirmPassword"
                  value={confirmPassword}
                  onChange={(e) => {
                    setConfirmPassword(e.target.value);
                    setPasswordError('');
                  }}
                  placeholder="Zopakujte heslo"
                  autoComplete="new-password"
                  className={`w-full px-4 py-3 bg-luxury-light/10 border rounded-lg text-luxury-light placeholder:text-luxury-light/40 focus:outline-none focus:ring-2 focus:border-transparent transition-all ${
                    passwordError
                      ? 'border-red-500/50 focus:ring-red-500'
                      : 'border-luxury-gold/30 focus:ring-luxury-gold'
                  }`}
                  required
                  disabled={isLoading}
                />
                {passwordError && (
                  <p className="text-red-400 text-xs mt-1">{passwordError}</p>
                )}
              </div>

              {/* Info Box */}
              <div className="p-4 bg-blue-500/10 border border-blue-500/30 rounded-lg">
                <p className="text-blue-400 text-xs leading-relaxed">
                  Heslo musí obsahovat alespoň 8 znaků. Doporučujeme používat kombinaci velkých a malých písmen, číslic a speciálních znaků.
                </p>
              </div>

              {/* Submit Button */}
              <button
                type="submit"
                disabled={isLoading || !password || !confirmPassword}
                className="w-full py-3 bg-luxury-gold hover:bg-yellow-400 text-luxury-dark font-bold rounded-lg transition-colors duration-300 disabled:opacity-50 disabled:cursor-not-allowed text-lg"
              >
                {isLoading ? 'Resetuji heslo...' : 'Resetovat heslo'}
              </button>
            </form>

            {/* Info Text */}
            <div className="mt-8 p-4 bg-luxury-gold/5 border border-luxury-gold/20 rounded-lg">
              <p className="text-luxury-light/50 text-xs text-center">
                Potřebujete pomoc? <Link href="/" className="text-luxury-gold hover:text-yellow-300 transition-colors">Kontaktujte podporu</Link>.
              </p>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

export default ResetPassword;
