import { useMemo, useCallback } from 'react';
import { Drawer, Progress, Typography, Collapse, Button, Grid, theme } from 'antd';
import { useNavigate } from 'react-router-dom';
import { useTourStore } from '../../stores/tour.store';
import { useSettingsStore } from '../../stores/settings.store';
import { getAvailableSections } from './tourRegistry';
import { TourSectionCard } from './TourSectionCard';
import type { TourCategory, TourSection } from './types';

const { Title, Text } = Typography;

const categoryLabels: Record<TourCategory, string> = {
  essentials: 'Essentials',
  features: 'Features',
};

export function TourHub() {
  const { hubOpen, closeHub, sections, launchSection, resetSection, resetAllSections } = useTourStore();
  const settings = useSettingsStore((s) => s.settings);
  const navigate = useNavigate();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const { token } = theme.useToken();

  const availableSections = useMemo(
    () => (settings ? getAvailableSections(settings as unknown as Record<string, unknown>) : []),
    [settings]
  );

  const completedCount = useMemo(
    () => availableSections.filter((s) => sections[s.id]?.completed).length,
    [availableSections, sections]
  );

  const totalCount = availableSections.length;
  const overallPercent = totalCount > 0 ? Math.round((completedCount / totalCount) * 100) : 0;

  // Group sections by category
  const grouped = useMemo(() => {
    const groups: Record<string, TourSection[]> = {};
    for (const section of availableSections) {
      const cat = section.category;
      if (!groups[cat]) groups[cat] = [];
      groups[cat]!.push(section);
    }
    return groups;
  }, [availableSections]);

  const handleLaunch = useCallback(
    (section: TourSection) => {
      if (!settings) return;
      const ctx = { settings, isMobile };
      const steps = section.buildSteps(ctx);
      if (steps.length === 0) return;

      launchSection(section.id, steps.length);
      closeHub();

      if (section.route) {
        navigate(section.route);
      }
    },
    [settings, isMobile, launchSection, closeHub, navigate]
  );

  const handleReset = useCallback(
    (sectionId: string) => {
      resetSection(sectionId as TourSection['id']);
    },
    [resetSection]
  );

  return (
    <Drawer
      title={null}
      open={hubOpen}
      onClose={closeHub}
      width={isMobile ? '100%' : 400}
      styles={{ body: { padding: '16px 20px' } }}
    >
      <div style={{ marginBottom: 20 }}>
        <Title level={4} style={{ marginBottom: 4 }}>Learning Tours</Title>
        <Text type="secondary">
          Interactive tutorials to help you learn each part of the platform.
        </Text>

        <div style={{ marginTop: 12 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
            <Text type="secondary" style={{ fontSize: 13 }}>
              {completedCount} of {totalCount} completed
            </Text>
            <Text type="secondary" style={{ fontSize: 13 }}>
              {overallPercent}%
            </Text>
          </div>
          <Progress
            percent={overallPercent}
            showInfo={false}
            status={completedCount === totalCount ? 'success' : 'active'}
          />
        </div>
      </div>

      <Collapse
        defaultActiveKey={['essentials', 'features']}
        ghost
        items={Object.entries(grouped).map(([category, sects]) => ({
          key: category,
          label: (
            <Text strong style={{ fontSize: 14 }}>
              {categoryLabels[category as TourCategory] || category}
            </Text>
          ),
          children: sects.map((section) => (
            <TourSectionCard
              key={section.id}
              section={section}
              progress={sections[section.id] ?? null}
              onLaunch={() => handleLaunch(section)}
              onReset={() => handleReset(section.id)}
            />
          )),
        }))}
      />

      {completedCount > 0 && (
        <div style={{ textAlign: 'center', marginTop: 16, paddingTop: 16, borderTop: `1px solid ${token.colorBorderSecondary}` }}>
          <Button
            type="link"
            danger
            size="small"
            onClick={resetAllSections}
          >
            Reset All Progress
          </Button>
        </div>
      )}
    </Drawer>
  );
}
