'use client';

import { useState, useEffect } from 'react';
import { apiRequest } from '@/lib/api';
import { SidebarNav } from '@/components/sidebar-nav';

interface CosmosConfig {
  configured: boolean;
  endpoint: string | null;
  database: string | null;
  updatedAt: string | null;
}

interface CosmosStatus {
  isInitialized: boolean;
  error: string | null;
}

export default function CosmosConfigPage() {
  const [config, setConfig] = useState<CosmosConfig | null>(null);
  const [status, setStatus] = useState<CosmosStatus | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [testing, setTesting] = useState(false);
  const [endpoint, setEndpoint] = useState('');
  const [key, setKey] = useState('');
  const [database, setDatabase] = useState('bytelyst-platform');
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  useEffect(() => {
    loadConfig();
    loadStatus();
  }, []);

  const loadConfig = async () => {
    try {
      const data = await apiRequest<CosmosConfig>('/cosmos-config');
      setConfig(data);
      if (data.configured && data.endpoint) {
        setEndpoint(data.endpoint);
        setDatabase(data.database || 'bytelyst-platform');
      }
    } catch (error) {
      console.error('Failed to load Cosmos config:', error);
    } finally {
      setLoading(false);
    }
  };

  const loadStatus = async () => {
    try {
      const data = await apiRequest<CosmosStatus>('/cosmos-status');
      setStatus(data);
    } catch (error) {
      console.error('Failed to load Cosmos status:', error);
    }
  };

  const testConnection = async () => {
    setTesting(true);
    setMessage(null);

    try {
      const data = await apiRequest<{ success: boolean; message: string; error?: string }>('/cosmos-test', {
        method: 'POST',
        body: JSON.stringify({ endpoint, key }),
      });

      if (data.success) {
        setMessage({ type: 'success', text: data.message });
      } else {
        setMessage({ type: 'error', text: data.error || 'Connection failed' });
      }
    } catch (error: any) {
      setMessage({ type: 'error', text: error.message || 'Failed to test connection' });
    } finally {
      setTesting(false);
    }
  };

  const saveConfig = async () => {
    setSaving(true);
    setMessage(null);

    try {
      const data = await apiRequest<{ success: boolean; message: string; error?: string }>('/cosmos-config', {
        method: 'POST',
        body: JSON.stringify({ endpoint, key, database }),
      });

      if (data.success) {
        setMessage({ type: 'success', text: data.message });
        await loadConfig();
        await loadStatus();
      } else {
        setMessage({ type: 'error', text: data.error || 'Failed to save configuration' });
      }
    } catch (error: any) {
      setMessage({ type: 'error', text: error.message || 'Failed to save configuration' });
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
      </div>
    );
  }

  return (
    <div className="flex min-h-screen bg-gray-50">
      <SidebarNav />

      <main className="flex-1 min-w-0 overflow-y-auto">
        <div className="p-8 max-md:p-4">
          <div className="mb-8">
        <h1 className="text-3xl font-bold text-gray-900 mb-2">Cosmos DB Configuration</h1>
        <p className="text-gray-600">Configure your Azure Cosmos DB connection for the DevOps dashboard.</p>
      </div>

      {/* Status Card */}
      <div className="bg-white rounded-lg shadow-md p-6 mb-6">
        <h2 className="text-xl font-semibold text-gray-900 mb-4">Connection Status</h2>
        {status ? (
          <div className="space-y-2">
            <div className="flex items-center">
              <span className="text-gray-600 w-32">Status:</span>
              <span className={`font-medium ${status.isInitialized ? 'text-green-600' : 'text-red-600'}`}>
                {status.isInitialized ? 'Connected' : 'Not Connected'}
              </span>
            </div>
            {status.error && (
              <div className="flex items-start">
                <span className="text-gray-600 w-32">Error:</span>
                <span className="text-red-600">{status.error}</span>
              </div>
            )}
          </div>
        ) : (
          <p className="text-gray-500">Loading status...</p>
        )}
      </div>

      {/* Configuration Form */}
      <div className="bg-white rounded-lg shadow-md p-6 mb-6">
        <h2 className="text-xl font-semibold text-gray-900 mb-4">Configuration</h2>
        <form onSubmit={(e) => { e.preventDefault(); saveConfig(); }} className="space-y-4">
          <div>
            <label htmlFor="endpoint" className="block text-sm font-medium text-gray-700 mb-1">
              Cosmos DB Endpoint
            </label>
            <input
              type="url"
              id="endpoint"
              value={endpoint}
              onChange={(e) => setEndpoint(e.target.value)}
              placeholder="https://your-account.documents.azure.com:443/"
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              required
            />
            <p className="mt-1 text-sm text-gray-500">
              The endpoint URL of your Azure Cosmos DB account
            </p>
          </div>

          <div>
            <label htmlFor="key" className="block text-sm font-medium text-gray-700 mb-1">
              Account Key
            </label>
            <input
              type="password"
              id="key"
              value={key}
              onChange={(e) => setKey(e.target.value)}
              placeholder="Enter your Cosmos DB account key"
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              required={!config?.configured}
            />
            <p className="mt-1 text-sm text-gray-500">
              The primary or secondary key of your Cosmos DB account
            </p>
          </div>

          <div>
            <label htmlFor="database" className="block text-sm font-medium text-gray-700 mb-1">
              Database Name
            </label>
            <input
              type="text"
              id="database"
              value={database}
              onChange={(e) => setDatabase(e.target.value)}
              placeholder="bytelyst-platform"
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              required
            />
            <p className="mt-1 text-sm text-gray-500">
              The name of the Cosmos DB database to use
            </p>
          </div>

          {message && (
            <div className={`p-3 rounded-md ${message.type === 'success' ? 'bg-green-50 text-green-800' : 'bg-red-50 text-red-800'}`}>
              {message.text}
            </div>
          )}

          <div className="flex space-x-3">
            <button
              type="submit"
              disabled={saving}
              className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {saving ? 'Saving...' : 'Save Configuration'}
            </button>
            <button
              type="button"
              onClick={testConnection}
              disabled={testing || !endpoint || !key}
              className="px-4 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-gray-500 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {testing ? 'Testing...' : 'Test Connection'}
            </button>
          </div>
        </form>
      </div>

      {/* Help Section */}
      <div className="bg-blue-50 rounded-lg p-6">
        <h3 className="text-lg font-semibold text-blue-900 mb-2">Need help?</h3>
        <ul className="list-disc list-inside text-blue-800 space-y-1">
          <li>For local development, you can use the Azure Cosmos DB Emulator</li>
          <li>Emulator endpoint: <code className="bg-blue-100 px-1 rounded">https://localhost:8081</code></li>
          <li>Emulator key: <code className="bg-blue-100 px-1 rounded">C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==</code></li>
          <li>Download the emulator from: <a href="https://aka.ms/cosmosdb-emulator" target="_blank" rel="noopener noreferrer" className="underline hover:text-blue-600">aka.ms/cosmosdb-emulator</a></li>
        </ul>
      </div>
        </div>
      </main>
    </div>
  );
}
