'use client';

import { useRef, useState, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import {
  ArrowLeft,
  FileDown,
  Printer,
  Table2,
  TrendingUp,
  Search,
  ChevronDown,
  ChevronUp,
  Building2,
  DollarSign,
  Clock,
  MapPin,
  Globe,
  CheckCircle2,
  XCircle,
  Filter,
} from 'lucide-react';
import { cn } from '@/lib/cn';
import { franchises, SEGMENTS, MARKET_KPI, type Franchise } from './data';

const LAST_UPDATE = '26 февраля 2026';

/* ─────────────── Helpers ─────────────── */

function getSegmentInfo(id: string) {
  return SEGMENTS.find((s) => s.id === id) ?? SEGMENTS[0];
}

/* ─────────────── Page ─────────────── */

export default function FitnessfranchiseComparisonPage() {
  const router = useRouter();
  const contentRef = useRef<HTMLDivElement>(null);
  const [search, setSearch] = useState('');
  const [activeSegment, setActiveSegment] = useState<string | null>(null);
  const [expandedCard, setExpandedCard] = useState<string | null>(null);

  const filtered = useMemo(() => {
    let list = franchises;
    if (activeSegment) list = list.filter((f) => f.segment === activeSegment);
    if (search.trim()) {
      const q = search.toLowerCase();
      list = list.filter(
        (f) =>
          f.name.toLowerCase().includes(q) ||
          f.description.toLowerCase().includes(q) ||
          f.segment.toLowerCase().includes(q),
      );
    }
    return list;
  }, [search, activeSegment]);

  const grouped = useMemo(() => {
    const map = new Map<string, Franchise[]>();
    for (const f of filtered) {
      const arr = map.get(f.segment) ?? [];
      arr.push(f);
      map.set(f.segment, arr);
    }
    return map;
  }, [filtered]);

  const handleDownloadPdf = async () => {
    const el = contentRef.current;
    if (!el) return;
    const html2canvas = (await import('html2canvas-pro')).default;
    const { jsPDF } = await import('jspdf');
    const canvas = await html2canvas(el, { scale: 2, useCORS: true });
    const imgData = canvas.toDataURL('image/png');
    const pdf = new jsPDF('l', 'mm', 'a4');
    const pdfW = pdf.internal.pageSize.getWidth();
    const pdfH = pdf.internal.pageSize.getHeight();
    const imgW = pdfW - 16;
    const imgH = (canvas.height * imgW) / canvas.width;
    let y = 8;
    let page = 0;
    while (y < imgH + 8) {
      if (page > 0) pdf.addPage();
      pdf.addImage(imgData, 'PNG', 8, 8 - y + 8 * (page === 0 ? 0 : 1), imgW, imgH);
      y += pdfH - 16;
      page++;
    }
    pdf.save('fitness-franchise-catalog-2026.pdf');
  };

  const handleCopyTable = () => {
    const rows = [
      [
        '#',
        'Франшиза',
        'Сегмент',
        'Инвестиции',
        'Паушальный',
        'Роялти',
        'Окупаемость',
        'Точек',
      ].join('\t'),
    ];
    franchises.forEach((f, i) => {
      rows.push(
        [
          i + 1,
          f.name,
          getSegmentInfo(f.segment).label,
          f.investment,
          f.lumpSum,
          f.royalty,
          f.payback,
          f.locations,
        ].join('\t'),
      );
    });
    void navigator.clipboard.writeText(rows.join('\n'));
    alert('Таблица скопирована в буфер обмена');
  };

  return (
    <div>
      <button
        onClick={() => router.push('/documents')}
        className="flex items-center gap-2 text-sm text-muted hover:text-gray-900 mb-6 transition-colors print:hidden"
      >
        <ArrowLeft className="h-4 w-4" />
        Все документы
      </button>

      <div ref={contentRef} className="space-y-6">
        {/* ── Header ── */}
        <div className="bg-card rounded-xl shadow-sm border border-border overflow-hidden">
          <div className="bg-gradient-to-r from-indigo-600 to-purple-600 px-6 py-6 text-white">
            <h1 className="text-2xl font-bold">Каталог фитнес-франшиз России 2025–2026</h1>
            <p className="text-indigo-100 mt-1 text-sm">
              Полный обзор {franchises.length} франшиз из {SEGMENTS.length} сегментов — данные со
              всех страниц каталогов TopFranchise, Businessmens, BeBoss, Franshiza.ru
            </p>
            <p className="text-indigo-200 text-xs mt-2">Обновлено: {LAST_UPDATE}</p>
          </div>

          {/* Export buttons */}
          <div className="px-6 py-3 border-b border-border flex flex-wrap gap-2 print:hidden">
            <button
              onClick={() => void handleDownloadPdf()}
              className="flex items-center gap-2 border border-border bg-card text-gray-700 px-4 py-2 rounded-xl text-sm font-medium hover:bg-background transition-colors"
            >
              <FileDown className="h-4 w-4" />
              PDF
            </button>
            <button
              onClick={handleCopyTable}
              className="flex items-center gap-2 border border-border bg-card text-gray-700 px-4 py-2 rounded-xl text-sm font-medium hover:bg-background transition-colors"
            >
              <Table2 className="h-4 w-4" />
              Копировать таблицу
            </button>
            <button
              onClick={() => window.print()}
              className="flex items-center gap-2 border border-border bg-card text-gray-700 px-4 py-2 rounded-xl text-sm font-medium hover:bg-background transition-colors"
            >
              <Printer className="h-4 w-4" />
              Печать
            </button>
          </div>
        </div>

        {/* ── KPI Cards ── */}
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3">
          {MARKET_KPI.map((kpi) => (
            <div
              key={kpi.label}
              className="bg-card rounded-xl border border-border p-4 text-center"
            >
              <p className="text-2xl font-bold text-indigo-600">{kpi.value}</p>
              <p className="text-xs text-muted mt-1">{kpi.label}</p>
              <p className="text-[10px] text-gray-400 mt-0.5">{kpi.sub}</p>
            </div>
          ))}
        </div>

        {/* ── Search & Filters ── */}
        <div className="bg-card rounded-xl border border-border p-4 print:hidden">
          <div className="flex flex-col md:flex-row gap-3">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted" />
              <input
                type="text"
                placeholder="Поиск по названию или описанию..."
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                className="w-full pl-10 pr-4 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
              />
            </div>
            <div className="flex items-center gap-2">
              <Filter className="h-4 w-4 text-muted" />
              <span className="text-xs text-muted whitespace-nowrap">Сегмент:</span>
            </div>
          </div>
          <div className="flex flex-wrap gap-2 mt-3">
            <button
              onClick={() => setActiveSegment(null)}
              className={cn(
                'px-3 py-1.5 rounded-full text-xs font-medium transition-colors border',
                !activeSegment
                  ? 'bg-indigo-600 text-white border-indigo-600'
                  : 'bg-card text-gray-600 border-border hover:bg-background',
              )}
            >
              Все ({franchises.length})
            </button>
            {SEGMENTS.map((seg) => {
              const count = franchises.filter((f) => f.segment === seg.id).length;
              return (
                <button
                  key={seg.id}
                  onClick={() => setActiveSegment(activeSegment === seg.id ? null : seg.id)}
                  className={cn(
                    'px-3 py-1.5 rounded-full text-xs font-medium transition-colors border',
                    activeSegment === seg.id
                      ? 'bg-indigo-600 text-white border-indigo-600'
                      : 'bg-card text-gray-600 border-border hover:bg-background',
                  )}
                >
                  {seg.label} ({count})
                </button>
              );
            })}
          </div>
        </div>

        {/* ── Results count ── */}
        <p className="text-sm text-muted px-1">
          Найдено: <span className="font-semibold text-gray-900">{filtered.length}</span> франшиз
          {activeSegment && <> в сегменте «{getSegmentInfo(activeSegment).label}»</>}
        </p>

        {/* ── Segments with franchise cards ── */}
        {SEGMENTS.filter((seg) => grouped.has(seg.id)).map((seg) => {
          const items = grouped.get(seg.id)!;
          return (
            <div key={seg.id} className="space-y-3">
              {/* Segment header */}
              <div
                className={cn(
                  'bg-gradient-to-r text-white rounded-xl px-5 py-3 flex items-center justify-between',
                  seg.color,
                )}
              >
                <h2 className="text-lg font-bold">{seg.label}</h2>
                <span className="bg-white/20 px-3 py-1 rounded-full text-sm font-medium">
                  {items.length} франшиз
                </span>
              </div>

              {/* Summary table */}
              <div className="bg-card rounded-xl border border-border overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="bg-gray-50 text-left">
                      <th className="px-3 py-2 font-medium text-muted text-xs">#</th>
                      <th className="px-3 py-2 font-medium text-muted text-xs">Франшиза</th>
                      <th className="px-3 py-2 font-medium text-muted text-xs">Инвестиции</th>
                      <th className="px-3 py-2 font-medium text-muted text-xs">Паушальный</th>
                      <th className="px-3 py-2 font-medium text-muted text-xs">Роялти</th>
                      <th className="px-3 py-2 font-medium text-muted text-xs">Окупаемость</th>
                      <th className="px-3 py-2 font-medium text-muted text-xs">Точек</th>
                      <th className="px-3 py-2 font-medium text-muted text-xs print:hidden"></th>
                    </tr>
                  </thead>
                  <tbody>
                    {items.map((f, idx) => {
                      const isExpanded = expandedCard === `${seg.id}-${idx}`;
                      return (
                        <tr
                          key={f.name}
                          className={cn(
                            'border-t border-border hover:bg-gray-50/50 transition-colors cursor-pointer',
                            isExpanded && 'bg-indigo-50/30',
                          )}
                          onClick={() => setExpandedCard(isExpanded ? null : `${seg.id}-${idx}`)}
                        >
                          <td className="px-3 py-2 text-muted text-xs">{idx + 1}</td>
                          <td className="px-3 py-2 font-medium text-gray-900 whitespace-nowrap">
                            <div className="flex items-center gap-2">
                              <span>{f.name}</span>
                              {f.founded !== '—' && (
                                <span className="text-[10px] text-muted bg-gray-100 px-1.5 py-0.5 rounded">
                                  с {f.founded}
                                </span>
                              )}
                            </div>
                          </td>
                          <td className="px-3 py-2 text-xs">{f.investment}</td>
                          <td className="px-3 py-2 text-xs">{f.lumpSum}</td>
                          <td className="px-3 py-2 text-xs">{f.royalty}</td>
                          <td className="px-3 py-2 text-xs">{f.payback}</td>
                          <td className="px-3 py-2 text-xs">{f.locations}</td>
                          <td className="px-3 py-2 print:hidden">
                            {isExpanded ? (
                              <ChevronUp className="h-4 w-4 text-muted" />
                            ) : (
                              <ChevronDown className="h-4 w-4 text-muted" />
                            )}
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>

              {/* Expanded detail cards */}
              {items.map((f, idx) => {
                const isExpanded = expandedCard === `${seg.id}-${idx}`;
                if (!isExpanded) return null;
                return (
                  <div
                    key={`detail-${f.name}`}
                    className="bg-card rounded-xl border-2 border-indigo-200 p-5 space-y-4 animate-in fade-in duration-200"
                  >
                    <div className="flex items-start justify-between">
                      <div>
                        <h3 className="text-lg font-bold text-gray-900">{f.name}</h3>
                        <p className="text-sm text-muted mt-1">{f.description}</p>
                      </div>
                      {f.website !== '—' && (
                        <span className="flex items-center gap-1 text-xs text-indigo-600 bg-indigo-50 px-2 py-1 rounded-lg whitespace-nowrap">
                          <Globe className="h-3 w-3" />
                          {f.website}
                        </span>
                      )}
                    </div>

                    <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                      <div className="bg-gray-50 rounded-lg p-3">
                        <div className="flex items-center gap-1 text-xs text-muted mb-1">
                          <DollarSign className="h-3 w-3" />
                          Инвестиции
                        </div>
                        <p className="text-sm font-semibold">{f.investment}</p>
                      </div>
                      <div className="bg-gray-50 rounded-lg p-3">
                        <div className="flex items-center gap-1 text-xs text-muted mb-1">
                          <Building2 className="h-3 w-3" />
                          Паушальный
                        </div>
                        <p className="text-sm font-semibold">{f.lumpSum}</p>
                      </div>
                      <div className="bg-gray-50 rounded-lg p-3">
                        <div className="flex items-center gap-1 text-xs text-muted mb-1">
                          <TrendingUp className="h-3 w-3" />
                          Роялти
                        </div>
                        <p className="text-sm font-semibold">{f.royalty}</p>
                      </div>
                      <div className="bg-gray-50 rounded-lg p-3">
                        <div className="flex items-center gap-1 text-xs text-muted mb-1">
                          <Clock className="h-3 w-3" />
                          Окупаемость
                        </div>
                        <p className="text-sm font-semibold">{f.payback}</p>
                      </div>
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      <div>
                        <h4 className="text-xs font-semibold text-emerald-700 uppercase tracking-wide mb-2 flex items-center gap-1">
                          <CheckCircle2 className="h-3 w-3" />
                          Сильные стороны
                        </h4>
                        <ul className="space-y-1">
                          {f.strengths.map((s) => (
                            <li key={s} className="text-xs text-gray-700 flex items-start gap-1.5">
                              <span className="text-emerald-500 mt-0.5">+</span>
                              {s}
                            </li>
                          ))}
                        </ul>
                      </div>
                      <div>
                        <h4 className="text-xs font-semibold text-red-700 uppercase tracking-wide mb-2 flex items-center gap-1">
                          <XCircle className="h-3 w-3" />
                          Слабые стороны
                        </h4>
                        <ul className="space-y-1">
                          {f.weaknesses.map((w) => (
                            <li key={w} className="text-xs text-gray-700 flex items-start gap-1.5">
                              <span className="text-red-500 mt-0.5">−</span>
                              {w}
                            </li>
                          ))}
                        </ul>
                      </div>
                    </div>

                    <div className="flex items-center gap-4 pt-2 border-t border-border text-xs text-muted">
                      {f.founded !== '—' && (
                        <span className="flex items-center gap-1">
                          <Clock className="h-3 w-3" /> Основана: {f.founded}
                        </span>
                      )}
                      <span className="flex items-center gap-1">
                        <MapPin className="h-3 w-3" /> Точек: {f.locations}
                      </span>
                    </div>
                  </div>
                );
              })}
            </div>
          );
        })}

        {/* ── Recommendations ── */}
        <div className="bg-card rounded-xl border border-border p-6 space-y-4">
          <h2 className="text-lg font-bold text-gray-900">Рекомендации по бюджету</h2>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="bg-emerald-50 rounded-xl p-4 border border-emerald-200">
              <h3 className="font-bold text-emerald-800 text-sm">До 2 млн ₽</h3>
              <p className="text-xs text-emerald-700 mt-2">
                <strong>Лучшие варианты:</strong> Beautiful Body (280K), ТОНУС-КЛУБ (от 500K),
                Kangoo Jumps (от 499K), StretchBerry (от 250K), UNIDANCE (240K), Yoga Home (40K),
                GYMCHEL (100K), GRAFITNESS (300K).
              </p>
              <p className="text-xs text-emerald-600 mt-2">
                Фокус: женский фитнес, растяжка, джампинг, йога. Быстрая окупаемость 3–8 мес.
              </p>
            </div>

            <div className="bg-blue-50 rounded-xl p-4 border border-blue-200">
              <h3 className="font-bold text-blue-800 text-sm">2–10 млн ₽</h3>
              <p className="text-xs text-blue-700 mt-2">
                <strong>Лучшие варианты:</strong> LEVITA (2,1M, №1 Forbes), Lady Stretch (1,2M, 109
                точек), Lady Jump (1,5M, 180+ точек), FIT-N-GO (2,6M, EMS-лидер), X-FIT Point
                (500K), Fit Curves (2,5M), Fit-Studio (5M), FITROOM (1,35M).
              </p>
              <p className="text-xs text-blue-600 mt-2">
                Широкий выбор: от автоматизированных залов до полноценных студий. Окупаемость 6–24
                мес.
              </p>
            </div>

            <div className="bg-amber-50 rounded-xl p-4 border border-amber-200">
              <h3 className="font-bold text-amber-800 text-sm">10+ млн ₽</h3>
              <p className="text-xs text-amber-700 mt-2">
                <strong>Лучшие варианты:</strong> Alex Fitness (20M, 0% роялти), World Gym (10M, 0%
                роялти), X-FIT клуб (8M), Pride Fitness (10M), VELOBEAT (13M), FeRRUM (6,9M).
                Премиум: World Class (150M), SPIRIT (35M+), Gold&apos;s Gym (30M+).
              </p>
              <p className="text-xs text-amber-600 mt-2">
                Полноформатные клубы и премиум-сегмент. Окупаемость 18–60 мес. Высокая выручка.
              </p>
            </div>
          </div>
        </div>

        {/* ── Sources ── */}
        <div className="bg-card rounded-xl border border-border p-6">
          <h2 className="text-lg font-bold text-gray-900 mb-3">Источники данных</h2>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-2 text-xs text-muted">
            <div>
              <p>topfranchise.ru — каталог франшиз (все страницы)</p>
              <p>businessmens.ru — каталог франшиз фитнес</p>
              <p>beboss.ru — франшизы фитнес-клубов</p>
              <p>franshiza.ru — спортивные франшизы</p>
              <p>franchise-katalog.ru — фитнес-клубы</p>
            </div>
            <div>
              <p>kp.ru — рейтинг фитнес-франшиз</p>
              <p>forbes.ru — рейтинг прибыльных франшиз 2024</p>
              <p>Официальные сайты франшиз</p>
              <p>impulsecrm.ru, franch-home.ru — обзоры</p>
              <p className="mt-2 text-gray-400">
                Данные на февраль 2026. Уточняйте условия у франчайзеров.
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
