'use client';

import { useEffect, useState, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { ArrowLeft, Plus, Loader2, Copy } from 'lucide-react';
import { cn } from '@/lib/cn';
import { api } from '@/lib/api';

type Tab =
  | 'services'
  | 'schedule'
  | 'group-events'
  | 'memberships'
  | 'webhooks'
  | 'crm-bridge'
  | 'widget';

const inputClass =
  'w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary bg-background text-text';

export default function BookingSettingsPage() {
  const router = useRouter();
  const [tab, setTab] = useState<Tab>('services');

  return (
    <div>
      {/* Header */}
      <div className="flex items-center gap-3 mb-6">
        <button
          onClick={() => router.push('/bookings')}
          className="p-2 rounded-lg hover:bg-background transition-colors"
        >
          <ArrowLeft className="h-5 w-5 text-muted" />
        </button>
        <div>
          <h1 className="text-xl font-bold text-text">Настройки записи</h1>
          <p className="text-sm text-muted">Услуги, расписание, абонементы, интеграции</p>
        </div>
      </div>

      {/* Tabs */}
      <div className="flex items-center gap-1 mb-6 border-b border-border overflow-x-auto">
        {[
          { key: 'services' as const, label: 'Услуги' },
          { key: 'schedule' as const, label: 'Расписание' },
          { key: 'group-events' as const, label: 'Группы' },
          { key: 'memberships' as const, label: 'Абонементы' },
          { key: 'webhooks' as const, label: 'Вебхуки' },
          { key: 'crm-bridge' as const, label: 'CRM Bridge' },
          { key: 'widget' as const, label: 'Виджет' },
        ].map((t) => (
          <button
            key={t.key}
            onClick={() => setTab(t.key)}
            className={cn(
              'px-4 py-2 text-sm font-medium border-b-2 transition-colors -mb-px whitespace-nowrap',
              tab === t.key
                ? 'border-primary text-primary'
                : 'border-transparent text-muted hover:text-text',
            )}
          >
            {t.label}
          </button>
        ))}
      </div>

      {/* Tab content */}
      {tab === 'services' && <ServicesTab />}
      {tab === 'schedule' && <ScheduleTab />}
      {tab === 'group-events' && <GroupEventsTab />}
      {tab === 'memberships' && <MembershipsTab />}
      {tab === 'webhooks' && <WebhooksTab />}
      {tab === 'crm-bridge' && <CrmBridgeTab />}
      {tab === 'widget' && <WidgetTab />}
    </div>
  );
}

// ═══════════════════════════════════════════════════════════
// Services Tab
// ═══════════════════════════════════════════════════════════

function ServicesTab() {
  const [services, setServices] = useState<any[]>([]);
  const [categories, setCategories] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  const fetch = useCallback(async () => {
    setLoading(true);
    try {
      const [s, c] = await Promise.all([
        api.get<any[]>('/booking/services'),
        api.get<any[]>('/booking/service-categories'),
      ]);
      setServices(s);
      setCategories(c);
    } catch {
      /* ignore */
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetch();
  }, [fetch]);

  if (loading) return <LoadingSpinner />;

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <p className="text-sm text-muted">{services.length} услуг</p>
        <button className="flex items-center gap-2 px-3 py-2 rounded-lg bg-primary text-white text-sm hover:bg-primary/90 transition-colors">
          <Plus className="h-4 w-4" /> Добавить услугу
        </button>
      </div>

      {categories.length > 0 && (
        <div className="flex flex-wrap gap-2 mb-3">
          {categories.map((c) => (
            <span key={c.id} className="px-2 py-1 rounded-full bg-primary/10 text-primary text-xs">
              {c.name}
            </span>
          ))}
        </div>
      )}

      <div className="bg-card rounded-xl border border-border divide-y divide-border">
        {services.map((s) => (
          <div
            key={s.id}
            className="flex items-center gap-4 px-4 py-3 hover:bg-background/30 transition-colors"
          >
            {s.color && (
              <div className="w-3 h-3 rounded-full shrink-0" style={{ background: s.color }} />
            )}
            <div className="flex-1 min-w-0">
              <div className="font-medium text-text text-sm">{s.name}</div>
              <div className="text-xs text-muted">
                {s.duration} мин · {Number(s.price).toLocaleString('ru-RU')} ₽ ·{' '}
                {s.type === 'GROUP' ? 'Групповая' : 'Индивидуальная'}
              </div>
            </div>
            <div className="text-xs text-muted">
              {s.isActive ? (
                <span className="text-green-600">Активна</span>
              ) : (
                <span className="text-red-500">Неактивна</span>
              )}
            </div>
          </div>
        ))}
        {services.length === 0 && (
          <div className="px-4 py-8 text-center text-muted text-sm">Услуги не добавлены</div>
        )}
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════
// Schedule Tab
// ═══════════════════════════════════════════════════════════

function ScheduleTab() {
  const [schedules, setSchedules] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    api
      .get<any[]>('/booking/staff-schedule')
      .then(setSchedules)
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  if (loading) return <LoadingSpinner />;

  const days = ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс'];

  return (
    <div className="space-y-4">
      <p className="text-sm text-muted">Недельные шаблоны расписания тренеров</p>

      {schedules.length === 0 ? (
        <div className="bg-card rounded-xl border border-border px-4 py-8 text-center text-muted text-sm">
          Расписания не настроены. Добавьте шаблон для каждого тренера.
        </div>
      ) : (
        <div className="bg-card rounded-xl border border-border divide-y divide-border">
          {schedules.map((s: any) => (
            <div key={s.staffId} className="px-4 py-3">
              <div className="font-medium text-text text-sm mb-2">
                {s.staff?.firstName} {s.staff?.lastName}
              </div>
              <div className="flex gap-2 flex-wrap">
                {s.slots?.map((slot: any, i: number) => (
                  <span key={i} className="px-2 py-1 rounded bg-primary/10 text-primary text-xs">
                    {days[slot.dayOfWeek]} {slot.startTime}–{slot.endTime}
                  </span>
                ))}
                {(!s.slots || s.slots.length === 0) && (
                  <span className="text-xs text-muted">Нет слотов</span>
                )}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ═══════════════════════════════════════════════════════════
// Group Events Tab
// ═══════════════════════════════════════════════════════════

function GroupEventsTab() {
  const [events, setEvents] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    api
      .get<{ items: any[] }>('/booking/group-events')
      .then((d) => setEvents(d.items ?? d))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  if (loading) return <LoadingSpinner />;

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <p className="text-sm text-muted">{events.length} событий</p>
        <button className="flex items-center gap-2 px-3 py-2 rounded-lg bg-primary text-white text-sm hover:bg-primary/90 transition-colors">
          <Plus className="h-4 w-4" /> Создать событие
        </button>
      </div>

      <div className="bg-card rounded-xl border border-border divide-y divide-border">
        {events.map((e) => (
          <div
            key={e.id}
            className="flex items-center justify-between px-4 py-3 hover:bg-background/30 transition-colors"
          >
            <div>
              <div className="font-medium text-text text-sm">{e.title ?? e.service?.name}</div>
              <div className="text-xs text-muted">
                {new Date(e.startAt).toLocaleString('ru-RU', {
                  day: 'numeric',
                  month: 'short',
                  hour: '2-digit',
                  minute: '2-digit',
                })}
                {' · '}
                {e.bookedCount}/{e.capacity} мест
              </div>
            </div>
            {e.isCancelled && <span className="text-xs text-red-500">Отменено</span>}
          </div>
        ))}
        {events.length === 0 && (
          <div className="px-4 py-8 text-center text-muted text-sm">Групповых событий нет</div>
        )}
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════
// Memberships Tab
// ═══════════════════════════════════════════════════════════

function MembershipsTab() {
  const [types, setTypes] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    api
      .get<any[]>('/booking/memberships')
      .then(setTypes)
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  if (loading) return <LoadingSpinner />;

  const kindLabels: Record<string, string> = {
    VISIT_BASED: 'По визитам',
    UNLIMITED: 'Безлимит',
    HOUR_BASED: 'По часам',
    MIXED: 'Смешанный',
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <p className="text-sm text-muted">{types.length} типов абонементов</p>
        <button className="flex items-center gap-2 px-3 py-2 rounded-lg bg-primary text-white text-sm hover:bg-primary/90 transition-colors">
          <Plus className="h-4 w-4" /> Добавить тип
        </button>
      </div>

      <div className="bg-card rounded-xl border border-border divide-y divide-border">
        {types.map((t) => (
          <div
            key={t.id}
            className="flex items-center justify-between px-4 py-3 hover:bg-background/30 transition-colors"
          >
            <div>
              <div className="font-medium text-text text-sm">{t.name}</div>
              <div className="text-xs text-muted">
                {kindLabels[t.kind] ?? t.kind}
                {t.totalVisits ? ` · ${t.totalVisits} визитов` : ''}
                {t.totalHours ? ` · ${t.totalHours}ч` : ''}
                {' · '}
                {t.validityDays} дн · {Number(t.price).toLocaleString('ru-RU')} ₽
              </div>
            </div>
            <div className="flex items-center gap-2">
              <span className="text-xs text-muted">{t._count?.memberships ?? 0} выдано</span>
              {t.isActive ? (
                <span className="text-xs text-green-600">Активен</span>
              ) : (
                <span className="text-xs text-red-500">Неактивен</span>
              )}
            </div>
          </div>
        ))}
        {types.length === 0 && (
          <div className="px-4 py-8 text-center text-muted text-sm">
            Типы абонементов не созданы
          </div>
        )}
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════
// Webhooks Tab
// ═══════════════════════════════════════════════════════════

function WebhooksTab() {
  const [endpoints, setEndpoints] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  const fetch = useCallback(async () => {
    setLoading(true);
    try {
      setEndpoints(await api.get<any[]>('/booking/webhooks/endpoints'));
    } catch {
      /* ignore */
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetch();
  }, [fetch]);

  if (loading) return <LoadingSpinner />;

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <p className="text-sm text-muted">
          Webhook-эндпоинты для внешних систем (Bitrix24, 1C и др.)
        </p>
        <button className="flex items-center gap-2 px-3 py-2 rounded-lg bg-primary text-white text-sm hover:bg-primary/90 transition-colors">
          <Plus className="h-4 w-4" /> Добавить
        </button>
      </div>

      <div className="bg-card rounded-xl border border-border divide-y divide-border">
        {endpoints.map((ep) => (
          <div key={ep.id} className="px-4 py-3 hover:bg-background/30 transition-colors">
            <div className="flex items-center justify-between mb-1">
              <div className="font-medium text-text text-sm">{ep.name ?? 'Без названия'}</div>
              <div className="flex items-center gap-2">
                {ep.isActive ? (
                  <span className="text-xs text-green-600">Активен</span>
                ) : (
                  <span className="text-xs text-red-500">Выключен</span>
                )}
                <button
                  onClick={() => navigator.clipboard.writeText(ep.secret)}
                  className="p-1 rounded hover:bg-background transition-colors"
                  title="Скопировать секрет"
                >
                  <Copy className="h-3.5 w-3.5 text-muted" />
                </button>
              </div>
            </div>
            <div className="text-xs text-muted truncate">{ep.url}</div>
            <div className="flex flex-wrap gap-1 mt-1">
              {ep.events?.map((e: string) => (
                <span key={e} className="px-1.5 py-0.5 rounded bg-background text-xs text-muted">
                  {e}
                </span>
              ))}
            </div>
          </div>
        ))}
        {endpoints.length === 0 && (
          <div className="px-4 py-8 text-center text-muted text-sm">
            Webhook-эндпоинты не настроены
          </div>
        )}
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════
// CRM Bridge Tab
// ═══════════════════════════════════════════════════════════

function CrmBridgeTab() {
  const [bridge, setBridge] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [pipelines, setPipelines] = useState<any[]>([]);

  useEffect(() => {
    Promise.all([
      api.get('/booking/crm-bridge').catch(() => null),
      api.get<any[]>('/crm/pipelines').catch(() => []),
    ]).then(([b, p]) => {
      setBridge(b);
      setPipelines(p);
      setLoading(false);
    });
  }, []);

  if (loading) return <LoadingSpinner />;

  return (
    <div className="max-w-xl space-y-4">
      <p className="text-sm text-muted">
        Настройте связь модуля записи с CRM. При новой записи автоматически создаётся сделка в
        выбранной воронке.
      </p>

      <div className="bg-card rounded-xl border border-border p-4 space-y-4">
        <div className="flex items-center justify-between">
          <span className="text-sm font-medium text-text">Включить CRM Bridge</span>
          <div
            className={cn(
              'w-10 h-6 rounded-full transition-colors cursor-pointer flex items-center px-1',
              bridge?.isEnabled ? 'bg-primary' : 'bg-border',
            )}
          >
            <div
              className={cn(
                'w-4 h-4 rounded-full bg-white transition-transform',
                bridge?.isEnabled ? 'translate-x-4' : 'translate-x-0',
              )}
            />
          </div>
        </div>

        <div>
          <label className="block text-sm font-medium text-text mb-1">CRM Воронка</label>
          <select className={inputClass} defaultValue={bridge?.pipelineId ?? ''}>
            <option value="">Не выбрана</option>
            {pipelines.map((p) => (
              <option key={p.id} value={p.id}>
                {p.name}
              </option>
            ))}
          </select>
        </div>

        <div className="grid grid-cols-2 gap-3">
          <div>
            <label className="block text-sm font-medium text-text mb-1">Стадия: Новая запись</label>
            <select className={inputClass} defaultValue={bridge?.newRecordStageId ?? ''}>
              <option value="">—</option>
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-text mb-1">Стадия: Завершена</label>
            <select className={inputClass} defaultValue={bridge?.completedStageId ?? ''}>
              <option value="">—</option>
            </select>
          </div>
        </div>

        <div className="flex items-center gap-3">
          <label className="flex items-center gap-2 text-sm text-text cursor-pointer">
            <input
              type="checkbox"
              defaultChecked={bridge?.createDealOnBook ?? true}
              className="rounded"
            />
            Создавать сделку при записи
          </label>
          <label className="flex items-center gap-2 text-sm text-text cursor-pointer">
            <input
              type="checkbox"
              defaultChecked={bridge?.syncClientData ?? true}
              className="rounded"
            />
            Синхронизировать клиентов
          </label>
        </div>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════
// Widget Tab
// ═══════════════════════════════════════════════════════════

function WidgetTab() {
  const [settings, setSettings] = useState<any>(null);
  const [embedCode, setEmbedCode] = useState<any>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    Promise.all([
      api.get('/booking/widget-settings'),
      api.get('/booking/widget-settings/embed-code?apiKey=YOUR_API_KEY').catch(() => null),
    ])
      .then(([s, e]) => {
        setSettings(s);
        setEmbedCode(e);
        setLoading(false);
      })
      .catch(() => setLoading(false));
  }, []);

  if (loading) return <LoadingSpinner />;

  return (
    <div className="max-w-2xl space-y-6">
      <p className="text-sm text-muted">
        Настройте виджет онлайн-записи для встраивания на ваш сайт.
      </p>

      {/* Preview settings */}
      <div className="bg-card rounded-xl border border-border p-4 space-y-4">
        <h3 className="font-medium text-text">Внешний вид</h3>
        <div className="grid grid-cols-2 gap-3">
          <div>
            <label className="block text-sm font-medium text-text mb-1">Заголовок</label>
            <input className={inputClass} defaultValue={settings?.title ?? 'Онлайн-запись'} />
          </div>
          <div>
            <label className="block text-sm font-medium text-text mb-1">URL логотипа</label>
            <input
              className={inputClass}
              defaultValue={settings?.logoUrl ?? ''}
              placeholder="https://..."
            />
          </div>
        </div>
        <div className="grid grid-cols-3 gap-3">
          <div>
            <label className="block text-sm font-medium text-text mb-1">Основной цвет</label>
            <div className="flex items-center gap-2">
              <input
                type="color"
                defaultValue={settings?.colors?.primary ?? '#3B82F6'}
                className="w-8 h-8 rounded cursor-pointer"
              />
              <input className={inputClass} defaultValue={settings?.colors?.primary ?? '#3B82F6'} />
            </div>
          </div>
          <div>
            <label className="block text-sm font-medium text-text mb-1">Фон</label>
            <input
              className={inputClass}
              defaultValue={settings?.colors?.background ?? '#FFFFFF'}
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-text mb-1">Текст</label>
            <input className={inputClass} defaultValue={settings?.colors?.text ?? '#1F2937'} />
          </div>
        </div>
      </div>

      {/* Embed code */}
      {embedCode && (
        <div className="bg-card rounded-xl border border-border p-4 space-y-4">
          <h3 className="font-medium text-text">Код для встраивания</h3>
          {Object.entries(embedCode).map(([key, code]) => (
            <div key={key}>
              <div className="flex items-center justify-between mb-1">
                <span className="text-sm font-medium text-text capitalize">
                  {key.replace(/([A-Z])/g, ' $1')}
                </span>
                <button
                  onClick={() => navigator.clipboard.writeText(code as string)}
                  className="flex items-center gap-1 text-xs text-primary hover:text-primary/80"
                >
                  <Copy className="h-3 w-3" /> Копировать
                </button>
              </div>
              <pre className="bg-background rounded-lg p-3 text-xs text-muted overflow-x-auto whitespace-pre-wrap">
                {code as string}
              </pre>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ═══════════════════════════════════════════════════════════
// Shared
// ═══════════════════════════════════════════════════════════

function LoadingSpinner() {
  return (
    <div className="flex items-center justify-center py-12">
      <Loader2 className="h-5 w-5 animate-spin text-primary" />
    </div>
  );
}
