// src/components/DBManager.tsx
import React, { useState, useEffect } from 'react';
import apiClient from '../services/api';

interface DomainConfig {
  domain_id: string;
  name: string;
}

interface DBManagerProps {
  activeDomain: string;
  setActiveDomain: (domain: string) => void;
}

const DBManager: React.FC<DBManagerProps> = ({ activeDomain, setActiveDomain }) => {
  const [domains, setDomains] = useState<DomainConfig[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    const fetchDomains = async () => {
      try {
        const response = await apiClient.get('/config/domains');
        setDomains(response.data);
        // Set a default active DB if the current one isn't in the list
        if (response.data.length > 0 && !response.data.some((d: DomainConfig) => d.domain_id === activeDomain)) {
          setActiveDomain(response.data[0].domain_id);
        }
      } catch (err) {
        setError('Failed to load domains.');
        console.error(err);
      } finally {
        setIsLoading(false);
      }
    };
    fetchDomains();
  }, [activeDomain, setActiveDomain]);

  useEffect(() => {
    // When activeDomain changes, post it to the backend
    if (activeDomain) {
      const postActiveDomain = async () => {
        try {
          await apiClient.post('/config/domains/active', { domain_id: activeDomain });
        } catch (err) {
          console.error("Failed to set active domain", err);
        }
      };
      postActiveDomain();
    }
  }, [activeDomain]);

  if (isLoading) {
    return <div className="panel-section"><h3>Knowledge Base Management</h3><p>Loading domains...</p></div>;
  }

  if (error) {
    return <div className="panel-section"><h3>Knowledge Base Management</h3><p style={{color: 'red'}}>{error}</p></div>;
  }

  return (
    <div className="panel-section">
      <h3>Knowledge Base Management</h3>
      
      <div className="form-group">
        <label>Active Knowledge Base (Domain)</label>
        <select value={activeDomain} onChange={(e) => setActiveDomain(e.target.value)}>
          {domains.map(domain => (
            <option key={domain.domain_id} value={domain.domain_id}>
              {domain.name}
            </option>
          ))}
        </select>
      </div>

      <button onClick={() => alert('Uploading/Importing DB... (Not implemented)')}>
        Upload / Import DB
      </button>
    </div>
  );
};

export default DBManager;

