'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { ArrowLeft, Save, Trash2 } from 'lucide-react';

interface Company {
  id: number;
  companyName: string;
}

interface Classification {
  id: number;
  name: string;
  description: string;
  isActive: boolean;
  isSystem: boolean;
}

interface KioskSettings {
  excluded_company_ids: number[];
  excluded_classifications: string[];
  cycle_interval: number;
  refresh_interval: number;
  ticker_speed: number;
  show_rmm_alerts: boolean;
}

export default function KioskSettingsPage() {
  const router = useRouter();
  const [settings, setSettings] = useState<KioskSettings>({
    excluded_company_ids: [],
    excluded_classifications: [],
    cycle_interval: 7,
    refresh_interval: 60,
    ticker_speed: 60,
    show_rmm_alerts: false,
  });
  const [companies, setCompanies] = useState<Company[]>([]);
  const [classifications, setClassifications] = useState<Classification[]>([]);
  const [selectedCompanyId, setSelectedCompanyId] = useState<string>('');
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [syncing, setSyncing] = useState(false);

  useEffect(() => {
    fetchSettings();
    fetchCompanies();
    fetchClassifications();
  }, []);

  const fetchSettings = async () => {
    try {
      const res = await fetch('/api/kiosk/settings');
      if (res.ok) {
        const data = await res.json();
        // Ensure excluded_company_ids are numbers
        if (data.excluded_company_ids && Array.isArray(data.excluded_company_ids)) {
          data.excluded_company_ids = data.excluded_company_ids.map((id: any) => 
            typeof id === 'string' ? parseInt(id) : id
          );
        }
        setSettings(data);
      }
    } catch (error) {
      console.error('Error fetching settings:', error);
    } finally {
      setLoading(false);
    }
  };

  const fetchCompanies = async () => {
    try {
      const res = await fetch('/api/companies');
      if (res.ok) {
        const data = await res.json();
        // API returns { companies: [...] }
        const companiesList = data.companies || [];
        setCompanies(companiesList.sort((a: Company, b: Company) => 
          a.companyName.localeCompare(b.companyName)
        ));
      }
    } catch (error) {
      console.error('Error fetching companies:', error);
    }
  };

  const fetchClassifications = async () => {
    try {
      const res = await fetch('/api/sync/classifications');
      if (res.ok) {
        const data = await res.json();
        setClassifications(data.classifications || []);
      }
    } catch (error) {
      console.error('Error fetching classifications:', error);
    }
  };

  const syncClassifications = async () => {
    setSyncing(true);
    try {
      const res = await fetch('/api/sync/classifications', {
        method: 'POST',
      });
      if (res.ok) {
        const data = await res.json();
        alert(`Synced ${data.total} classifications from Autotask`);
        await fetchClassifications();
      } else {
        const error = await res.json();
        alert(`Failed to sync: ${error.error || 'Unknown error'}`);
      }
    } catch (error) {
      console.error('Error syncing classifications:', error);
      alert('Failed to sync classifications');
    } finally {
      setSyncing(false);
    }
  };

  const handleAddExcludedCompany = () => {
    if (selectedCompanyId && !settings.excluded_company_ids.includes(parseInt(selectedCompanyId))) {
      setSettings({
        ...settings,
        excluded_company_ids: [...settings.excluded_company_ids, parseInt(selectedCompanyId)],
      });
      setSelectedCompanyId('');
    }
  };

  const handleRemoveExcludedCompany = (companyId: number) => {
    setSettings({
      ...settings,
      excluded_company_ids: settings.excluded_company_ids.filter(id => id !== companyId),
    });
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      // Save each setting
      await Promise.all([
        fetch('/api/kiosk/settings', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            setting_key: 'excluded_company_ids',
            setting_value: settings.excluded_company_ids,
          }),
        }),
        fetch('/api/kiosk/settings', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            setting_key: 'excluded_classifications',
            setting_value: settings.excluded_classifications,
          }),
        }),
        fetch('/api/kiosk/settings', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            setting_key: 'cycle_interval',
            setting_value: settings.cycle_interval,
          }),
        }),
        fetch('/api/kiosk/settings', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            setting_key: 'refresh_interval',
            setting_value: settings.refresh_interval,
          }),
        }),
        fetch('/api/kiosk/settings', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            setting_key: 'show_rmm_alerts',
            setting_value: settings.show_rmm_alerts,
          }),
        }),
        fetch('/api/kiosk/settings', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            setting_key: 'ticker_speed',
            setting_value: settings.ticker_speed,
          }),
        }),
      ]);

      alert('Settings saved successfully!');
    } catch (error) {
      console.error('Error saving settings:', error);
      alert('Failed to save settings');
    } finally {
      setSaving(false);
    }
  };

  const getCompanyName = (companyId: number) => {
    // API returns id as string, settings stores as number - convert for comparison
    const idStr = companyId.toString();
    return companies.find(c => c.id.toString() === idStr)?.companyName || `Company ${companyId}`;
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-950 text-white flex items-center justify-center">
        <div className="text-xl">Loading settings...</div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-950 text-white p-8">
      <div className="max-w-4xl mx-auto">
        {/* Header */}
        <div className="flex items-center justify-between mb-8">
          <div className="flex items-center gap-4">
            <Button
              variant="ghost"
              onClick={() => router.push('/dashboard')}
              className="text-gray-400 hover:text-white"
            >
              <ArrowLeft className="w-5 h-5 mr-2" />
              Back to Dashboard
            </Button>
            <h1 className="text-3xl font-bold">Kiosk Display Settings</h1>
          </div>
          <Button
            onClick={handleSave}
            disabled={saving}
            className="bg-blue-600 hover:bg-blue-700"
          >
            <Save className="w-5 h-5 mr-2" />
            {saving ? 'Saving...' : 'Save Settings'}
          </Button>
        </div>

        <div className="space-y-8">
          {/* Excluded Companies Section */}
          <div className="bg-gray-900 rounded-lg p-6 border border-gray-800">
            <h2 className="text-xl font-semibold mb-4">Excluded Companies (Co-Managed Clients)</h2>
            <p className="text-gray-400 mb-4">
              Tickets from these companies will not appear in the kiosk display.
            </p>

            {/* Add Company */}
            <div className="flex gap-2 mb-4">
              <select
                value={selectedCompanyId}
                onChange={(e) => setSelectedCompanyId(e.target.value)}
                className="flex-1 bg-gray-800 border border-gray-700 rounded px-3 py-2 text-white"
              >
                <option value="">Select a company to exclude...</option>
                {companies
                  .filter(c => !settings.excluded_company_ids.includes(c.id))
                  .map(company => (
                    <option key={company.id} value={company.id}>
                      {company.companyName}
                    </option>
                  ))}
              </select>
              <Button
                onClick={handleAddExcludedCompany}
                disabled={!selectedCompanyId}
                className="bg-blue-600 hover:bg-blue-700"
              >
                Add
              </Button>
            </div>

            {/* Excluded Companies List */}
            <div className="space-y-2">
              {settings.excluded_company_ids.length === 0 ? (
                <div className="text-gray-500 text-center py-4">
                  No companies excluded
                </div>
              ) : (
                settings.excluded_company_ids.map(companyId => (
                  <div
                    key={companyId}
                    className="flex items-center justify-between bg-gray-800 rounded px-4 py-3 border border-gray-700"
                  >
                    <span>{getCompanyName(companyId)}</span>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleRemoveExcludedCompany(companyId)}
                      className="text-red-400 hover:text-red-300 hover:bg-red-900/20"
                    >
                      <Trash2 className="w-4 h-4" />
                    </Button>
                  </div>
                ))
              )}
            </div>
          </div>

          {/* Excluded Classifications Section */}
          <div className="bg-gray-900 rounded-lg p-6 border border-gray-800">
            <h2 className="text-xl font-semibold mb-4">Excluded Company Classifications</h2>
            <p className="text-gray-400 mb-4">
              Tickets from companies with these classifications will not appear in the kiosk display.
            </p>

            {/* Classifications from Database */}
            {classifications.length === 0 ? (
              <div className="text-center py-8 text-gray-500">
                <p className="mb-2">No classifications found.</p>
                <p className="text-sm">Refresh the page to load classifications.</p>
              </div>
            ) : (
              <div className="space-y-2">
                {classifications.map(classification => (
                  <label key={classification.id} className="flex items-center gap-3 bg-gray-800 rounded px-4 py-3 border border-gray-700 cursor-pointer hover:bg-gray-750">
                    <input
                      type="checkbox"
                      checked={settings.excluded_classifications.includes(classification.name)}
                      onChange={(e) => {
                        if (e.target.checked) {
                          setSettings({
                            ...settings,
                            excluded_classifications: [...settings.excluded_classifications, classification.name],
                          });
                        } else {
                          setSettings({
                            ...settings,
                            excluded_classifications: settings.excluded_classifications.filter(c => c !== classification.name),
                          });
                        }
                      }}
                      className="w-5 h-5 rounded border-gray-600 text-blue-600 focus:ring-blue-500"
                    />
                    <div className="flex-1">
                      <div className="font-medium">{classification.name}</div>
                      {classification.description && (
                        <div className="text-xs text-gray-500">{classification.description}</div>
                      )}
                    </div>
                  </label>
                ))}
              </div>
            )}
          </div>

          {/* Display Settings */}
          <div className="bg-gray-900 rounded-lg p-6 border border-gray-800">
            <h2 className="text-xl font-semibold mb-4">Display Settings</h2>

            <div className="space-y-4">
              {/* Cycle Interval */}
              <div>
                <label className="block text-sm font-medium mb-2">
                  KPI Card Cycle Interval: {settings.cycle_interval} seconds
                </label>
                <input
                  type="range"
                  min="3"
                  max="15"
                  step="1"
                  value={settings.cycle_interval}
                  onChange={(e) => setSettings({ ...settings, cycle_interval: parseInt(e.target.value) })}
                  className="w-full"
                />
                <div className="flex justify-between text-xs text-gray-500 mt-1">
                  <span>3s (Fast)</span>
                  <span>15s (Slow)</span>
                </div>
              </div>

              {/* Refresh Interval */}
              <div>
                <label className="block text-sm font-medium mb-2">
                  Data Refresh Interval: {settings.refresh_interval} seconds
                </label>
                <input
                  type="range"
                  min="30"
                  max="300"
                  step="30"
                  value={settings.refresh_interval}
                  onChange={(e) => setSettings({ ...settings, refresh_interval: parseInt(e.target.value) })}
                  className="w-full"
                />
                <div className="flex justify-between text-xs text-gray-500 mt-1">
                  <span>30s</span>
                  <span>5 min</span>
                </div>
              </div>

              {/* Ticker Speed */}
              <div>
                <label className="block text-sm font-medium mb-2">
                  Ticker Scroll Speed: {settings.ticker_speed} seconds
                </label>
                <input
                  type="range"
                  min="10"
                  max="120"
                  step="5"
                  value={settings.ticker_speed}
                  onChange={(e) => setSettings({ ...settings, ticker_speed: parseInt(e.target.value) })}
                  className="w-full"
                />
                <div className="flex justify-between text-xs text-gray-500 mt-1">
                  <span>10s (Fast)</span>
                  <span>120s (Slow)</span>
                </div>
              </div>
            </div>
          </div>

          {/* Filter Settings */}
          <div className="bg-gray-900 rounded-lg p-6 border border-gray-800">
            <h2 className="text-xl font-semibold mb-4">Ticket Filters</h2>

            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <div>
                  <div className="font-medium">Show RMM Alert Tickets</div>
                  <div className="text-sm text-gray-400">
                    Include automated monitoring alerts (Veeam, WAN circuits, server alerts)
                  </div>
                </div>
                <label className="relative inline-flex items-center cursor-pointer">
                  <input
                    type="checkbox"
                    checked={settings.show_rmm_alerts}
                    onChange={(e) => setSettings({ ...settings, show_rmm_alerts: e.target.checked })}
                    className="sr-only peer"
                  />
                  <div className="w-11 h-6 bg-gray-700 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                </label>
              </div>
            </div>
          </div>

          {/* Preview Link */}
          <div className="bg-gray-900 rounded-lg p-6 border border-gray-800">
            <h2 className="text-xl font-semibold mb-4">Kiosk Display</h2>
            <p className="text-gray-400 mb-4">
              Open the kiosk display in full-screen mode for your TV.
            </p>
            <Button
              onClick={() => window.open('/kiosk', '_blank')}
              className="bg-blue-600 hover:bg-blue-700"
            >
              Open Kiosk Display
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
}
