// components/models.jsx — ModelsTable component.
// Depends on: React (global)

// ── Table Export Component ─────────────────────────────────────

function TableExport({ data, filename, title }) {
  const [showMenu, setShowMenu] = useState(false);

  const convertToCSV = (data) => {
    if (!data || data.length === 0) return '';
    
    const headers = Object.keys(data[0]);
    const csvHeaders = headers.join(',');
    
    const csvRows = data.map(row => {
      return headers.map(header => {
        const value = row[header];
        // Handle nested objects and arrays
        if (typeof value === 'object' && value !== null) {
          return `"${JSON.stringify(value).replaceAll('"', '""')}"`;
        }
        // Escape commas and quotes in strings
        if (typeof value === 'string' && (value.includes(',') || value.includes('"'))) {
          return `"${value.replaceAll('"', '""')}"`;
        }
        return value;
      }).join(',');
    });
    
    return [csvHeaders, ...csvRows].join('\n');
  };

  const downloadCSV = () => {
    const csv = convertToCSV(data);
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', `${filename}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    link.remove();
  };

  const downloadJSON = () => {
    const json = JSON.stringify(data, null, 2);
    const blob = new Blob([json], { type: 'application/json;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', `${filename}.json`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    link.remove();
  };

  const copyToClipboard = (format, event) => {
    let content;
    if (format === 'csv') {
      content = convertToCSV(data);
    } else {
      content = JSON.stringify(data, null, 2);
    }
    
    navigator.clipboard.writeText(content).then(() => {
      // Show brief success feedback
      const button = event.target;
      const originalText = button.textContent;
      button.textContent = 'Copied!';
      button.className = button.className.replace('bg-gray-100', 'bg-green-100').replace('text-gray-600', 'text-green-600');
      setTimeout(() => {
        button.textContent = originalText;
        button.className = button.className.replace('bg-green-100', 'bg-gray-100').replace('text-green-600', 'text-gray-600');
      }, 2000);
    });
  };

  if (!data || data.length === 0) {
    return null;
  }

  return (
    <div className="relative">
      <button
        onClick={() => setShowMenu(!showMenu)}
        className="text-xs px-2 py-1 rounded bg-gray-100 text-gray-600 hover:bg-gray-200 flex items-center gap-1"
        title="Export table data"
      >
        📊 Export ▼
      </button>
      
      {showMenu && (
        <div className="absolute right-0 mt-1 w-48 bg-white rounded-md shadow-lg border border-gray-200 z-10">
          <div className="py-1">
            <button
              onClick={() => { downloadCSV(); setShowMenu(false); }}
              className="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
            >
              📄 Download CSV
            </button>
            <button
              onClick={() => { downloadJSON(); setShowMenu(false); }}
              className="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
            >
              📋 Download JSON
            </button>
            <button
              onClick={(e) => { copyToClipboard('csv', e); setShowMenu(false); }}
              className="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
            >
              📋 Copy CSV
            </button>
            <button
              onClick={(e) => { copyToClipboard('json', e); setShowMenu(false); }}
              className="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
            >
              📋 Copy JSON
            </button>
          </div>
        </div>
      )}
      
      {/* Close menu when clicking outside */}
      {showMenu && (
        <div
          className="fixed inset-0 z-0"
          onClick={() => setShowMenu(false)}
          onKeyDown={(e) => { if (e.key === 'Escape') setShowMenu(false); }}
          tabIndex={-1}
        />
      )}
    </div>
  );
}

function ModelsTable({ models }) {
  if (!models || !models.length) return <p className="text-gray-500 text-sm">No models available</p>;
  
  const exportData = models.map(m => ({
    model: m.id,
    provider: m.owned_by,
    input_cost_per_1m: !m.input_cost_per_1m ? 'FREE' : `$${m.input_cost_per_1m.toFixed(2)}`,
    output_cost_per_1m: !m.output_cost_per_1m ? 'FREE' : `$${m.output_cost_per_1m.toFixed(2)}`,
    tier_range: m.tier_range || '',
    capabilities: m.capabilities?.join(', ') || ''
  }));
  
  return (
    <div>
      <div className="flex justify-between items-center mb-2">
        <span className="text-xs text-gray-500">Available models ({models.length})</span>
        <TableExport 
          data={exportData}
          filename="models"
          title="Models"
        />
      </div>
      <div className="overflow-x-auto">
      <table className="w-full text-xs">
        <thead>
          <tr className="border-b border-gray-200 text-left text-gray-500">
            <th className="pb-2 font-medium">Model</th>
            <th className="pb-2 font-medium">Provider</th>
            <th className="pb-2 font-medium text-right">Input $/1M</th>
            <th className="pb-2 font-medium text-right">Output $/1M</th>
            <th className="pb-2 font-medium">Tier Range</th>
            <th className="pb-2 font-medium">Capabilities</th>
          </tr>
        </thead>
        <tbody>
          {models.map(m => (
            <tr key={m.id} className="border-b border-gray-100 hover:bg-gray-50">
              <td className="py-2 font-mono text-gray-900">{m.id}</td>
              <td className="py-2"><span className="px-1.5 py-0.5 bg-blue-50 text-blue-700 rounded text-xs">{m.owned_by}</span></td>
              <td className="py-2 text-right font-mono">{!m.input_cost_per_1m ? <span className="text-emerald-600">FREE</span> : `$${m.input_cost_per_1m.toFixed(2)}`}</td>
              <td className="py-2 text-right font-mono">{!m.output_cost_per_1m ? <span className="text-emerald-600">FREE</span> : `$${m.output_cost_per_1m.toFixed(2)}`}</td>
              <td className="py-2 text-gray-600">{m.tier_range}</td>
              <td className="py-2">
                <div className="flex flex-wrap gap-1">
                  {m.capabilities?.map(c => (
                    <span key={c} className="px-1 py-0.5 bg-gray-100 text-gray-600 rounded text-xs">{c}</span>
                  ))}
                </div>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
    </div>
  );
}
