'use client';

import { useState, useEffect } from 'react';
import { Phone, Loader2, RefreshCw } from 'lucide-react';
import { cn, formatPhone } from '@/lib/utils';

interface PhoneNumber {
  sid: string;
  phoneNumber: string;
  friendlyName: string;
}

interface Route {
  id: string;
  twilio_number: string;
  bot_name: string | null;
  active: number;
}

interface PhoneNumbersCardProps {
  twilioConnected: boolean | null;
}

export default function PhoneNumbersCard({ twilioConnected }: PhoneNumbersCardProps) {
  const [numbers, setNumbers] = useState<PhoneNumber[]>([]);
  const [routes, setRoutes] = useState<Route[]>([]);
  const [loading, setLoading] = useState(false);
  const [togglingId, setTogglingId] = useState<string | null>(null);

  async function fetchData() {
    setLoading(true);
    try {
      const [numbersRes, routesRes] = await Promise.all([
        fetch('/api/settings/phone-numbers'),
        fetch('/api/routes'),
      ]);

      if (numbersRes.ok) {
        const data = await numbersRes.json();
        setNumbers(Array.isArray(data) ? data : data.numbers || []);
      }

      if (routesRes.ok) {
        const data = await routesRes.json();
        setRoutes(Array.isArray(data) ? data : data.routes || []);
      }
    } catch (err) {
      console.error('Failed to fetch phone numbers:', err);
    } finally {
      setLoading(false);
    }
  }

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

  function getRouteForNumber(phoneNumber: string): Route | undefined {
    return routes.find((r) => r.twilio_number === phoneNumber);
  }

  async function handleToggle(phoneNumber: string, route: Route | undefined) {
    if (!route) return; // Can't toggle unassigned numbers
    setTogglingId(phoneNumber);
    try {
      const res = await fetch(`/api/routes/${route.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ active: route.active ? 0 : 1 }),
      });
      if (res.ok) {
        setRoutes((prev) =>
          prev.map((r) =>
            r.id === route.id ? { ...r, active: r.active ? 0 : 1 } : r
          )
        );
      }
    } catch (err) {
      console.error('Failed to toggle route:', err);
    } finally {
      setTogglingId(null);
    }
  }

  return (
    <div className="card p-6 space-y-5">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-cyan-500/10 border border-cyan-500/20">
            <Phone className="h-5 w-5 text-cyan-400" />
          </div>
          <div>
            <h3 className="text-sm font-semibold text-white">Phone Numbers</h3>
            <p className="text-xs text-slate-500">Twilio numbers & bot assignments</p>
          </div>
        </div>
        <button
          onClick={fetchData}
          disabled={loading || !twilioConnected}
          className="flex items-center gap-1.5 rounded-lg border border-slate-700/50 bg-slate-800/50 px-3 py-1.5 text-xs text-slate-400 transition-all hover:text-white hover:bg-slate-700/50 disabled:opacity-50"
        >
          <RefreshCw className={cn('h-3 w-3', loading && 'animate-spin')} />
          Refresh
        </button>
      </div>

      {/* Number list */}
      <div className="space-y-2">
        {loading ? (
          <div className="flex items-center justify-center py-8">
            <Loader2 className="h-5 w-5 animate-spin text-slate-500" />
          </div>
        ) : !twilioConnected ? (
          <div className="flex flex-col items-center py-8 text-center">
            <Phone className="h-8 w-8 text-slate-600 mb-2" />
            <p className="text-sm text-slate-500">Connect Twilio to view phone numbers</p>
          </div>
        ) : numbers.length === 0 ? (
          <div className="flex flex-col items-center py-8 text-center">
            <Phone className="h-8 w-8 text-slate-600 mb-2" />
            <p className="text-sm text-slate-500">No phone numbers found</p>
            <p className="text-xs text-slate-600 mt-1">Add numbers in your Twilio console</p>
          </div>
        ) : (
          numbers.map((num) => {
            const route = getRouteForNumber(num.phoneNumber);
            const isActive = route?.active === 1;
            const isAssigned = !!route;
            const isToggling = togglingId === num.phoneNumber;

            return (
              <div
                key={num.sid}
                className={cn(
                  'flex items-center justify-between rounded-lg border px-4 py-3 transition-colors',
                  isActive
                    ? 'border-slate-700/50 bg-slate-800/30'
                    : 'border-slate-700/30 bg-slate-800/20'
                )}
              >
                <div className="flex items-center gap-3 min-w-0">
                  <div className={cn(
                    'flex h-8 w-8 items-center justify-center rounded-full flex-shrink-0',
                    isActive ? 'bg-cyan-500/10' : 'bg-slate-700/50'
                  )}>
                    <Phone className={cn('h-3.5 w-3.5', isActive ? 'text-cyan-400' : 'text-slate-500')} />
                  </div>
                  <div className="min-w-0">
                    <p className="text-sm font-medium text-slate-200 num truncate">
                      {formatPhone(num.phoneNumber)}
                    </p>
                    <p className="text-xs text-slate-500 truncate">
                      {isAssigned ? (
                        <>Assigned Bot: <span className="text-cyan-400/80">{route.bot_name || 'Unnamed'}</span></>
                      ) : (
                        <span className="text-slate-600 italic">Unassigned</span>
                      )}
                    </p>
                  </div>
                </div>

                {/* Toggle switch */}
                <button
                  onClick={() => handleToggle(num.phoneNumber, route)}
                  disabled={!isAssigned || isToggling}
                  className={cn(
                    'relative inline-flex h-6 w-11 flex-shrink-0 rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none',
                    !isAssigned && 'opacity-40 cursor-not-allowed',
                    isActive ? 'bg-cyan-500' : 'bg-slate-600'
                  )}
                >
                  <span
                    className={cn(
                      'inline-block h-5 w-5 rounded-full bg-white shadow-sm transition-transform duration-200 ease-in-out',
                      isActive ? 'translate-x-5' : 'translate-x-0'
                    )}
                  />
                </button>
              </div>
            );
          })
        )}
      </div>
    </div>
  );
}
