import { useEffect, useRef } from 'react';
import { ArrowLeft } from 'lucide-react';
import { motion } from 'framer-motion';
import { useTranslation } from 'react-i18next';
import { useBriefTasks } from '@/hooks/useBriefTasks';
import { useTaskBriefing } from '@/context/TaskBriefingContext';
import { TaskCarousel, clearCarouselBriefingCache } from './TaskCarousel';
import { TaskBriefEmptyState } from './TaskBriefEmptyState';
import { Skeleton } from '@/components/ui/skeleton';
import { Button } from '@/components/ui/button';
import { SidebarTrigger } from '@/components/ui/sidebar';
import { Separator } from '@/components/ui/separator';

/**
 * Inline task briefing section — renders inside the home page content area.
 * No overlay/backdrop/fixed positioning; the parent hides/shows this via AnimatePresence.
 */
export function TaskBriefingOverlay() {
  const { close, initialTaskId } = useTaskBriefing();
  const { t } = useTranslation();
  const { tasks, isLoading } = useBriefTasks();
  const backBtnRef = useRef<HTMLButtonElement>(null);

  // ESC to close
  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if (e.key === 'Escape') close();
    };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [close]);

  // Focus back button on mount
  useEffect(() => {
    backBtnRef.current?.focus();
  }, []);

  // Clear session cache when unmounted (i.e. closed)
  useEffect(() => {
    return () => clearCarouselBriefingCache();
  }, []);

  return (
    <motion.div
      className="flex flex-col h-full w-full"
      initial={{ opacity: 0, x: 24 }}
      animate={{ opacity: 1, x: 0 }}
      exit={{ opacity: 0, x: 24 }}
      transition={{ type: 'spring', stiffness: 400, damping: 38 }}
    >
      {/* Top bar — mirrors note page: SidebarTrigger | sep | back */}
      <div className="flex h-14 shrink-0 items-center gap-1 px-3">
        <SidebarTrigger />
        <Separator orientation="vertical" className="data-[orientation=vertical]:h-4" />
        <Button
          ref={backBtnRef}
          variant="ghost"
          size="icon"
          className="h-7 w-7"
          onClick={close}
          aria-label={t('brief.controls.close')}
        >
          <ArrowLeft className="h-4 w-4" />
        </Button>
        <span className="ml-auto text-xs text-muted-foreground/60">
          {t('brief.overlayTitle')}
        </span>
      </div>

      {/* Content */}
      <div className="flex-1 min-h-0">
        {isLoading ? (
          <div className="p-8 space-y-3">
            <Skeleton className="h-5 w-1/2" />
            <Skeleton className="h-5 w-1/3" />
          </div>
        ) : tasks.length === 0 ? (
          <TaskBriefEmptyState />
        ) : (
          <TaskCarousel tasks={tasks} initialTaskId={initialTaskId} />
        )}
      </div>
    </motion.div>
  );
}
