'use client';

import { useEffect, useState, useCallback } from 'react';
import { useParams } from 'next/navigation';
import Link from 'next/link';
import {
  ArrowLeft,
  Save,
  Upload,
  CheckCircle,
  AlertCircle,
  Copy,
  Plus,
  Code,
  Workflow,
  ListOrdered,
} from 'lucide-react';
import { api } from '@/lib/api';
import { FlowEditor } from '@/components/telegram-bot/flow-editor/flow-editor';
import { StepEditor } from '@/components/telegram-bot/flow-editor/step-editor';
import type { ScenarioJson } from '@/components/telegram-bot/flow-editor/scenario-converter';

interface Scenario {
  id: string;
  name: string;
  description: string | null;
  scenario: Record<string, unknown>;
  version: number;
  isPublished: boolean;
  isDraft: boolean;
}

interface BotDetail {
  id: string;
  name: string;
  scenarioId: string | null;
}

export default function ScenarioPage() {
  const params = useParams();
  const botId = params.id as string;
  const [, setBot] = useState<BotDetail | null>(null);
  const [scenarios, setScenarios] = useState<Scenario[]>([]);
  const [selected, setSelected] = useState<Scenario | null>(null);
  const [jsonText, setJsonText] = useState('');
  const [editorMode, setEditorMode] = useState<'steps' | 'visual' | 'json'>('steps');
  const [saving, setSaving] = useState(false);
  const [validating, setValidating] = useState(false);
  const [validationResult, setValidationResult] = useState<{
    valid: boolean;
    error?: string;
  } | null>(null);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');

  const fetchData = useCallback(async () => {
    try {
      const [botData, scenariosData] = await Promise.all([
        api.get<BotDetail>(`/telegram-bot/bots/${botId}`),
        api.get<Scenario[]>('/telegram-bot/scenarios'),
      ]);
      setBot(botData);
      setScenarios(scenariosData);

      if (botData.scenarioId) {
        // List endpoint doesn't return full JSON — fetch the complete scenario
        try {
          const fullScenario = await api.get<Scenario>(
            `/telegram-bot/scenarios/${botData.scenarioId}`,
          );
          setSelected(fullScenario);
          setJsonText(JSON.stringify(fullScenario.scenario, null, 2));
        } catch {
          // Scenario may have been deleted
        }
      }
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Ошибка');
    }
  }, [botId]);

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

  const handleSelectScenario = async (id: string) => {
    try {
      const sc = await api.get<Scenario>(`/telegram-bot/scenarios/${id}`);
      setSelected(sc);
      setJsonText(JSON.stringify(sc.scenario, null, 2));
      // Assign to bot
      await api.patch(`/telegram-bot/bots/${botId}`, { scenarioId: id });
      setSuccess('Сценарий назначен боту');
      setTimeout(() => setSuccess(''), 3000);
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Ошибка');
    }
  };

  const handleSave = async () => {
    if (!selected) return;
    try {
      setSaving(true);
      setError('');
      const parsed = JSON.parse(jsonText);
      await api.patch(`/telegram-bot/scenarios/${selected.id}`, { scenario: parsed });
      setSuccess('Сценарий сохранён');
      setValidationResult(null);
      setTimeout(() => setSuccess(''), 3000);
      await fetchData();
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Ошибка парсинга JSON');
    } finally {
      setSaving(false);
    }
  };

  const handleValidate = async () => {
    if (!selected) return;
    try {
      setValidating(true);
      await api.post(`/telegram-bot/scenarios/${selected.id}/validate`);
      setValidationResult({ valid: true });
    } catch (err: unknown) {
      setValidationResult({ valid: false, error: err instanceof Error ? err.message : 'Ошибка' });
    } finally {
      setValidating(false);
    }
  };

  const handlePublish = async () => {
    if (!selected) return;
    try {
      await api.post(`/telegram-bot/scenarios/${selected.id}/publish`);
      setSuccess('Сценарий опубликован');
      setTimeout(() => setSuccess(''), 3000);
      await fetchData();
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Ошибка');
    }
  };

  const handleCreate = async () => {
    const name = prompt('Название сценария:');
    if (!name) return;
    try {
      const sc = await api.post<Scenario>('/telegram-bot/scenarios', { name });
      await fetchData();
      await handleSelectScenario(sc.id);
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Ошибка');
    }
  };

  const handleDuplicate = async () => {
    if (!selected) return;
    try {
      await api.post(`/telegram-bot/scenarios/${selected.id}/duplicate`);
      setSuccess('Сценарий дублирован');
      setTimeout(() => setSuccess(''), 3000);
      await fetchData();
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Ошибка');
    }
  };

  const nodeCount = selected?.scenario ? Object.keys(selected.scenario.nodes ?? {}).length : 0;

  return (
    <div>
      <div className="mb-6">
        <Link
          href={`/telegram-bot/${botId}`}
          className="flex items-center gap-1 text-sm text-[var(--muted)] hover:text-[var(--primary)] mb-3"
        >
          <ArrowLeft className="h-4 w-4" /> Назад к боту
        </Link>
        <h1 className="text-2xl font-bold text-[var(--text)]">Сценарий</h1>
      </div>

      {error && (
        <div className="mb-4 rounded-lg bg-[var(--error)]/10 p-3 text-sm text-[var(--error)]">
          {error}
        </div>
      )}
      {success && (
        <div className="mb-4 rounded-lg bg-[var(--success)]/10 p-3 text-sm text-[var(--success)]">
          {success}
        </div>
      )}

      {/* Scenario selector */}
      <div className="mb-4 flex items-center gap-3">
        <select
          value={selected?.id ?? ''}
          onChange={(e) => e.target.value && handleSelectScenario(e.target.value)}
          className="flex-1 rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-sm text-[var(--text)]"
        >
          <option value="">Выберите сценарий...</option>
          {scenarios.map((s) => (
            <option key={s.id} value={s.id}>
              {s.name} (v{s.version}) {s.isPublished ? '✓' : ''}
            </option>
          ))}
        </select>
        <button
          onClick={handleCreate}
          className="flex items-center gap-1 rounded-lg bg-[var(--primary)] px-3 py-2 text-sm text-[var(--primary-foreground)]"
        >
          <Plus className="h-4 w-4" /> Новый
        </button>
      </div>

      {selected && (
        <>
          {/* Info bar */}
          <div className="mb-4 flex items-center justify-between rounded-xl border border-[var(--border)] bg-[var(--card)] p-3">
            <div className="flex items-center gap-4 text-sm text-[var(--muted)]">
              <span>
                Версия: <b className="text-[var(--text)]">{selected.version}</b>
              </span>
              <span>
                Нод: <b className="text-[var(--text)]">{nodeCount}</b>
              </span>
              <span
                className={selected.isPublished ? 'text-[var(--success)]' : 'text-[var(--warning)]'}
              >
                {selected.isPublished ? '✓ Опубликован' : '● Черновик'}
              </span>
            </div>
            <div className="flex items-center gap-2">
              <button
                onClick={handleDuplicate}
                className="rounded-lg p-1.5 text-[var(--muted)] hover:text-[var(--primary)]"
                title="Дублировать"
              >
                <Copy className="h-4 w-4" />
              </button>
            </div>
          </div>

          {/* Editor mode toggle */}
          <div className="mb-4 flex items-center gap-1 rounded-lg bg-[var(--background)] p-1 w-fit border border-[var(--border)]">
            <button
              onClick={() => setEditorMode('steps')}
              className={`flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-medium transition-colors ${
                editorMode === 'steps'
                  ? 'bg-[var(--primary)] text-[var(--primary-foreground)]'
                  : 'text-[var(--muted)] hover:text-[var(--text)]'
              }`}
            >
              <ListOrdered className="h-3.5 w-3.5" /> Редактор
            </button>
            <button
              onClick={() => setEditorMode('visual')}
              className={`flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-medium transition-colors ${
                editorMode === 'visual'
                  ? 'bg-[var(--primary)] text-[var(--primary-foreground)]'
                  : 'text-[var(--muted)] hover:text-[var(--text)]'
              }`}
            >
              <Workflow className="h-3.5 w-3.5" /> Схема
            </button>
            <button
              onClick={() => {
                if (editorMode !== 'json' && selected) {
                  setJsonText(JSON.stringify(selected.scenario, null, 2));
                }
                setEditorMode('json');
              }}
              className={`flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-medium transition-colors ${
                editorMode === 'json'
                  ? 'bg-[var(--primary)] text-[var(--primary-foreground)]'
                  : 'text-[var(--muted)] hover:text-[var(--text)]'
              }`}
            >
              <Code className="h-3.5 w-3.5" /> JSON
            </button>
          </div>

          {/* Step Editor (form-based) */}
          {editorMode === 'steps' && selected?.scenario && (
            <StepEditor
              scenario={selected.scenario as unknown as ScenarioJson}
              onChange={async (updatedScenario) => {
                try {
                  setSaving(true);
                  await api.patch(`/telegram-bot/scenarios/${selected.id}`, {
                    scenario: updatedScenario,
                  });
                  setSuccess('Сценарий сохранён');
                  setTimeout(() => setSuccess(''), 3000);
                  await fetchData();
                } catch (err: unknown) {
                  setError(err instanceof Error ? err.message : 'Ошибка');
                } finally {
                  setSaving(false);
                }
              }}
            />
          )}

          {/* Visual Editor (React Flow) */}
          {editorMode === 'visual' && selected?.scenario && (
            <FlowEditor
              scenario={selected.scenario as unknown as ScenarioJson}
              positions={
                (selected as unknown as { positions?: Record<string, { x: number; y: number }> })
                  .positions
              }
              onSave={async (updatedScenario) => {
                try {
                  setSaving(true);
                  await api.patch(`/telegram-bot/scenarios/${selected.id}`, {
                    scenario: updatedScenario,
                  });
                  setSuccess('Сценарий сохранён');
                  setTimeout(() => setSuccess(''), 3000);
                  await fetchData();
                } catch (err: unknown) {
                  setError(err instanceof Error ? err.message : 'Ошибка');
                } finally {
                  setSaving(false);
                }
              }}
              onPositionsChange={async (positions) => {
                await api
                  .patch(`/telegram-bot/scenarios/${selected.id}`, { positions })
                  .catch(() => {});
              }}
            />
          )}

          {/* JSON Editor */}
          {editorMode === 'json' && (
            <div className="rounded-xl border border-[var(--border)] bg-[var(--card)] overflow-hidden">
              <textarea
                value={jsonText}
                onChange={(e) => setJsonText(e.target.value)}
                rows={25}
                spellCheck={false}
                className="w-full bg-[var(--background)] p-4 text-sm text-[var(--text)] font-mono resize-y border-0 focus:outline-none"
              />
            </div>
          )}

          {/* Validation result */}
          {validationResult && (
            <div
              className={`mt-3 rounded-lg p-3 text-sm flex items-center gap-2 ${
                validationResult.valid
                  ? 'bg-[var(--success)]/10 text-[var(--success)]'
                  : 'bg-[var(--error)]/10 text-[var(--error)]'
              }`}
            >
              {validationResult.valid ? (
                <>
                  <CheckCircle className="h-4 w-4" /> Сценарий валиден
                </>
              ) : (
                <>
                  <AlertCircle className="h-4 w-4" /> {validationResult.error}
                </>
              )}
            </div>
          )}

          {/* Actions */}
          <div className="mt-4 flex items-center gap-3">
            <button
              onClick={handleSave}
              disabled={saving}
              className="flex items-center gap-2 rounded-lg bg-[var(--primary)] px-4 py-2.5 text-sm font-medium text-[var(--primary-foreground)] hover:opacity-90 disabled:opacity-50"
            >
              <Save className="h-4 w-4" />
              {saving ? 'Сохранение...' : 'Сохранить'}
            </button>
            <button
              onClick={handleValidate}
              disabled={validating}
              className="flex items-center gap-2 rounded-lg border border-[var(--border)] px-4 py-2.5 text-sm text-[var(--text)] hover:bg-[var(--background)]"
            >
              {validating ? 'Проверка...' : 'Проверить'}
            </button>
            <button
              onClick={handlePublish}
              className="flex items-center gap-2 rounded-lg bg-[var(--success)]/10 px-4 py-2.5 text-sm font-medium text-[var(--success)] hover:bg-[var(--success)]/20"
            >
              <Upload className="h-4 w-4" />
              Опубликовать
            </button>
          </div>

          <p className="mt-3 text-xs text-[var(--muted)]">
            Редактор: пошаговое редактирование сценария. Схема: визуальная карта (React Flow). JSON:
            прямое редактирование.
          </p>
        </>
      )}
    </div>
  );
}
