/**
 * Database Health Settings component.
 *
 * Implements database health monitoring and repair functionality.
 * Allows administrators to check database table status and repair if needed.
 *
 * @package GetMD
 * @since   1.0.1
 */

import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Alert, AlertDescription } from './ui/alert';
import { getAPI } from '../lib/api';
import type { DatabaseHealth } from '../types/wordpress';

interface DatabaseSettingsProps {
  /**
   * When true, renders only the content without the Card wrapper.
   * Useful for embedding in a collapsible section.
   */
  inline?: boolean;
}

/**
 * Render a settings card that monitors and repairs the export history database.
 *
 * Displays current health (status, last checked time, and version), provides a Recheck action,
 * and exposes a Repair action when issues are detected; performs an initial health check on mount
 * and re-checks after a successful repair.
 *
 * @returns The Database Settings UI as a JSX.Element
 */
export function DatabaseSettings({ inline = false }: DatabaseSettingsProps) {
  const { i18n } = window.summixGetmdData || {};
  const [health, setHealth] = useState<DatabaseHealth | null>(null);
  const [isChecking, setIsChecking] = useState(false);
  const [isRepairing, setIsRepairing] = useState(false);
  const [repairResult, setRepairResult] = useState<'success' | 'error' | null>(null);

  const checkDatabaseHealth = async () => {
    setIsChecking(true);
    setRepairResult(null);
    try {
      const data = await getAPI().getDatabaseHealth();
      setHealth(data);
    } catch (error) {
      console.error('Health check failed:', error);
    } finally {
      setIsChecking(false);
    }
  };

  const repairDatabase = async () => {
    setIsRepairing(true);
    setRepairResult(null);
    try {
      const data = await getAPI().repairDatabase();
      setRepairResult(data.success ? 'success' : 'error');
      if (data.success) {
        // Re-check health after successful repair
        await checkDatabaseHealth();
      }
    } catch (error) {
      setRepairResult('error');
      console.error('Database repair failed:', error);
    } finally {
      setIsRepairing(false);
    }
  };

  useEffect(() => {
    checkDatabaseHealth();
  }, []);

  const isHealthy = health?.tableExists && health?.structureValid;
  const hasChecked = health !== null;

  // Content that can be rendered inline or inside a Card
  const content = (
    <div className="smx-space-y-4">
        {/* Health Status */}
        <div className="smx-flex smx-items-center smx-justify-between smx-p-4 smx-border smx-rounded-lg smx-bg-gray-50">
          <div className="smx-flex smx-items-center smx-gap-3">
            {isChecking || !hasChecked ? (
              <div className="smx-h-5 smx-w-5 smx-border-2 smx-border-gray-300 smx-border-t-gray-600 smx-rounded-full smx-animate-spin" />
            ) : isHealthy ? (
              <svg className="smx-h-5 smx-w-5 smx-text-green-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            ) : (
              <svg className="smx-h-5 smx-w-5 smx-text-red-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            )}
            <div>
              <p className="smx-font-medium smx-text-sm">
                {!hasChecked ? (i18n?.checking || 'Checking...') : isHealthy ? (i18n?.allGood || 'All good') : (i18n?.needsAttention || 'Needs attention')}
              </p>
              {health?.lastChecked && (
                <p className="smx-text-xs smx-text-gray-500 smx-mt-1">
                  {i18n?.checked || 'Checked'} {new Date(health.lastChecked).toLocaleString()}
                </p>
              )}
              {health?.dbVersion && health?.expectedVersion && (
                <p className="smx-text-xs smx-text-gray-500 smx-mt-0.5">
                  {i18n?.version || 'Version'} {health.dbVersion} {health.dbVersion !== health.expectedVersion && (i18n?.shouldBe?.replace('%s', health.expectedVersion) || `(should be ${health.expectedVersion})`)}
                </p>
              )}
            </div>
          </div>
          <Button
            variant="outline"
            size="sm"
            onClick={checkDatabaseHealth}
            disabled={isChecking}
          >
            {isChecking ? (i18n?.checking || 'Checking...') : (i18n?.checkAgain || 'Check again')}
          </Button>
        </div>

        {/* Repair Section */}
        {!isHealthy && health && (
          <Alert>
            <AlertDescription>
              <div className="smx-flex smx-items-start smx-gap-3">
                <svg className="smx-h-5 smx-w-5 smx-text-blue-600 smx-mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                </svg>
                <div className="smx-flex-1">
                  <p className="smx-text-sm smx-font-medium smx-mb-2">
                    {i18n?.repairNeeded || 'Repair needed'}
                  </p>
                  <p className="smx-text-sm smx-mb-3">
                    {i18n?.repairDesc || 'Some tables are missing or damaged. Repairing will restore them without affecting your exports.'}
                  </p>
                  <Button
                    onClick={repairDatabase}
                    disabled={isRepairing}
                    size="sm"
                  >
                    {isRepairing ? (
                      <>
                        <div className="smx-mr-2 smx-h-4 smx-w-4 smx-border-2 smx-border-white smx-border-t-transparent smx-rounded-full smx-animate-spin" />
                        {i18n?.repairing || 'Repairing...'}
                      </>
                    ) : (
                      <>
                        <svg className="smx-mr-2 smx-h-4 smx-w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                        </svg>
                        {i18n?.repair || 'Repair'}
                      </>
                    )}
                  </Button>
                </div>
              </div>
            </AlertDescription>
          </Alert>
        )}

        {/* Repair Result */}
        {repairResult === 'success' && (
          <Alert>
            <AlertDescription>
              <div className="smx-flex smx-items-center smx-gap-3">
                <svg className="smx-h-5 smx-w-5 smx-text-green-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                <p className="smx-text-sm smx-font-medium">
                  {i18n?.repairSuccess || 'Repaired. All good now.'}
                </p>
              </div>
            </AlertDescription>
          </Alert>
        )}

        {repairResult === 'error' && (
          <Alert variant="destructive">
            <AlertDescription>
              <div className="smx-flex smx-items-center smx-gap-3">
                <svg className="smx-h-5 smx-w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                <p className="smx-text-sm smx-font-medium">
                  {i18n?.repairFailed || 'Repair failed. Check the error log or reach out to support.'}
                </p>
              </div>
            </AlertDescription>
          </Alert>
        )}

        {/* Help Text */}
        {isHealthy && (
          <div className="smx-bg-gray-50 smx-border smx-border-gray-200 smx-rounded-lg smx-p-3">
            <p className="smx-text-xs smx-text-gray-600">
              {i18n?.databaseTip || 'This check runs automatically when you visit Settings. Use repair if exports start failing.'}
            </p>
          </div>
        )}
    </div>
  );

  // Inline mode: return just the content
  if (inline) {
    return content;
  }

  // Full mode: wrap in Card
  return (
    <Card>
      <CardHeader>
        <CardTitle>{i18n?.databaseTitle || 'Database'}</CardTitle>
        <CardDescription>
          {i18n?.databaseDesc || 'Check and fix the tables that store your export history.'}
        </CardDescription>
      </CardHeader>
      <CardContent>
        {content}
      </CardContent>
    </Card>
  );
}