'use client';

import type { CompletionResult } from '@/features/focus-session';
import { copy } from '@/shared/i18n';
import { cn } from '@/shared/lib/cn';
import { useEffect, useState } from 'react';

type EndSessionStage = 'decision' | 'unfinished-confirm';

interface EndSessionConfirmModalProps {
  open: boolean;
  currentGoal: string;
  completionResult?: CompletionResult | null;
  onClose: () => void;
  onFinishHere: () => Promise<CompletionResult | null> | CompletionResult | null;
  onSaveAndReturn: () => Promise<CompletionResult | null> | CompletionResult | null;
  onBackToLobby: () => void;
}

const formatFocusedMinutes = (focusedSeconds: number) => {
  const safeSeconds = Math.max(0, focusedSeconds);
  return Math.max(1, Math.round(safeSeconds / 60));
};

export const EndSessionConfirmModal = ({
  open,
  currentGoal,
  completionResult = null,
  onClose,
  onFinishHere,
  onSaveAndReturn,
  onBackToLobby,
}: EndSessionConfirmModalProps) => {
  const [stage, setStage] = useState<EndSessionStage>('decision');
  const [isSubmitting, setIsSubmitting] = useState(false);

  const endSessionCopy = copy.space.endSession;
  const trimmedGoal = currentGoal.trim() || copy.space.focusHud.goalFallback;
  
  const activeStage = completionResult
    ? completionResult.completionSource === 'manual-end'
      ? 'result-saved'
      : 'result-success'
    : stage;
    
  const focusedMinutes = completionResult
    ? formatFocusedMinutes(completionResult.focusedSeconds)
    : 0;
    
  const hasThoughts = Boolean(completionResult && completionResult.thoughts.length > 0);

  useEffect(() => {
    if (!open) {
      // Add a slight delay before resetting state so the fade-out animation can finish smoothly
      const timer = setTimeout(() => {
        setStage('decision');
        setIsSubmitting(false);
      }, 700);
      return () => clearTimeout(timer);
    }

    const allowEscape = !isSubmitting && !completionResult;
    const handleEscape = (event: KeyboardEvent) => {
      if (event.key === 'Escape' && allowEscape) {
        onClose();
      }
    };

    window.addEventListener('keydown', handleEscape);
    return () => {
      window.removeEventListener('keydown', handleEscape);
    };
  }, [completionResult, isSubmitting, onClose, open]);

  const handleFinishHere = async () => {
    if (isSubmitting) return;
    setIsSubmitting(true);
    try {
      await onFinishHere();
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleSaveAndReturn = async () => {
    if (isSubmitting) return;
    setIsSubmitting(true);
    try {
      await onSaveAndReturn();
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div
      className={cn(
        'pointer-events-none fixed inset-0 z-[70] flex items-center justify-center px-4',
      )}
      aria-hidden={!open}
    >
      {/* Abyssal Backdrop: Direct filter animation to prevent WebKit blur pop-in */}
      <div
        onClick={() => {
          if (activeStage === 'decision' || activeStage === 'unfinished-confirm') {
            onClose();
          }
        }}
        className={cn(
          'absolute inset-0 transition-all duration-1000 ease-[cubic-bezier(0.16,1,0.3,1)] transform-gpu',
          open ? 'bg-black/80 backdrop-blur-[40px] pointer-events-auto' : 'bg-transparent backdrop-blur-none pointer-events-none',
        )}
      >
        <div className={cn("absolute inset-0 bg-[url('/noise.png')] mix-blend-overlay pointer-events-none transition-opacity duration-1000", open ? "opacity-20" : "opacity-0")} />
        <div className={cn("absolute inset-0 bg-[radial-gradient(circle_at_center,rgba(255,255,255,0.03)_0%,transparent_70%)] pointer-events-none transition-opacity duration-1000", open ? "opacity-100" : "opacity-0")} />
      </div>

      <div
        className={cn(
          'relative flex w-full max-w-2xl flex-col items-center text-center transition-all duration-1000 ease-[cubic-bezier(0.16,1,0.3,1)]',
          'max-h-[100dvh] overflow-y-auto overscroll-y-contain py-12 sm:py-16 [&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none]',
          open ? 'pointer-events-auto translate-y-0 scale-100 opacity-100' : 'pointer-events-none translate-y-12 scale-[0.98] opacity-0',
        )}
      >
        {activeStage === 'decision' ? (
          <div className="flex w-full flex-col items-center animate-in fade-in slide-in-from-bottom-8 duration-1000">
            <p className="mb-6 text-[10px] font-medium uppercase tracking-[0.4em] text-white/30 drop-shadow-sm">
              {endSessionCopy.decision.eyebrow}
            </p>
            <h3
              id="end-session-title"
              className="mb-12 text-4xl font-extralight tracking-tight text-white/90 md:text-5xl drop-shadow-[0_0_40px_rgba(255,255,255,0.1)]"
            >
              {endSessionCopy.decision.title}
            </h3>

            {/* Volumetric Card */}
            <div className="mb-14 w-full max-w-lg rounded-3xl border border-white/[0.04] bg-white/[0.02] p-8 shadow-[inset_0_0_20px_rgba(255,255,255,0.01),0_20px_40px_rgba(0,0,0,0.4)] backdrop-blur-md">
              <p className="mb-4 text-[9px] font-semibold uppercase tracking-[0.3em] text-white/30">
                {endSessionCopy.decision.goalLabel}
              </p>
              <p className="text-xl font-light leading-relaxed tracking-wide text-white/80">{trimmedGoal}</p>
            </div>

            <div className="flex w-full max-w-md flex-col gap-4 sm:flex-row">
              {/* Primary CTA (The Pearl) */}
              <button
                type="button"
                onClick={handleFinishHere}
                disabled={isSubmitting}
                className="group relative flex-1 overflow-hidden rounded-full bg-white px-6 py-4 text-[14px] font-medium text-black transition-all duration-500 hover:scale-[1.02] hover:shadow-[0_0_40px_rgba(255,255,255,0.2)] active:scale-[0.98] disabled:opacity-50"
              >
                <div className="absolute inset-0 bg-gradient-to-t from-black/5 to-transparent opacity-0 transition-opacity duration-500 group-hover:opacity-100" />
                <span className="relative z-10">
                  {isSubmitting
                    ? copy.space.goalComplete.finishPending
                    : endSessionCopy.decision.finishedAnswer}
                </span>
              </button>
              
              {/* Secondary CTA (Ghost Button) */}
              <button
                type="button"
                onClick={() => setStage('unfinished-confirm')}
                disabled={isSubmitting}
                className="flex-1 rounded-full border border-white/10 bg-transparent px-6 py-4 text-[14px] font-light text-white/60 transition-all duration-500 hover:border-white/20 hover:bg-white/[0.03] hover:text-white/90 active:scale-[0.98] disabled:opacity-50"
              >
                {endSessionCopy.decision.unfinishedAnswer}
              </button>
            </div>

            <button
              type="button"
              onClick={onClose}
              disabled={isSubmitting}
              className="mt-10 text-[11px] font-light uppercase tracking-widest text-white/20 transition-all duration-300 hover:text-white/60 disabled:opacity-50"
            >
              {endSessionCopy.decision.cancelButton}
            </button>
          </div>
        ) : null}

        {activeStage === 'unfinished-confirm' ? (
          <div className="flex w-full flex-col items-center animate-in fade-in zoom-in-95 duration-700">
            <div className="mb-10 inline-flex h-16 w-16 items-center justify-center rounded-full border border-white/5 bg-white/[0.02] shadow-[inset_0_0_15px_rgba(255,255,255,0.02)] backdrop-blur-md" />
            <p className="mb-4 text-[10px] font-medium uppercase tracking-[0.4em] text-white/30">
              {endSessionCopy.unfinishedConfirm.eyebrow}
            </p>
            <h3
              id="end-session-title"
              className="mb-6 text-3xl font-extralight tracking-tight text-white/90 md:text-4xl"
            >
              {endSessionCopy.unfinishedConfirm.title}
            </h3>
            <p className="mb-12 max-w-md text-[15px] font-light leading-relaxed text-white/50">
              {endSessionCopy.unfinishedConfirm.description}
            </p>

            <div className="mb-14 w-full max-w-lg rounded-3xl border border-white/[0.04] bg-white/[0.02] p-8 shadow-[inset_0_0_20px_rgba(255,255,255,0.01),0_20px_40px_rgba(0,0,0,0.4)] backdrop-blur-md">
              <p className="mb-4 text-[9px] font-semibold uppercase tracking-[0.3em] text-white/30">
                {endSessionCopy.decision.goalLabel}
              </p>
              <p className="text-xl font-light leading-relaxed tracking-wide text-white/80">{trimmedGoal}</p>
            </div>

            <div className="flex w-full max-w-md flex-col gap-4 sm:flex-row">
              <button
                type="button"
                onClick={onClose}
                disabled={isSubmitting}
                className="flex-1 rounded-full border border-white/10 bg-transparent px-6 py-4 text-[14px] font-light text-white/60 transition-all duration-500 hover:border-white/20 hover:bg-white/[0.03] hover:text-white/90 active:scale-[0.98] disabled:opacity-50"
              >
                {endSessionCopy.unfinishedConfirm.keepFocusingButton}
              </button>
              <button
                type="button"
                onClick={handleSaveAndReturn}
                disabled={isSubmitting}
                className="group relative flex-1 overflow-hidden rounded-full bg-white px-6 py-4 text-[14px] font-medium text-black transition-all duration-500 hover:scale-[1.02] hover:shadow-[0_0_40px_rgba(255,255,255,0.2)] active:scale-[0.98] disabled:opacity-50"
              >
                 <div className="absolute inset-0 bg-gradient-to-t from-black/5 to-transparent opacity-0 transition-opacity duration-500 group-hover:opacity-100" />
                 <span className="relative z-10">
                  {isSubmitting
                    ? endSessionCopy.unfinishedConfirm.saveAndReturnPending
                    : endSessionCopy.unfinishedConfirm.saveAndReturnButton}
                 </span>
              </button>
            </div>
          </div>
        ) : null}

        {(activeStage === 'result-success' || activeStage === 'result-saved') && completionResult ? (
          <div className="flex w-full flex-col items-center">
            {/* Stage dependent subtle glow */}
            <div className={cn(
               "mb-10 inline-flex h-16 w-16 items-center justify-center rounded-full border border-white/10 backdrop-blur-md animate-in fade-in zoom-in duration-1000",
               activeStage === 'result-success' 
                ? "bg-white/[0.04] shadow-[0_0_50px_rgba(255,255,255,0.1),inset_0_0_20px_rgba(255,255,255,0.05)]" 
                : "bg-white/[0.02] shadow-[inset_0_0_15px_rgba(255,255,255,0.02)]"
            )} />
            
            <p className="mb-4 text-[10px] font-medium uppercase tracking-[0.4em] text-white/30 animate-in fade-in slide-in-from-bottom-4 duration-1000 delay-150 fill-mode-both">
              {activeStage === 'result-success' ? endSessionCopy.resultSuccess.eyebrow : endSessionCopy.resultSaved.eyebrow}
            </p>
            <h3
              id="end-session-title"
              className="mb-8 text-4xl font-extralight tracking-tight text-white/90 md:text-5xl animate-in fade-in slide-in-from-bottom-4 duration-1000 delay-300 fill-mode-both drop-shadow-[0_0_40px_rgba(255,255,255,0.1)]"
            >
              {activeStage === 'result-success' ? endSessionCopy.resultSuccess.title : endSessionCopy.resultSaved.title}
            </h3>
            <p className="mb-14 max-w-md text-[15px] font-light leading-relaxed text-white/50 animate-in fade-in slide-in-from-bottom-4 duration-1000 delay-500 fill-mode-both">
              {activeStage === 'result-success' ? endSessionCopy.resultSuccess.description : endSessionCopy.resultSaved.description}
            </p>

            <div className="mb-16 flex w-full max-w-lg flex-col gap-4 animate-in fade-in slide-in-from-bottom-8 duration-1000 delay-700 fill-mode-both">
              {/* The Hero Number */}
              <div className="rounded-3xl border border-white/[0.04] bg-white/[0.01] px-6 py-10 text-center shadow-[inset_0_0_30px_rgba(255,255,255,0.01),0_20px_40px_rgba(0,0,0,0.3)] backdrop-blur-xl relative overflow-hidden">
                <div className="absolute inset-0 bg-[radial-gradient(ellipse_at_top,rgba(255,255,255,0.05),transparent_50%)] pointer-events-none" />
                <p className="mb-3 text-[9px] font-semibold uppercase tracking-[0.4em] text-white/30">
                  {endSessionCopy.resultSuccess.focusedLabel}
                </p>
                <div className="relative inline-block">
                  <div className="absolute inset-0 bg-white/20 blur-[40px] rounded-full" />
                  <p className="relative text-7xl font-thin tracking-tighter text-white drop-shadow-md md:text-8xl">
                    {focusedMinutes}
                    <span className="ml-2 text-4xl font-light text-white/30">m</span>
                  </p>
                </div>
              </div>

              {activeStage === 'result-saved' && (
                <div className="rounded-3xl border border-white/[0.03] bg-white/[0.01] px-8 py-6 text-left shadow-[0_10px_30px_rgba(0,0,0,0.2)] backdrop-blur-md">
                  <p className="mb-3 text-[9px] font-semibold uppercase tracking-[0.3em] text-white/30">
                    {endSessionCopy.resultSaved.goalStatusLabel}
                  </p>
                  <p className="text-[13px] font-light uppercase tracking-[0.2em] text-white/50">
                    {endSessionCopy.resultSaved.goalStatusValue}
                  </p>
                </div>
              )}

              <div className="rounded-3xl border border-white/[0.03] bg-white/[0.01] px-8 py-7 text-left shadow-[0_10px_30px_rgba(0,0,0,0.2)] backdrop-blur-md">
                <p className="mb-4 text-[9px] font-semibold uppercase tracking-[0.3em] text-white/30">
                  {endSessionCopy.resultSuccess.goalLabel}
                </p>
                <p className="text-[17px] font-light leading-relaxed tracking-wide text-white/80">
                  {completionResult.goalText}
                </p>
              </div>

              {hasThoughts ? (
                <div className="rounded-3xl border border-white/[0.03] bg-white/[0.01] px-8 py-7 text-left shadow-[0_10px_30px_rgba(0,0,0,0.2)] backdrop-blur-md">
                  <div className="mb-5 flex items-center justify-between">
                    <p className="text-[9px] font-semibold uppercase tracking-[0.3em] text-white/30">
                      {endSessionCopy.resultSuccess.thoughtsLabel}
                    </p>
                    <span className="inline-flex h-5 items-center justify-center rounded-full border border-white/10 bg-white/5 px-2.5 text-[9px] font-medium text-white/50">
                      {completionResult.thoughts.length}
                    </span>
                  </div>
                  <div className="space-y-3">
                    {completionResult.thoughts.map((thought) => (
                      <div
                        key={thought.id}
                        className="rounded-2xl border border-white/[0.02] bg-black/40 px-5 py-4"
                      >
                        <p className="text-[14px] font-light leading-relaxed text-white/70">
                          {thought.text}
                        </p>
                      </div>
                    ))}
                  </div>
                </div>
              ) : null}
            </div>

            <div className="animate-in fade-in slide-in-from-bottom-4 duration-1000 delay-1000 fill-mode-both">
              <button
                type="button"
                onClick={onBackToLobby}
                className="group relative overflow-hidden rounded-full bg-white px-14 py-5 text-[14px] font-medium text-black transition-all duration-500 hover:scale-[1.03] hover:shadow-[0_0_50px_rgba(255,255,255,0.25)] active:scale-[0.98]"
              >
                <div className="absolute inset-0 bg-gradient-to-t from-black/5 to-transparent opacity-0 transition-opacity duration-500 group-hover:opacity-100" />
                <span className="relative z-10">
                  {activeStage === 'result-success' ? endSessionCopy.resultSuccess.backToLobby : endSessionCopy.resultSaved.backToLobby}
                </span>
              </button>
            </div>
            
          </div>
        ) : null}
      </div>
    </div>
  );
};
