'use client';

import { useState, useEffect } from 'react';
import { usePathname, useRouter } from 'next/navigation';
import { useOnboarding } from '@/contexts/OnboardingContext';
import { useAuth } from '@/contexts/AuthContext';
import { getOnboardingKey } from '@/lib/onboarding-steps';

const PAGE_LABELS: Record<string, string> = {
  dashboard: 'Главная',
  schedule: 'Расписание',
  students: 'Студенты',
  materials: 'Материалы',
  homework: 'Домашние задания',
  feedback: 'Обратная связь',
  analytics: 'Аналитика',
  payment: 'Тарифы',
  referrals: 'Рефералы',
  profile: 'Профиль',
  chat: 'Чат',
  'my-progress': 'Прогресс',
  'request-mentor': 'Мои менторы',
};

const MENTOR_PAGES = ['dashboard', 'schedule', 'students', 'materials', 'homework', 'feedback', 'analytics', 'payment', 'referrals', 'profile'];
const CLIENT_PAGES = ['dashboard', 'schedule', 'chat', 'materials', 'homework', 'my-progress', 'request-mentor', 'profile'];

export function OnboardingTipsSection() {
  const onboarding = useOnboarding();
  const { user } = useAuth();
  const pathname = usePathname();
  const router = useRouter();
  const [progress, setProgress] = useState({ seen: 0, total: 0 });
  const [expanded, setExpanded] = useState(false);

  const role = user?.role === 'mentor' ? 'mentor' : user?.role === 'client' ? 'client' : user?.role === 'parent' ? 'parent' : null;
  const pages = role === 'mentor' ? MENTOR_PAGES : role === 'client' ? CLIENT_PAGES : MENTOR_PAGES;

  useEffect(() => {
    if (!onboarding) return;
    onboarding.refreshProgress().then(() => {
      setProgress(onboarding.getProgress());
    });
  }, [onboarding, pathname]);

  if (!onboarding || !role) return null;

  const currentKey = getOnboardingKey(pathname || '', role as 'mentor' | 'client' | 'parent');

  const handleShowAgain = () => {
    if (currentKey) onboarding.runTourManually(currentKey, { force: true });
  };

  const handleShowOnPage = (pageKey: string) => {
    setExpanded(false);
    const path = pageKey === 'dashboard' ? '/dashboard' : `/${pageKey}`;
    router.push(path);
    setTimeout(() => onboarding.runTourManually(pageKey, { force: true }), 800);
  };

  if (progress.total === 0) return null;

  return (
    <div
      className="ios26-panel"
      style={{
        padding: 20,
        borderRadius: 16,
        background: 'var(--md-sys-color-surface-container-low)',
        border: '1px solid var(--md-sys-color-outline-variant, rgba(0,0,0,0.08))',
      }}
    >
      <h3 style={{ fontSize: 16, fontWeight: 600, margin: '0 0 12px 0', color: 'var(--md-sys-color-on-surface)' }}>
        Подсказки по платформе
      </h3>
      <p style={{ fontSize: 14, color: 'var(--md-sys-color-on-surface-variant)', margin: '0 0 16px 0', lineHeight: 1.5 }}>
        Пройдено {progress.seen} из {progress.total} страниц
      </p>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, alignItems: 'center' }}>
        {currentKey && (
          <button
            type="button"
            onClick={handleShowAgain}
            style={{
              padding: '10px 16px',
              fontSize: 14,
              fontWeight: 600,
              color: 'var(--md-sys-color-on-primary)',
              background: 'var(--md-sys-color-primary)',
              border: 'none',
              borderRadius: 12,
              cursor: 'pointer',
            }}
          >
            Показать подсказки снова
          </button>
        )}
        <button
          type="button"
          onClick={() => setExpanded(!expanded)}
          style={{
            padding: '10px 16px',
            fontSize: 14,
            fontWeight: 500,
            color: 'var(--md-sys-color-primary)',
            background: 'transparent',
            border: '1px solid var(--md-sys-color-primary)',
            borderRadius: 12,
            cursor: 'pointer',
          }}
        >
          {expanded ? 'Свернуть' : 'Подсказки на другой странице'}
        </button>
      </div>
      {expanded && (
        <div
          style={{
            marginTop: 16,
            paddingTop: 16,
            borderTop: '1px solid var(--md-sys-color-outline-variant, rgba(0,0,0,0.08))',
            display: 'flex',
            flexWrap: 'wrap',
            gap: 8,
          }}
        >
          {pages.map((key) => (
            <button
              key={key}
              type="button"
              onClick={() => handleShowOnPage(key)}
              style={{
                padding: '8px 12px',
                fontSize: 13,
                fontWeight: 500,
                color: 'var(--md-sys-color-on-surface)',
                background: 'var(--md-sys-color-surface-container-high)',
                border: 'none',
                borderRadius: 10,
                cursor: 'pointer',
              }}
            >
              {PAGE_LABELS[key] || key}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}
