// components/UpdatePasswordLogic.tsx
'use client';

import { useState, useEffect } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { createClientComponentClient } from '@supabase/auth-helpers-nextjs';
import type { SupabaseClient } from '@supabase/supabase-js';

export default function UpdatePasswordLogic() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const supabase: SupabaseClient = createClientComponentClient();

  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [message, setMessage] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  const [status, setStatus] = useState<'validating' | 'ready' | 'invalid'>('validating');

  useEffect(() => {
    let isMounted = true;

    const code = searchParams.get('code');

    if (!code) {
      setStatus('invalid');
      setError('Link de redefinição inválido ou expirado.');
      setTimeout(() => router.push('/login'), 5000);
      return;
    }

    const processCode = async () => {
      try {
        const { error } = await supabase.auth.exchangeCodeForSession(code);

        if (error) {
          setStatus('invalid');
          setError('Link de redefinição inválido ou expirado.');
          setTimeout(() => router.push('/login'), 5000);
          return;
        }

        if (isMounted) {
          setStatus('ready');
        }
      } catch (err: any) {
        setStatus('invalid');
        setError('Erro inesperado ao validar o link.');
        setTimeout(() => router.push('/login'), 5000);
      }
    };

    processCode();

    return () => {
      isMounted = false;
    };

  }, [searchParams, supabase, router]);

  const handleUpdatePassword = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setError(null);
    setMessage(null);

    if (password !== confirmPassword) {
      setError('As senhas não coincidem.');
      return;
    }
    if (password.length < 6) {
      setError('A senha deve ter no mínimo 6 caracteres.');
      return;
    }

    setLoading(true);

    try {
      const { error: updateError } = await supabase.auth.updateUser({
        password: password
      });

      if (updateError) throw updateError;

      setMessage('Senha atualizada com sucesso! Redirecionando para o login...');

      await supabase.auth.signOut();

      setTimeout(() => {
        router.push('/login');
      }, 3000);

    } catch (err: any) {
      setError(err.message || 'Erro ao atualizar a senha.');
    } finally {
      setLoading(false);
    }
  };

  if (status === 'validating') {
    return (
      <div className="flex flex-col items-center justify-center min-h-screen bg-gray-50 p-4">
        <div className="w-full max-w-md p-8 space-y-6 bg-white rounded-lg shadow-md text-center">
          <h2 className="text-2xl font-bold text-gray-800">Verificando Link</h2>
          <p className="text-gray-600">
            Aguarde um momento enquanto validamos seu link de recuperação de senha.
          </p>
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600 mx-auto"></div>
        </div>
      </div>
    );
  }

  return (
    <div className="flex items-center justify-center min-h-screen bg-gray-50 p-4">
      <div className="w-full max-w-md p-8 space-y-6 bg-white rounded-lg shadow-md">
        {status === 'ready' ? (
          <>
            <h2 className="text-2xl font-bold text-center text-gray-800">Crie sua nova senha</h2>
            <p className="text-center text-gray-600">
              Digite e confirme sua nova senha de acesso abaixo.
            </p>

            <form onSubmit={handleUpdatePassword} className="space-y-6">
              <div>
                <label htmlFor="password" className="block text-sm font-medium text-gray-700">Nova Senha</label>
                <input
                  id="password"
                  name="password"
                  type="password"
                  required
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  className="w-full px-3 py-2 mt-1 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500"
                  placeholder="••••••••"
                  minLength={6}
                />
              </div>

              <div>
                <label htmlFor="confirmPassword" className="block text-sm font-medium text-gray-700">Confirmar Nova Senha</label>
                <input
                  id="confirmPassword"
                  name="confirmPassword"
                  type="password"
                  required
                  value={confirmPassword}
                  onChange={(e) => setConfirmPassword(e.target.value)}
                  className="w-full px-3 py-2 mt-1 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500"
                  placeholder="••••••••"
                  minLength={6}
                />
              </div>

              <div>
                <button
                  type="submit"
                  disabled={loading}
                  className="w-full px-4 py-2 font-medium text-white bg-indigo-600 rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:bg-indigo-400 disabled:cursor-not-allowed"
                >
                  {loading ? 'Atualizando...' : 'Atualizar Senha'}
                </button>
              </div>
            </form>
          </>
        ) : null}

        {error && (
          <div className="p-4 mt-4 text-sm text-red-700 bg-red-100 rounded-lg" role="alert">
            <span className="font-medium">Erro:</span> {error}
          </div>
        )}

        {message && (
          <div className="p-4 mt-4 text-sm text-green-700 bg-green-100 rounded-lg" role="alert">
            <span className="font-medium">Sucesso:</span> {message}
          </div>
        )}
      </div>
    </div>
  );
}