'use client';

import { useEffect, useState, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { ArrowLeft, Plus, Trash2, GripVertical, Copy, Loader2 } from 'lucide-react';
import { cn } from '@/lib/cn';
import { api } from '@/lib/api';
import { PipelineManager } from '@/components/crm/pipeline-manager';
import { FieldManager } from '@/components/crm/field-manager';
import { CardLayoutEditor } from '@/components/crm/card-layout-editor';

type Tab = 'pipelines' | 'fields' | 'card-layout' | 'webhooks' | 'lost-reasons';

interface WebhookEndpoint {
  id: string;
  name: string;
  token: string;
  isActive: boolean;
  antifraudEnabled: boolean;
  createdAt: string;
}

interface LostReason {
  id: string;
  name: string;
  isActive: boolean;
  position: number;
}

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

  return (
    <div>
      {/* Header */}
      <div className="flex items-center gap-3 mb-6">
        <button
          onClick={() => router.push('/crm')}
          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">Настройки CRM</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: 'pipelines' as const, label: 'Воронки' },
          { key: 'fields' as const, label: 'Кастомные поля' },
          { key: 'card-layout' as const, label: 'Раскладка карточки' },
          { key: 'webhooks' as const, label: 'Вебхуки' },
          { key: 'lost-reasons' 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 === 'pipelines' && <PipelinesTab />}
      {tab === 'fields' && <FieldsTab />}
      {tab === 'card-layout' && <CardLayoutTab />}
      {tab === 'webhooks' && <WebhooksTab />}
      {tab === 'lost-reasons' && <LostReasonsTab />}
    </div>
  );
}

// --- Pipelines Tab ---
function PipelinesTab() {
  return <PipelineManager />;
}

// --- Custom Fields Tab ---
function FieldsTab() {
  const [entityType, setEntityType] = useState('deal');
  const entityTypes = [
    { key: 'deal', label: 'Сделки' },
    { key: 'training', label: 'Тренировки' },
  ];

  return (
    <div>
      <div className="flex items-center gap-1 mb-4">
        {entityTypes.map((et) => (
          <button
            key={et.key}
            onClick={() => setEntityType(et.key)}
            className={cn(
              'px-3 py-1.5 text-xs font-medium rounded-lg transition-colors',
              entityType === et.key
                ? 'bg-primary/10 text-primary'
                : 'text-muted hover:text-text hover:bg-background',
            )}
          >
            {et.label}
          </button>
        ))}
      </div>
      <FieldManager key={entityType} entityType={entityType} />
    </div>
  );
}

// --- Card Layout Tab ---
function CardLayoutTab() {
  const [entityType, setEntityType] = useState('deal');
  const entityTypes = [{ key: 'deal', label: 'Сделки' }];

  return (
    <div>
      <div className="flex items-center gap-1 mb-4">
        {entityTypes.map((et) => (
          <button
            key={et.key}
            onClick={() => setEntityType(et.key)}
            className={cn(
              'px-3 py-1.5 text-xs font-medium rounded-lg transition-colors',
              entityType === et.key
                ? 'bg-primary/10 text-primary'
                : 'text-muted hover:text-text hover:bg-background',
            )}
          >
            {et.label}
          </button>
        ))}
      </div>
      <CardLayoutEditor key={entityType} entityType={entityType} />
    </div>
  );
}

