'use client';

import { useState, useEffect, useCallback } from 'react';
import { Settings, ChevronRight } from 'lucide-react';
import TwilioCard from '@/components/settings/twilio-card';
import CloseBotCard from '@/components/settings/closebot-card';
import PhoneNumbersCard from '@/components/settings/phone-numbers-card';
import PhoneGatewayCard from '@/components/settings/phone-gateway-card';
import NotificationsCard from '@/components/settings/notifications-card';
import WebhookUrlsCard from '@/components/settings/webhook-urls-card';

export default function SettingsPage() {
  const [settings, setSettings] = useState<Record<string, string>>({});
  const [twilioConnected, setTwilioConnected] = useState<boolean | null>(null);
  const [closebotConnected, setClosebotConnected] = useState<boolean | null>(null);
  const [closebotAgencyName, setClosebotAgencyName] = useState<string | undefined>();
  const [closebotSourcesCount, setClosebotSourcesCount] = useState<number | undefined>();
  const [testing, setTesting] = useState(false);
  const [loading, setLoading] = useState(true);

  // Load settings on mount
  useEffect(() => {
    async function load() {
      try {
        const res = await fetch('/api/settings');
        if (res.ok) {
          const data = await res.json();
          setSettings(data);
        }
      } catch (err) {
        console.error('Failed to load settings:', err);
      } finally {
        setLoading(false);
      }
    }
    load();
  }, []);

  // Save settings handler
  const handleSave = useCallback(async (updates: Record<string, string>) => {
    const res = await fetch('/api/settings', {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(updates),
    });

    if (!res.ok) {
      throw new Error('Failed to save settings');
    }

    // Update local state
    setSettings((prev) => ({ ...prev, ...updates }));
  }, []);

  // Test connections
  const handleTestConnection = useCallback(async () => {
    setTesting(true);
    try {
      const res = await fetch('/api/settings/test-connection', { method: 'POST' });
      if (res.ok) {
        const data = await res.json();
        setTwilioConnected(data.twilio);
        setClosebotConnected(data.closebot);
        if (data.closebotAgencyName) setClosebotAgencyName(data.closebotAgencyName);
        if (data.closebotSourcesCount !== undefined) setClosebotSourcesCount(data.closebotSourcesCount);
      } else {
        setTwilioConnected(false);
        setClosebotConnected(false);
      }
    } catch {
      setTwilioConnected(false);
      setClosebotConnected(false);
    } finally {
      setTesting(false);
    }
  }, []);

  // Auto-test on load
  useEffect(() => {
    if (!loading) {
      handleTestConnection();
    }
  }, [loading, handleTestConnection]);

  return (
    <div className="p-6 lg:p-8 space-y-6">
      {/* Breadcrumb Header */}
      <div>
        <div className="flex items-center gap-2 text-sm text-slate-500 mb-1">
          <Settings className="h-4 w-4" />
          <span>Settings</span>
          <ChevronRight className="h-3 w-3" />
          <span className="text-slate-300">Configuration</span>
        </div>
        <h1 className="text-2xl font-bold text-white">Settings</h1>
        <p className="text-sm text-slate-500 mt-0.5">
          Manage connections, phone numbers, and notification preferences
        </p>
      </div>

      {/* Two-column card layout */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Left column */}
        <div className="space-y-6">
          <TwilioCard
            settings={settings}
            onSave={handleSave}
            connected={twilioConnected}
            onTestConnection={handleTestConnection}
            testing={testing}
          />
          <CloseBotCard
            settings={settings}
            onSave={handleSave}
            connected={closebotConnected}
            onTestConnection={handleTestConnection}
            testing={testing}
            agencyName={closebotAgencyName}
            sourcesCount={closebotSourcesCount}
          />
          <NotificationsCard
            settings={settings}
            onSave={handleSave}
          />
        </div>

        {/* Right column */}
        <div className="space-y-6">
          <PhoneNumbersCard
            twilioConnected={twilioConnected}
          />
          <PhoneGatewayCard
            onTestConnection={handleTestConnection}
            testing={testing}
          />
          <WebhookUrlsCard />
        </div>
      </div>
    </div>
  );
}
