'use client';

import { useState, useEffect } from 'react';

interface Props {
  companies: any[];
  billingMode: 'mooninvoice' | 'native';
  onModeChange: (mode: 'mooninvoice' | 'native') => void;
}

export default function BillingSettingsTab({ companies, billingMode, onModeChange }: Props) {
  const [settings, setSettings] = useState<any>(null);
  const [companyData, setCompanyData] = useState<Record<string, any>>({});
  const [testResults, setTestResults] = useState<Record<string, { ok: boolean; message: string } | null>>({});
  const [testLoading, setTestLoading] = useState<Record<string, boolean>>({});
  const [saving, setSaving] = useState(false);
  const [activeSection, setActiveSection] = useState<'mooninvoice' | 'stripe' | 'defaults' | 'migration'>('mooninvoice');
  const [migrationStatus, setMigrationStatus] = useState<any>(null);
  const [migrationRunning, setMigrationRunning] = useState(false);

  useEffect(() => {
    fetch('/api/billing/settings')
      .then(r => r.json())
      .then(d => {
        setSettings(d.settings);
        const cd: Record<string, any> = {};
        (d.companies || []).forEach((c: any) => { cd[c.id] = c; });
        setCompanyData(cd);
        if (d.settings?.migration_import_status) {
          setMigrationStatus(d.settings.migration_import_status);
        }
      });
  }, []);

  const handleTestConnection = async (companyId: string, llc: string) => {
    setTestLoading(p => ({ ...p, [companyId]: true }));
    const res = await fetch('/api/billing/settings', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ action: 'test_connection', company: llc.toLowerCase() }),
    });
    const data = await res.json();
    setTestResults(p => ({ ...p, [companyId]: data }));
    setTestLoading(p => ({ ...p, [companyId]: false }));
  };

  const handleSaveSettings = async () => {
    setSaving(true);
    await fetch('/api/billing/settings', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ settings }),
    });
    setSaving(false);
  };

  const handleSaveCompany = async (companyId: string) => {
    setSaving(true);
    await fetch('/api/billing/settings', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ action: 'update_company', companyId, company: companyData[companyId] }),
    });
    setSaving(false);
  };

  const handleRunMigration = async () => {
    setMigrationRunning(true);
    try {
      const res = await fetch('/api/billing/sync', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({}),
      });
      const data = await res.json();
      setMigrationStatus(data.results);
    } finally {
      setMigrationRunning(false);
    }
  };

  const handleSwitchToNative = async () => {
    if (!confirm('Switch to native billing mode? MoonInvoice will no longer be the active data source.')) return;
    await fetch('/api/billing/settings', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ settings: { billing_mode: 'native' } }),
    });
    onModeChange('native');
  };

  const handleRollback = async () => {
    if (!confirm('Roll back to MoonInvoice mode?')) return;
    await fetch('/api/billing/settings', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ settings: { billing_mode: 'mooninvoice' } }),
    });
    onModeChange('mooninvoice');
  };

  const sections = [
    { id: 'mooninvoice', label: 'MoonInvoice' },
    { id: 'stripe', label: 'Stripe' },
    { id: 'defaults', label: 'Invoice Defaults' },
    { id: 'migration', label: 'Migration' },
  ] as const;

  return (
    <div className="flex gap-6">
      {/* Sidebar */}
      <div className="w-48 flex-shrink-0">
        <nav className="space-y-1">
          {sections.map(s => (
            <button
              key={s.id}
              onClick={() => setActiveSection(s.id)}
              className={`w-full text-left px-3 py-2 rounded-lg text-sm transition-colors ${
                activeSection === s.id
                  ? 'bg-blue-900/50 text-blue-300' :'text-gray-400 hover:text-white hover:bg-gray-800'
              }`}
            >
              {s.label}
            </button>
          ))}
        </nav>
      </div>

      {/* Content */}
      <div className="flex-1 space-y-6">

        {/* MoonInvoice Settings */}
        {activeSection === 'mooninvoice' && (
          <div className="space-y-6">
            <h2 className="text-base font-semibold text-white">MoonInvoice Settings</h2>
            {companies.map(company => (
              <div key={company.id} className="bg-gray-900 border border-gray-800 rounded-xl p-5 space-y-4">
                <h3 className="text-sm font-semibold text-gray-300">{company.name} ({company.llc_entity})</h3>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-xs text-gray-400 mb-1">MoonInvoice Company ID</label>
                    <input
                      type="text"
                      value={companyData[company.id]?.mooninvoice_company_id || ''}
                      onChange={e => setCompanyData(p => ({ ...p, [company.id]: { ...p[company.id], mooninvoice_company_id: e.target.value } }))}
                      placeholder="Enter company ID..."
                      className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-sm text-gray-200 focus:outline-none focus:border-blue-500"
                    />
                  </div>
                  <div>
                    <label className="block text-xs text-gray-400 mb-1">API Key</label>
                    <input
                      type="password"
                      value={companyData[company.id]?.mooninvoice_api_key || ''}
                      onChange={e => setCompanyData(p => ({ ...p, [company.id]: { ...p[company.id], mooninvoice_api_key: e.target.value } }))}
                      placeholder="••••••••••••••••"
                      className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-sm text-gray-200 focus:outline-none focus:border-blue-500"
                    />
                  </div>
                </div>
                <div className="flex items-center gap-3">
                  <button
                    onClick={() => handleTestConnection(company.id, company.llc_entity)}
                    disabled={testLoading[company.id]}
                    className="px-3 py-1.5 bg-gray-700 hover:bg-gray-600 text-gray-300 rounded-lg text-sm transition-colors"
                  >
                    {testLoading[company.id] ? 'Testing...' : 'Test Connection'}
                  </button>
                  {testResults[company.id] && (
                    <span className={`text-xs ${testResults[company.id]?.ok ? 'text-green-400' : 'text-red-400'}`}>
                      {testResults[company.id]?.ok ? '✓' : '✕'} {testResults[company.id]?.message}
                    </span>
                  )}
                  <button
                    onClick={() => handleSaveCompany(company.id)}
                    disabled={saving}
                    className="ml-auto px-3 py-1.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm transition-colors"
                  >
                    Save
                  </button>
                </div>
              </div>
            ))}

            {settings && (
              <div className="bg-gray-900 border border-gray-800 rounded-xl p-5 space-y-4">
                <h3 className="text-sm font-semibold text-gray-300">Sync Settings</h3>
                <div className="flex items-center gap-4">
                  <label className="text-sm text-gray-400">Sync Frequency</label>
                  <select
                    value={settings.sync_frequency_minutes}
                    onChange={e => setSettings((p: any) => ({ ...p, sync_frequency_minutes: Number(e.target.value) }))}
                    className="bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-sm text-gray-200 focus:outline-none focus:border-blue-500"
                  >
                    <option value={5}>Every 5 minutes</option>
                    <option value={15}>Every 15 minutes</option>
                    <option value={30}>Every 30 minutes</option>
                    <option value={9999}>Manual only</option>
                  </select>
                </div>
                <div className="flex items-center gap-3">
                  <button
                    onClick={async () => {
                      await fetch('/api/billing/sync', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({}) });
                    }}
                    className="px-3 py-1.5 bg-gray-700 hover:bg-gray-600 text-gray-300 rounded-lg text-sm transition-colors"
                  >
                    Sync Now
                  </button>
                  <button onClick={handleSaveSettings} disabled={saving} className="px-3 py-1.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm transition-colors">
                    Save
                  </button>
                </div>
              </div>
            )}
          </div>
        )}

        {/* Stripe Settings */}
        {activeSection === 'stripe' && (
          <div className="space-y-6">
            <h2 className="text-base font-semibold text-white">Stripe Settings</h2>
            <div className="bg-yellow-900/20 border border-yellow-700 rounded-xl p-4 text-sm text-yellow-300">
              Stripe keys will be added later. Add <code className="bg-yellow-900/40 px-1 rounded">STRIPE_SECRET_KEY_RMP</code> and <code className="bg-yellow-900/40 px-1 rounded">STRIPE_SECRET_KEY_JTR</code> to your environment variables to enable payment collection.
            </div>
            {companies.map(company => (
              <div key={company.id} className="bg-gray-900 border border-gray-800 rounded-xl p-5 space-y-4">
                <h3 className="text-sm font-semibold text-gray-300">{company.name} Stripe Account</h3>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-xs text-gray-400 mb-1">Stripe Account ID</label>
                    <input
                      type="text"
                      value={companyData[company.id]?.stripe_account_id || ''}
                      onChange={e => setCompanyData(p => ({ ...p, [company.id]: { ...p[company.id], stripe_account_id: e.target.value } }))}
                      placeholder="acct_..."
                      className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-sm text-gray-200 focus:outline-none focus:border-blue-500"
                    />
                  </div>
                  <div>
                    <label className="block text-xs text-gray-400 mb-1">Webhook Endpoint</label>
                    <input
                      type="text"
                      readOnly
                      value={`${process.env.NEXT_PUBLIC_SITE_URL || ''}/api/webhooks/stripe/${company.llc_entity?.toLowerCase()}`}
                      className="w-full bg-gray-800/50 border border-gray-700 rounded-lg px-3 py-2 text-sm text-gray-500 cursor-default"
                    />
                  </div>
                </div>
                <div className="flex items-center gap-3">
                  <span className="px-2 py-1 bg-yellow-900/50 text-yellow-300 rounded text-xs">Not Connected — Add Stripe keys to env vars</span>
                  <button onClick={() => handleSaveCompany(company.id)} disabled={saving} className="ml-auto px-3 py-1.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm transition-colors">
                    Save
                  </button>
                </div>
              </div>
            ))}
            {settings && (
              <div className="bg-gray-900 border border-gray-800 rounded-xl p-5">
                <label className="flex items-center gap-3 cursor-pointer">
                  <div
                    onClick={() => setSettings((p: any) => ({ ...p, stripe_test_mode: !p.stripe_test_mode }))}
                    className={`w-10 h-5 rounded-full transition-colors relative cursor-pointer ${settings.stripe_test_mode ? 'bg-yellow-600' : 'bg-green-600'}`}
                  >
                    <span className={`absolute top-0.5 w-4 h-4 bg-white rounded-full transition-transform ${settings.stripe_test_mode ? 'left-0.5' : 'left-5'}`} />
                  </div>
                  <span className="text-sm text-gray-300">Test Mode {settings.stripe_test_mode ? '(enabled)' : '(disabled — live)'}</span>
                </label>
                <button onClick={handleSaveSettings} disabled={saving} className="mt-3 px-3 py-1.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm transition-colors">
                  Save
                </button>
              </div>
            )}
          </div>
        )}

        {/* Invoice Defaults */}
        {activeSection === 'defaults' && settings && (
          <div className="space-y-6">
            <h2 className="text-base font-semibold text-white">Invoice Defaults</h2>
            <div className="bg-gray-900 border border-gray-800 rounded-xl p-5 space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs text-gray-400 mb-1">Default Payment Terms</label>
                  <select
                    value={settings.default_payment_terms}
                    onChange={e => setSettings((p: any) => ({ ...p, default_payment_terms: e.target.value }))}
                    className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-sm text-gray-200 focus:outline-none focus:border-blue-500"
                  >
                    {['Net 15', 'Net 30', 'Net 45', 'Due on receipt'].map(t => <option key={t}>{t}</option>)}
                  </select>
                </div>
                <div>
                  <label className="block text-xs text-gray-400 mb-1">Default Currency</label>
                  <select
                    value={settings.default_currency}
                    onChange={e => setSettings((p: any) => ({ ...p, default_currency: e.target.value }))}
                    className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-sm text-gray-200 focus:outline-none focus:border-blue-500"
                  >
                    <option>USD</option>
                  </select>
                </div>
              </div>
              <div className="space-y-3">
                <label className="flex items-center gap-3 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={settings.late_payment_reminder_enabled}
                    onChange={e => setSettings((p: any) => ({ ...p, late_payment_reminder_enabled: e.target.checked }))}
                    className="rounded"
                  />
                  <span className="text-sm text-gray-300">Late payment reminder</span>
                  {settings.late_payment_reminder_enabled && (
                    <input
                      type="number"
                      value={settings.late_payment_reminder_days}
                      onChange={e => setSettings((p: any) => ({ ...p, late_payment_reminder_days: Number(e.target.value) }))}
                      className="w-16 bg-gray-800 border border-gray-700 rounded px-2 py-1 text-sm text-gray-200 focus:outline-none focus:border-blue-500"
                    />
                  )}
                  {settings.late_payment_reminder_enabled && <span className="text-sm text-gray-400">days after due</span>}
                </label>
                <label className="flex items-center gap-3 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={settings.auto_send_reminders}
                    onChange={e => setSettings((p: any) => ({ ...p, auto_send_reminders: e.target.checked }))}
                    className="rounded"
                  />
                  <span className="text-sm text-gray-300">Auto-send reminders</span>
                </label>
              </div>
              <button onClick={handleSaveSettings} disabled={saving} className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium transition-colors">
                {saving ? 'Saving...' : 'Save Defaults'}
              </button>
            </div>
          </div>
        )}

        {/* Migration Tool */}
        {activeSection === 'migration' && (
          <div className="space-y-6">
            <h2 className="text-base font-semibold text-white">Migration Tool</h2>
            <div className="bg-gray-900 border border-gray-800 rounded-xl p-5 space-y-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-200">Current Mode</p>
                  <p className={`text-xs mt-0.5 ${billingMode === 'mooninvoice' ? 'text-blue-400' : 'text-green-400'}`}>
                    {billingMode === 'mooninvoice' ? 'MoonInvoice (live data source)' : 'Native (self-hosted)'}
                  </p>
                </div>
                <span className={`px-3 py-1 rounded-full text-xs font-medium ${billingMode === 'mooninvoice' ? 'bg-blue-900/50 text-blue-300' : 'bg-green-900/50 text-green-300'}`}>
                  {billingMode === 'mooninvoice' ? 'MoonInvoice Mode' : 'Native Mode'}
                </span>
              </div>

              {migrationStatus && (
                <div className="bg-gray-800 rounded-lg p-4 space-y-2">
                  <p className="text-xs font-semibold text-gray-300 uppercase tracking-wide">Last Import Results</p>
                  {Object.entries(migrationStatus).map(([company, result]: [string, any]) => (
                    <div key={company} className="flex items-center justify-between text-sm">
                      <span className="text-gray-400 uppercase">{company}</span>
                      {result.skipped ? (
                        <span className="text-gray-500 text-xs">Skipped — API key not configured</span>
                      ) : result.ok ? (
                        <span className="text-green-400 text-xs">✓ {result.recordsSynced} records synced</span>
                      ) : (
                        <span className="text-red-400 text-xs">✕ {result.error}</span>
                      )}
                    </div>
                  ))}
                </div>
              )}

              <div className="border-t border-gray-800 pt-4 space-y-3">
                <p className="text-xs text-gray-400">
                  The migration tool imports all historical MoonInvoice data into the native database. 
                  Once imported and verified, you can switch to native mode — no code changes, instant rollback available.
                </p>
                <div className="flex items-center gap-3 flex-wrap">
                  <button
                    onClick={handleRunMigration}
                    disabled={migrationRunning}
                    className="px-4 py-2 bg-gray-700 hover:bg-gray-600 text-gray-200 rounded-lg text-sm font-medium transition-colors"
                  >
                    {migrationRunning ? 'Running Import...' : 'Run Data Import'}
                  </button>
                  {billingMode === 'mooninvoice' ? (
                    <button
                      onClick={handleSwitchToNative}
                      disabled={!migrationStatus}
                      className="px-4 py-2 bg-green-700 hover:bg-green-600 disabled:opacity-40 disabled:cursor-not-allowed text-white rounded-lg text-sm font-medium transition-colors"
                    >
                      Switch to Native Mode
                    </button>
                  ) : (
                    <button
                      onClick={handleRollback}
                      className="px-4 py-2 bg-orange-700 hover:bg-orange-600 text-white rounded-lg text-sm font-medium transition-colors"
                    >
                      Rollback to MoonInvoice
                    </button>
                  )}
                </div>
                {billingMode === 'mooninvoice' && !migrationStatus && (
                  <p className="text-xs text-gray-500">Run Data Import first before switching to native mode.</p>
                )}
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