// --- Webhooks Tab ---
function WebhooksTab() {
  const [endpoints, setEndpoints] = useState<WebhookEndpoint[]>([]);
  const [loading, setLoading] = useState(true);
  const [creating, setCreating] = useState(false);
  const [newName, setNewName] = useState('');

  const fetchEndpoints = useCallback(async () => {
    try {
      const data = await api.get<WebhookEndpoint[]>('/crm/webhooks');
      setEndpoints(data);
    } catch {
      // silently ignore fetch errors
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    void fetchEndpoints();
  }, [fetchEndpoints]);

  const handleCreate = async () => {
    if (!newName.trim()) return;
    setCreating(true);
    try {
      await api.post('/crm/webhooks', { name: newName.trim() });
      setNewName('');
      await fetchEndpoints();
    } catch {
      // silently ignore create errors
    } finally {
      setCreating(false);
    }
  };

  const handleDelete = async (id: string) => {
    await api.delete(`/crm/webhooks/${id}`);
    await fetchEndpoints();
  };

  const copyUrl = (token: string) => {
    const baseUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/v1';
    navigator.clipboard.writeText(`${baseUrl}/crm/deals/webhook/${token}`);
  };

  if (loading) return <LoadingState />;

  return (
    <div className="space-y-4">
      {/* Create form */}
      <div className="flex items-center gap-3">
        <input
          type="text"
          value={newName}
          onChange={(e) => setNewName(e.target.value)}
          onKeyDown={(e) => {
            if (e.key === 'Enter') void handleCreate();
          }}
          placeholder="Название вебхука (например: Заявки с Tilda)"
          className="flex-1 px-3 py-2 border border-border rounded-lg text-sm bg-background text-text focus:outline-none focus:ring-2 focus:ring-primary/30"
        />
        <button
          onClick={() => void handleCreate()}
          disabled={creating || !newName.trim()}
          className="flex items-center gap-1.5 px-4 py-2 bg-primary text-white rounded-lg text-sm hover:bg-primary/90 disabled:opacity-50 transition-colors"
        >
          <Plus className="h-4 w-4" />
          Создать
        </button>
      </div>

      {/* List */}
      <div className="space-y-2">
        {endpoints.map((ep) => (
          <div
            key={ep.id}
            className="bg-card rounded-xl border border-border p-4 flex items-center justify-between gap-4"
          >
            <div className="flex-1 min-w-0">
              <div className="flex items-center gap-2">
                <span className="font-medium text-text text-sm">{ep.name}</span>
                <span
                  className={cn(
                    'text-[10px] px-1.5 py-0.5 rounded-full',
                    ep.isActive ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700',
                  )}
                >
                  {ep.isActive ? 'Активен' : 'Отключен'}
                </span>
              </div>
              <div className="text-xs text-muted mt-1 font-mono truncate">
                /crm/deals/webhook/{ep.token}
              </div>
            </div>
            <div className="flex items-center gap-2 shrink-0">
              <button
                onClick={() => copyUrl(ep.token)}
                className="p-2 rounded-lg hover:bg-background text-muted hover:text-text transition-colors"
                title="Копировать URL"
              >
                <Copy className="h-4 w-4" />
              </button>
              <button
                onClick={() => void handleDelete(ep.id)}
                className="p-2 rounded-lg hover:bg-error/10 text-muted hover:text-error transition-colors"
                title="Удалить"
              >
                <Trash2 className="h-4 w-4" />
              </button>
            </div>
          </div>
        ))}

        {endpoints.length === 0 && (
          <div className="text-center py-8 text-muted text-sm">Нет вебхук-эндпоинтов</div>
        )}
      </div>
    </div>
  );
}

// --- Lost Reasons Tab ---
function LostReasonsTab() {
  const [reasons, setReasons] = useState<LostReason[]>([]);
  const [loading, setLoading] = useState(true);
  const [newReason, setNewReason] = useState('');

  const fetchReasons = useCallback(async () => {
    try {
      const data = await api.get<LostReason[]>('/crm/lost-reasons');
      setReasons(data);
    } catch {
      // silently ignore
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    void fetchReasons();
  }, [fetchReasons]);

  const handleCreate = async () => {
    if (!newReason.trim()) return;
    try {
      await api.post('/crm/lost-reasons', { name: newReason.trim() });
      setNewReason('');
      await fetchReasons();
    } catch {
      // silently ignore
    }
  };

  if (loading) return <LoadingState />;

  return (
    <div className="space-y-4">
      <div className="flex items-center gap-3">
        <input
          type="text"
          value={newReason}
          onChange={(e) => setNewReason(e.target.value)}
          onKeyDown={(e) => {
            if (e.key === 'Enter') void handleCreate();
          }}
          placeholder="Новая причина проигрыша..."
          className="flex-1 px-3 py-2 border border-border rounded-lg text-sm bg-background text-text focus:outline-none focus:ring-2 focus:ring-primary/30"
        />
        <button
          onClick={() => void handleCreate()}
          disabled={!newReason.trim()}
          className="flex items-center gap-1.5 px-4 py-2 bg-primary text-white rounded-lg text-sm hover:bg-primary/90 disabled:opacity-50 transition-colors"
        >
          <Plus className="h-4 w-4" />
          Добавить
        </button>
      </div>

      <div className="bg-card rounded-xl border border-border">
        <div className="space-y-0">
          {reasons.map((reason) => (
            <div
              key={reason.id}
              className="flex items-center gap-3 px-4 py-3 border-b border-border/50 last:border-0"
            >
              <GripVertical className="h-4 w-4 text-muted/50" />
              <span className="text-sm text-text flex-1">{reason.name}</span>
              <span
                className={cn(
                  'text-[10px] px-1.5 py-0.5 rounded-full',
                  reason.isActive ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700',
                )}
              >
                {reason.isActive ? 'Активна' : 'Неактивна'}
              </span>
            </div>
          ))}
          {reasons.length === 0 && (
            <div className="text-center py-8 text-muted text-sm">Нет причин проигрыша</div>
          )}
        </div>
      </div>
    </div>
  );
}

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