/**
 * Orphaned Tables Panel
 *
 * Lists third-party database tables whose owning plugin is deactivated,
 * uninstalled, or unidentified. Detection is report-only; removal is offered
 * only for tables whose owner is confirmed uninstalled and requires typing
 * DELETE to confirm.
 */

import { useState, useEffect, useCallback } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import { Spinner } from '@wordpress/components';
import apiFetch from '@wordpress/api-fetch';
import ProrankButton from '../../../components/ProrankButton';
import { useNotification } from '../../../contexts/NotificationContext';
import * as React from 'react';

interface OrphanTable {
  table: string;
  status: 'orphaned' | 'inactive' | 'unknown';
  owner: string;
  size_kb: number;
  rows: number;
}

const STATUS_META: Record<string, { label: string; color: string; bg: string }> = {
  orphaned: { label: __('Plugin uninstalled', 'prorank-seo'), color: '#b91c1c', bg: '#fef2f2' },
  inactive: { label: __('Plugin deactivated', 'prorank-seo'), color: '#92400e', bg: '#fffbeb' },
  unknown: { label: __('Unidentified', 'prorank-seo'), color: '#475569', bg: '#f1f5f9' },
};

const OrphanedTablesPanel: React.FC = () => {
  const [tables, setTables] = useState<OrphanTable[]>([]);
  const [loading, setLoading] = useState(true);
  const [dropping, setDropping] = useState<string>('');
  const { showNotification } = useNotification();

  const loadTables = useCallback(async () => {
    setLoading(true);
    try {
      const response = await apiFetch<{ tables: OrphanTable[] }>({
        path: '/prorank-seo/v1/database-optimization/orphaned-tables',
      });
      setTables(Array.isArray(response?.tables) ? response.tables : []);
    } catch (error) {
      setTables([]);
    } finally {
      setLoading(false);
    }
  }, []);

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

  const handleDrop = async (table: OrphanTable) => {
    const confirmation = window.prompt(
      sprintf(
        /* translators: %s: database table name */
        __('This permanently deletes the table %s and all its data. Make sure you have a backup. Type DELETE to confirm.', 'prorank-seo'),
        table.table
      )
    );

    if (confirmation !== 'DELETE') {
      return;
    }

    setDropping(table.table);
    try {
      const response = await apiFetch<{ success: boolean; message: string }>({
        path: '/prorank-seo/v1/database-optimization/orphaned-tables/drop',
        method: 'POST',
        data: { table: table.table, confirm: 'DELETE' },
      });
      showNotification(response?.message || __('Table removed.', 'prorank-seo'), 'success');
      await loadTables();
    } catch (error: any) {
      showNotification(error?.message || __('Failed to remove table.', 'prorank-seo'), 'error');
    } finally {
      setDropping('');
    }
  };

  return (
    <div className="prorank-card">
      <div className="prorank-card-header">
        <h3>
          <span className="dashicons dashicons-editor-table"></span>
          {__('Leftover Plugin Tables', 'prorank-seo')}
        </h3>
      </div>
      <div className="prorank-card-body">
        <p style={{ color: '#64748b', marginTop: 0 }}>
          {__('Tables created by plugins that are no longer active. Removal is only offered when the owning plugin is uninstalled — unidentified tables are listed for information only.', 'prorank-seo')}
        </p>

        {loading ? (
          <div style={{ padding: '16px', textAlign: 'center' }}>
            <Spinner />
          </div>
        ) : tables.length === 0 ? (
          <div style={{ padding: '12px 14px', background: '#f0fdf4', borderRadius: '8px', color: '#166534' }}>
            {__('No leftover tables found — every third-party table belongs to an active plugin.', 'prorank-seo')}
          </div>
        ) : (
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ textAlign: 'left', color: '#64748b', fontSize: '12px' }}>
                <th style={{ padding: '6px 8px' }}>{__('Table', 'prorank-seo')}</th>
                <th style={{ padding: '6px 8px' }}>{__('Owner', 'prorank-seo')}</th>
                <th style={{ padding: '6px 8px' }}>{__('Status', 'prorank-seo')}</th>
                <th style={{ padding: '6px 8px', textAlign: 'right' }}>{__('Size', 'prorank-seo')}</th>
                <th style={{ padding: '6px 8px' }}></th>
              </tr>
            </thead>
            <tbody>
              {tables.map((table) => {
                const meta = STATUS_META[table.status] || STATUS_META.unknown;
                return (
                  <tr key={table.table} style={{ borderTop: '1px solid #e2e8f0' }}>
                    <td style={{ padding: '8px', fontFamily: 'monospace', fontSize: '12px' }}>{table.table}</td>
                    <td style={{ padding: '8px' }}>{table.owner || '—'}</td>
                    <td style={{ padding: '8px' }}>
                      <span style={{
                        fontSize: '11px',
                        padding: '2px 8px',
                        borderRadius: '9999px',
                        color: meta.color,
                        background: meta.bg,
                        whiteSpace: 'nowrap',
                      }}>
                        {meta.label}
                      </span>
                    </td>
                    <td style={{ padding: '8px', textAlign: 'right', whiteSpace: 'nowrap' }}>
                      {table.size_kb >= 1024
                        ? `${(table.size_kb / 1024).toFixed(1)} MB`
                        : `${table.size_kb.toFixed(1)} KB`}
                    </td>
                    <td style={{ padding: '8px', textAlign: 'right' }}>
                      {table.status === 'orphaned' && (
                        <ProrankButton
                          variant="secondary"
                          size="small"
                          disabled={dropping === table.table}
                          onClick={() => handleDrop(table)}
                        >
                          {dropping === table.table
                            ? __('Removing…', 'prorank-seo')
                            : __('Remove', 'prorank-seo')}
                        </ProrankButton>
                      )}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
};

export default OrphanedTablesPanel;
