'use client';

import { useEffect, useState } from 'react';
import { Search, SlidersHorizontal, Plus, GitBranch, ChevronRight, Loader2 } from 'lucide-react';
import { cn } from '@/lib/utils';
import RoutingView from '@/components/routing/routing-view';
import type { Route, TwilioNumber, CloseBotBot, CloseBotSource } from '@/components/routing/routing-view';

export default function RoutingPage() {
  const [routes, setRoutes] = useState<Route[]>([]);
  const [numbers, setNumbers] = useState<TwilioNumber[]>([]);
  const [bots, setBots] = useState<CloseBotBot[]>([]);
  const [sources, setSources] = useState<CloseBotSource[]>([]);

  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [search, setSearch] = useState('');
  const [showNewRoute, setShowNewRoute] = useState(false);

  useEffect(() => {
    async function fetchAll() {
      try {
        const [routesRes, numbersRes, botsRes, sourcesRes] = await Promise.all([
          fetch('/api/routes'),
          fetch('/api/twilio/numbers').catch(() => null),
          fetch('/api/closebot/bots').catch(() => null),
          fetch('/api/closebot/sources').catch(() => null),
        ]);

        if (routesRes.ok) {
          setRoutes(await routesRes.json());
        }

        // These may fail if not configured — that's fine
        if (numbersRes?.ok) {
          const data = await numbersRes.json();
          setNumbers(Array.isArray(data) ? data : data.numbers || []);
        }

        if (botsRes?.ok) {
          const data = await botsRes.json();
          setBots(Array.isArray(data) ? data : data.bots || []);
        }

        if (sourcesRes?.ok) {
          const data = await sourcesRes.json();
          setSources(Array.isArray(data) ? data : data.sources || []);
        }
      } catch (err) {
        console.error('Failed to load routing data:', err);
        setError('Failed to load routing data');
      } finally {
        setLoading(false);
      }
    }

    fetchAll();
  }, []);

  if (loading) {
    return (
      <div className="flex-1 flex items-center justify-center min-h-[60vh]">
        <div className="flex flex-col items-center gap-3">
          <Loader2 className="h-8 w-8 text-cyan-400 animate-spin" />
          <p className="text-sm text-slate-500">Loading routing configuration...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="flex flex-col h-[calc(100vh)] overflow-hidden">
      {/* Top bar */}
      <div className="flex-shrink-0 px-6 pt-6 pb-4">
        {/* Breadcrumb */}
        <div className="flex items-center gap-1.5 text-[12px] text-slate-500 mb-4">
          <GitBranch className="h-3.5 w-3.5" />
          <span>Routing</span>
          <ChevronRight className="h-3 w-3" />
          <span className="text-slate-300 font-medium">Phone Number Routing</span>
        </div>

        {/* Header row */}
        <div className="flex items-center justify-between gap-4">
          <div>
            <h1 className="text-2xl font-bold text-white">Phone Number Routing</h1>
            <p className="text-sm text-slate-500 mt-0.5">
              Connect Twilio numbers to CloseBot sources for automated SMS handling
            </p>
          </div>

          <div className="flex items-center gap-3">
            {/* Search */}
            <div className="relative w-64">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-500" />
              <input
                type="text"
                placeholder="Search routes..."
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                className="w-full rounded-lg border border-slate-700/50 bg-slate-800/50 py-2 pl-10 pr-4 text-sm text-slate-200 placeholder-slate-500 outline-none transition-colors focus:border-cyan-500/50 focus:ring-1 focus:ring-cyan-500/20 backdrop-blur-sm"
              />
            </div>

            {/* Filter icon */}
            <button
              className={cn(
                'flex h-9 w-9 items-center justify-center rounded-lg border transition-colors',
                'border-slate-700/50 text-slate-500 hover:text-slate-300 hover:border-slate-600/60 hover:bg-slate-800/50'
              )}
            >
              <SlidersHorizontal className="h-4 w-4" />
            </button>

            {/* + Add New Route */}
            <button
              onClick={() => setShowNewRoute(true)}
              className={cn(
                'flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-semibold transition-all duration-200',
                'border border-cyan-500/40 text-cyan-400',
                'hover:bg-cyan-500/10 hover:border-cyan-500/60 hover:shadow-[0_0_15px_rgba(34,211,238,0.1)]'
              )}
            >
              <Plus className="h-4 w-4" />
              Add New Route
            </button>
          </div>
        </div>

        {error && (
          <div className="mt-3 rounded-lg border border-amber-500/30 bg-amber-500/10 px-4 py-2.5 flex items-center gap-2">
            <span className="text-sm text-amber-400">{error}</span>
          </div>
        )}
      </div>

      {/* Three-column routing view */}
      <div className="flex-1 min-h-0 border-t border-slate-700/30">
        <RoutingView
          initialRoutes={routes}
          initialNumbers={numbers}
          initialBots={bots}
          initialSources={sources}
          showNewRouteDialog={showNewRoute}
          onCloseNewRouteDialog={() => setShowNewRoute(false)}
        />
      </div>
    </div>
  );
}
