'use client';

import { useEffect, useState, useMemo } from 'react';
import { Search, SlidersHorizontal, ArrowUpDown, Plus, Loader2, AlertCircle } from 'lucide-react';
import { cn } from '@/lib/utils';
import { BotCard, type BotData } from './bot-card';

type SortKey = 'name' | 'messages' | 'conversion' | 'lastActive';

export function BotGrid() {
  // Data
  const [bots, setBots] = useState<BotData[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isMock, setIsMock] = useState(false);

  // Filters
  const [search, setSearch] = useState('');
  const [showInactive, setShowInactive] = useState(true);
  const [sortKey, setSortKey] = useState<SortKey>('name');
  const [sortDir, setSortDir] = useState<'asc' | 'desc'>('asc');
  const [filterOpen, setFilterOpen] = useState(false);
  const [sortOpen, setSortOpen] = useState(false);

  // Fetch bots
  useEffect(() => {
    let cancelled = false;
    setLoading(true);
    fetch('/api/bots')
      .then((r) => r.json())
      .then((data) => {
        if (cancelled) return;
        setBots(data.bots ?? []);
        setIsMock(data.mock ?? false);
        setError(null);
      })
      .catch((err) => {
        if (cancelled) return;
        setError(err.message || 'Failed to load bots');
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, []);

  // Toggle handler (optimistic UI)
  function handleToggle(id: string, active: boolean) {
    setBots((prev) =>
      prev.map((b) => (b.id === id ? { ...b, active } : b))
    );
    // TODO: POST to API to persist toggle
  }

  // Derived list
  const filtered = useMemo(() => {
    let list = bots;
    // search
    if (search.trim()) {
      const q = search.toLowerCase();
      list = list.filter(
        (b) =>
          b.name.toLowerCase().includes(q) ||
          b.category.toLowerCase().includes(q) ||
          (b.twilioNumber && b.twilioNumber.includes(q))
      );
    }
    // filter inactive
    if (!showInactive) {
      list = list.filter((b) => b.active);
    }
    // sort
    list = [...list].sort((a, b) => {
      let cmp = 0;
      switch (sortKey) {
        case 'name':
          cmp = a.name.localeCompare(b.name);
          break;
        case 'messages':
          cmp = a.messageCount - b.messageCount;
          break;
        case 'conversion':
          cmp = (a.conversionPct ?? -1) - (b.conversionPct ?? -1);
          break;
        case 'lastActive':
          cmp =
            new Date(a.lastActive || 0).getTime() -
            new Date(b.lastActive || 0).getTime();
          break;
      }
      return sortDir === 'asc' ? cmp : -cmp;
    });
    return list;
  }, [bots, search, showInactive, sortKey, sortDir]);

  // Sort cycle
  function cycleSortKey() {
    setSortOpen((p) => !p);
  }

  function pickSort(key: SortKey) {
    if (key === sortKey) {
      setSortDir((d) => (d === 'asc' ? 'desc' : 'asc'));
    } else {
      setSortKey(key);
      setSortDir('asc');
    }
    setSortOpen(false);
  }

  // -----------------------------------------------------------------------
  // Render
  // -----------------------------------------------------------------------
  return (
    <div className="space-y-5">
      {/* Top bar */}
      <div className="flex flex-col sm:flex-row items-start sm:items-center gap-3">
        {/* Search */}
        <div className="relative flex-1 w-full sm:max-w-sm">
          <Search
            size={16}
            className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-500"
          />
          <input
            type="text"
            placeholder="Search bots…"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className={cn(
              'w-full pl-9 pr-3 py-2 rounded-lg text-sm',
              'bg-navy-800 border border-slate-700/60 text-slate-200 placeholder:text-slate-500',
              'focus:outline-none focus:ring-2 focus:ring-cyan-400/30 focus:border-cyan-500/50',
              'transition-colors'
            )}
          />
        </div>

        {/* Filter button */}
        <div className="relative">
          <button
            onClick={() => { setFilterOpen((p) => !p); setSortOpen(false); }}
            className={cn(
              'flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm border transition-colors',
              filterOpen
                ? 'bg-cyan-500/15 text-cyan-400 border-cyan-500/30'
                : 'bg-navy-800 text-slate-400 border-slate-700/60 hover:text-slate-200'
            )}
          >
            <SlidersHorizontal size={14} />
            Filter
          </button>
          {filterOpen && (
            <div className="absolute top-full mt-1 left-0 z-20 card p-3 min-w-[180px] space-y-2">
              <label className="flex items-center gap-2 text-sm text-slate-300 cursor-pointer">
                <input
                  type="checkbox"
                  checked={showInactive}
                  onChange={(e) => setShowInactive(e.target.checked)}
                  className="accent-cyan-400 rounded"
                />
                Show inactive bots
              </label>
            </div>
          )}
        </div>

        {/* Sort button */}
        <div className="relative">
          <button
            onClick={() => { cycleSortKey(); setFilterOpen(false); }}
            className={cn(
              'flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm border transition-colors',
              sortOpen
                ? 'bg-cyan-500/15 text-cyan-400 border-cyan-500/30'
                : 'bg-navy-800 text-slate-400 border-slate-700/60 hover:text-slate-200'
            )}
          >
            <ArrowUpDown size={14} />
            Sort
          </button>
          {sortOpen && (
            <div className="absolute top-full mt-1 left-0 z-20 card p-1 min-w-[180px]">
              {(
                [
                  ['name', 'Name'],
                  ['messages', 'Messages'],
                  ['conversion', 'Conversion %'],
                  ['lastActive', 'Last Active'],
                ] as [SortKey, string][]
              ).map(([key, label]) => (
                <button
                  key={key}
                  onClick={() => pickSort(key)}
                  className={cn(
                    'w-full text-left px-3 py-1.5 rounded-md text-sm transition-colors',
                    sortKey === key
                      ? 'bg-cyan-500/15 text-cyan-400'
                      : 'text-slate-300 hover:bg-slate-700/50'
                  )}
                >
                  {label}
                  {sortKey === key && (
                    <span className="ml-1 text-xs opacity-60">
                      {sortDir === 'asc' ? '↑' : '↓'}
                    </span>
                  )}
                </button>
              ))}
            </div>
          )}
        </div>

        {/* Create New Bot */}
        <button
          className={cn(
            'flex items-center gap-1.5 px-4 py-2 rounded-lg text-sm font-medium',
            'bg-cyan-500 text-white hover:bg-cyan-400 transition-colors',
            'shadow-lg shadow-cyan-500/20 ml-auto'
          )}
        >
          <Plus size={16} />
          Create New Bot
        </button>
      </div>

      {/* Mock data banner */}
      {isMock && !loading && (
        <div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-yellow-500/10 border border-yellow-500/20 text-yellow-400 text-xs">
          <AlertCircle size={14} />
          Showing sample data — connect your CloseBot API key for live bots.
        </div>
      )}

      {/* Loading state */}
      {loading && (
        <div className="flex items-center justify-center py-20">
          <Loader2 size={28} className="animate-spin text-cyan-400" />
        </div>
      )}

      {/* Error state */}
      {error && !loading && (
        <div className="flex flex-col items-center justify-center py-20 text-slate-400">
          <AlertCircle size={32} className="text-red-400 mb-2" />
          <p className="text-sm">{error}</p>
        </div>
      )}

      {/* Empty state */}
      {!loading && !error && filtered.length === 0 && (
        <div className="flex flex-col items-center justify-center py-20 text-slate-400">
          <p className="text-sm">
            {search ? 'No bots match your search.' : 'No bots found.'}
          </p>
        </div>
      )}

      {/* Bot grid */}
      {!loading && !error && filtered.length > 0 && (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {filtered.map((bot, i) => (
            <BotCard
              key={bot.id}
              bot={bot}
              index={i}
              onToggle={handleToggle}
            />
          ))}
        </div>
      )}
    </div>
  );
}
