"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import Link from "next/link";
import { Mail, ArrowLeft, Clock, CheckCircle2 } from "lucide-react";
import { AuthLayout } from "../components";
import { PasswordResetForm } from "@/features/auth/components";
import { Button, AnimatedContainer } from "@/components/atoms";
import { useAuthStore } from "../stores/auth.store";

const RESEND_COOLDOWN_SECONDS = 60;

function EmailSentConfirmation({
  email,
  cooldownEndRef,
  onBackToForm,
}: {
  email: string;
  cooldownEndRef: React.RefObject<number>;
  onBackToForm: () => void;
}) {
  const [secondsLeft, setSecondsLeft] = useState(() =>
    Math.max(0, Math.ceil((cooldownEndRef.current - Date.now()) / 1000))
  );
  const [resending, setResending] = useState(false);
  const [resendError, setResendError] = useState<string | null>(null);
  const [resendCount, setResendCount] = useState(0);
  const requestPasswordReset = useAuthStore(state => state.requestPasswordReset);

  useEffect(() => {
    const update = () => {
      const remaining = Math.max(0, Math.ceil((cooldownEndRef.current - Date.now()) / 1000));
      setSecondsLeft(remaining);
    };
    update();
    const interval = setInterval(update, 1000);
    return () => clearInterval(interval);
  }, [cooldownEndRef]);

  const handleResend = useCallback(async () => {
    setResending(true);
    setResendError(null);
    try {
      await requestPasswordReset(email);
      cooldownEndRef.current = Date.now() + RESEND_COOLDOWN_SECONDS * 1000;
      setSecondsLeft(RESEND_COOLDOWN_SECONDS);
      setResendCount(c => c + 1);
    } catch {
      setResendError("Failed to resend. Please try again.");
    } finally {
      setResending(false);
    }
  }, [email, requestPasswordReset, cooldownEndRef]);

  const canResend = secondsLeft === 0 && !resending;

  return (
    <AnimatedContainer animation="fade-up">
      <div className="w-full space-y-6">
        <div className="text-center space-y-2">
          <div className="mx-auto w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center mb-4">
            <Mail className="w-6 h-6 text-primary" />
          </div>
          <h2 className="text-xl font-semibold text-foreground">Check your email</h2>
          <p className="text-sm text-muted-foreground">
            We sent a password reset link to{" "}
            <span className="font-medium text-foreground">{email}</span>
          </p>
        </div>

        <div className="rounded-lg border border-border bg-muted/30 p-4 space-y-3">
          <div className="flex items-start gap-3">
            <CheckCircle2 className="w-5 h-5 text-green-500 mt-0.5 shrink-0" />
            <div className="text-sm text-muted-foreground space-y-1">
              <p>Click the link in the email to reset your password.</p>
              <p>The link expires in 15 minutes.</p>
            </div>
          </div>
        </div>

        {resendCount > 0 && (
          <p className="text-xs text-center text-green-600">Reset link resent successfully</p>
        )}

        <div className="space-y-3">
          {canResend ? (
            <Button
              variant="outline"
              className="w-full"
              onClick={() => void handleResend()}
              disabled={resending}
              loading={resending}
            >
              Resend reset link
            </Button>
          ) : (
            <div className="flex items-center justify-center gap-2 text-sm text-muted-foreground">
              <Clock className="w-4 h-4" />
              <span>Resend available in {secondsLeft}s</span>
            </div>
          )}

          {resendError && <p className="text-sm text-center text-red-600">{resendError}</p>}
        </div>

        <div className="space-y-2">
          <button
            type="button"
            onClick={onBackToForm}
            className="flex items-center justify-center gap-2 w-full text-sm text-muted-foreground hover:text-foreground transition-colors duration-200"
          >
            <ArrowLeft className="w-4 h-4" />
            <span>Try a different email</span>
          </button>
          <Link
            href="/auth/login"
            className="block text-center text-sm text-primary hover:underline font-medium transition-colors duration-[var(--cp-duration-normal)]"
          >
            Back to login
          </Link>
        </div>

        <p className="text-xs text-center text-muted-foreground">
          Didn&apos;t receive the email? Check your spam folder or try resending.
        </p>
      </div>
    </AnimatedContainer>
  );
}

export function ForgotPasswordView() {
  const [sentToEmail, setSentToEmail] = useState<string | null>(null);
  // Cooldown persists across form/confirmation transitions — prevents bypass
  const cooldownEndRef = useRef(0);

  const handleSuccess = useCallback((email?: string) => {
    if (email) {
      cooldownEndRef.current = Date.now() + RESEND_COOLDOWN_SECONDS * 1000;
      setSentToEmail(email);
    }
  }, []);

  if (sentToEmail) {
    return (
      <AuthLayout title="Forgot password" subtitle="Follow the instructions in your email">
        <EmailSentConfirmation
          email={sentToEmail}
          cooldownEndRef={cooldownEndRef}
          onBackToForm={() => setSentToEmail(null)}
        />
      </AuthLayout>
    );
  }

  return (
    <AuthLayout
      title="Forgot password"
      subtitle="Enter your email address and we'll send you a reset link"
    >
      <PasswordResetForm mode="request" onSuccess={handleSuccess} />
    </AuthLayout>
  );
}

export default ForgotPasswordView;
