import React from 'react';
import { useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';

import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';

import { AdminLayout } from '../components/AdminLayout';
import { TasksSection } from './TasksPage';
import { TaskCollectionsSection } from './TaskCollectionsPage';
import { EmotionsSection } from './EmotionsPage';

const TAB_KEYS = ['tasks', 'collections', 'emotions'] as const;
type EngagementTab = (typeof TAB_KEYS)[number];

function ensureValidTab(value: string | null): EngagementTab {
  if (value && (TAB_KEYS as readonly string[]).includes(value)) {
    return value as EngagementTab;
  }
  return 'tasks';
}

export default function EngagementPage(): JSX.Element {
  const { t } = useTranslation('management');
  const { t: tc } = useTranslation('common');
  const [searchParams, setSearchParams] = useSearchParams();

  const initialTab = React.useMemo(() => ensureValidTab(searchParams.get('tab')), [searchParams]);
  const [activeTab, setActiveTab] = React.useState<EngagementTab>(initialTab);

  const handleTabChange = React.useCallback(
    (next: string) => {
      const valid = ensureValidTab(next);
      setActiveTab(valid);
      setSearchParams((prev) => {
        const params = new URLSearchParams(prev);
        params.set('tab', valid);
        return params;
      });
    },
    [setSearchParams]
  );

  const heading = tc('navigation.engagement');

  return (
    <AdminLayout
      title={heading}
      subtitle={t('engagement.subtitle', 'Bündle Aufgaben, Vorlagen und Emotionen für deine Events.')}
    >
      <Tabs value={activeTab} onValueChange={handleTabChange} className="space-y-6">
        <TabsList className="grid w-full grid-cols-3 bg-white/60 shadow-sm">
          <TabsTrigger value="tasks">{tc('navigation.tasks')}</TabsTrigger>
          <TabsTrigger value="collections">{tc('navigation.collections')}</TabsTrigger>
          <TabsTrigger value="emotions">{tc('navigation.emotions')}</TabsTrigger>
        </TabsList>

        <TabsContent value="tasks" className="space-y-6">
          <TasksSection
            embedded
            onNavigateToCollections={() => handleTabChange('collections')}
          />
        </TabsContent>

        <TabsContent value="collections" className="space-y-6">
          <TaskCollectionsSection
            embedded
            onNavigateToTasks={() => handleTabChange('tasks')}
          />
        </TabsContent>

        <TabsContent value="emotions" className="space-y-6">
          <EmotionsSection embedded />
        </TabsContent>
      </Tabs>
    </AdminLayout>
  );
}
