'use client';

import { useEffect, useState, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { Plus, Search, LayoutGrid, ChevronDown, Filter, Loader2, Settings } from 'lucide-react';
import { cn } from '@/lib/cn';
import { api } from '@/lib/api';
import { DealTable } from '@/components/crm/deal-table';
import { CreateDealDialog } from '@/components/crm/create-deal-dialog';
import type { DealCardData } from '@/components/crm/deal-card';

interface Pipeline {
  id: string;
  name: string;
  isDefault: boolean;
}

export default function CrmListPage() {
  const router = useRouter();
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const [deals, setDeals] = useState<DealCardData[]>([]);
  const [pipelines, setPipelines] = useState<Pipeline[]>([]);

  // Filters
  const [pipelineId, setPipelineId] = useState('');
  const [search, setSearch] = useState('');
  const [source, setSource] = useState('');
  const [assigneeId, setAssigneeId] = useState('');
  const [dateFrom, setDateFrom] = useState('');
  const [dateTo, setDateTo] = useState('');
  const [showFilters, setShowFilters] = useState(false);

  const [staff, setStaff] = useState<{ id: string; firstName: string; lastName: string }[]>([]);
  const [showCreate, setShowCreate] = useState(false);

  useEffect(() => {
    api
      .get<Pipeline[]>('/crm/pipelines')
      .then((data) => {
        setPipelines(data);
        if (data.length > 0) {
          const def = data.find((p) => p.isDefault) ?? data[0];
          if (def) setPipelineId(def.id);
        }
      })
      .catch(() => {});
    api
      .get<{ id: string; firstName: string; lastName: string }[]>('/users/staff')
      .then(setStaff)
      .catch(() => {});
  }, []);

  const fetchDeals = useCallback(async () => {
    if (!pipelineId) return;
    setLoading(true);
    setError(null);

    try {
      const params = new URLSearchParams();
      params.set('pipelineId', pipelineId);
      params.set('limit', '100');
      if (search) params.set('search', search);
      if (source) params.set('source', source);
      if (assigneeId) params.set('assigneeId', assigneeId);
      if (dateFrom) params.set('dateFrom', dateFrom);
      if (dateTo) params.set('dateTo', dateTo);

      const data = await api.get<{ data: DealCardData[] }>(`/crm/deals?${params.toString()}`);
      setDeals(data.data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Ошибка загрузки');
    } finally {
      setLoading(false);
    }
  }, [pipelineId, search, source, assigneeId, dateFrom, dateTo]);

  useEffect(() => {
    const timeout = setTimeout(() => {
      void fetchDeals();
    }, 300);
    return () => clearTimeout(timeout);
  }, [fetchDeals]);

  const handleDealClick = (dealIdOrNumber: string) => {
    router.push(`/crm/deal/${dealIdOrNumber}`);
  };

  return (
    <div>
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-text">CRM</h1>
          <p className="text-sm text-muted mt-1">Управление сделками и воронкой продаж</p>
        </div>
        <div className="flex items-center gap-3">
          <button
            onClick={() => router.push('/crm/settings')}
            className="px-3 py-2 text-sm text-muted border border-border rounded-lg hover:bg-background transition-colors"
          >
            <Settings className="h-4 w-4" />
          </button>
          <button
            onClick={() => setShowCreate(true)}
            className="flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium hover:bg-primary/90 transition-colors"
          >
            <Plus className="h-4 w-4" />
            Новая сделка
          </button>
        </div>
      </div>

      {/* Filters bar */}
      <div className="bg-card rounded-xl shadow-sm border border-border mb-4">
        <div className="p-4 flex items-center gap-3 flex-wrap">
          {/* Pipeline selector */}
          <div className="relative">
            <select
              value={pipelineId}
              onChange={(e) => setPipelineId(e.target.value)}
              className="appearance-none px-3 py-2 pr-8 border border-border rounded-lg text-sm bg-background text-text focus:outline-none focus:ring-2 focus:ring-primary/30"
            >
              {pipelines.map((p) => (
                <option key={p.id} value={p.id}>
                  {p.name}
                </option>
              ))}
            </select>
            <ChevronDown className="absolute right-2 top-1/2 -translate-y-1/2 h-4 w-4 text-muted pointer-events-none" />
          </div>

          {/* Search */}
          <div className="relative flex-1 min-w-48">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted" />
            <input
              type="text"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="Поиск по номеру, названию или контакту..."
              className="w-full pl-9 pr-3 py-2 border border-border rounded-lg text-sm bg-background text-text focus:outline-none focus:ring-2 focus:ring-primary/30"
            />
          </div>

          {/* Source filter */}
          <select
            value={source}
            onChange={(e) => setSource(e.target.value)}
            className="appearance-none px-3 py-2 pr-8 border border-border rounded-lg text-sm bg-background text-text focus:outline-none focus:ring-2 focus:ring-primary/30"
          >
            <option value="">Все источники</option>
            <option value="LANDING">Лендинг</option>
            <option value="MANUAL">Вручную</option>
            <option value="WEBHOOK">Вебхук</option>
            <option value="PHONE">Телефон</option>
            <option value="REFERRAL">Реферал</option>
            <option value="SOCIAL">Соцсети</option>
          </select>

          {/* Filters toggle */}
          <button
            onClick={() => setShowFilters(!showFilters)}
            className={cn(
              'flex items-center gap-1.5 px-3 py-2 text-sm border border-border rounded-lg transition-colors',
              showFilters
                ? 'bg-primary text-white border-primary'
                : 'text-muted hover:bg-background',
            )}
          >
            <Filter className="h-4 w-4" />
            Фильтры
            {(assigneeId || dateFrom || dateTo) && (
              <span className="w-1.5 h-1.5 rounded-full bg-primary" />
            )}
          </button>

          {/* View toggle: List active, Kanban link */}
          <div className="flex items-center border border-border rounded-lg overflow-hidden">
            <button
              onClick={() => router.push('/crm/deal/kanban')}
              className="px-3 py-2 text-sm text-muted hover:bg-background transition-colors flex items-center gap-1"
            >
              <LayoutGrid className="h-4 w-4" />
            </button>
            <button className="px-3 py-2 text-sm bg-primary text-white">Список</button>
          </div>
        </div>

        {/* Advanced filters row */}
        {showFilters && (
          <div className="px-4 pb-4 pt-0 flex items-center gap-3 flex-wrap border-t border-border/50 mt-0 pt-3">
            <div>
              <label className="block text-[10px] text-muted mb-0.5">Ответственный</label>
              <select
                value={assigneeId}
                onChange={(e) => setAssigneeId(e.target.value)}
                className="appearance-none px-3 py-1.5 border border-border rounded-lg text-sm bg-background text-text focus:outline-none focus:ring-2 focus:ring-primary/30"
              >
                <option value="">Все</option>
                {staff.map((s) => (
                  <option key={s.id} value={s.id}>
                    {s.firstName} {s.lastName}
                  </option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-[10px] text-muted mb-0.5">Дата от</label>
              <input
                type="date"
                value={dateFrom}
                onChange={(e) => setDateFrom(e.target.value)}
                className="px-3 py-1.5 border border-border rounded-lg text-sm bg-background text-text focus:outline-none focus:ring-2 focus:ring-primary/30"
              />
            </div>
            <div>
              <label className="block text-[10px] text-muted mb-0.5">Дата до</label>
              <input
                type="date"
                value={dateTo}
                onChange={(e) => setDateTo(e.target.value)}
                className="px-3 py-1.5 border border-border rounded-lg text-sm bg-background text-text focus:outline-none focus:ring-2 focus:ring-primary/30"
              />
            </div>
            {(assigneeId || dateFrom || dateTo) && (
              <button
                onClick={() => {
                  setAssigneeId('');
                  setDateFrom('');
                  setDateTo('');
                }}
                className="text-xs text-primary hover:underline self-end mb-1"
              >
                Сбросить
              </button>
            )}
          </div>
        )}
      </div>

      {/* Content */}
      {loading ? (
        <div className="flex items-center justify-center py-20">
          <Loader2 className="h-8 w-8 animate-spin text-primary" />
        </div>
      ) : error ? (
        <div className="bg-error/10 text-error rounded-xl p-6 text-center">
          <p>{error}</p>
          <button onClick={fetchDeals} className="mt-2 text-sm underline hover:no-underline">
            Повторить
          </button>
        </div>
      ) : (
        <div className="bg-card rounded-xl shadow-sm border border-border">
          <DealTable deals={deals} onDealClick={handleDealClick} />
        </div>
      )}

      <CreateDealDialog
        open={showCreate}
        onClose={() => setShowCreate(false)}
        onCreated={fetchDeals}
      />
    </div>
  );
}
