import { useState } from 'react';
import { colors, fonts } from '@formiq/core';
import FormsTab from './components/FormsTab';

type Tab = 'dashboard' | 'forms' | 'settings';

const TABS: { id: Tab; label: string }[] = [
  { id: 'dashboard', label: 'Dashboard' },
  { id: 'forms',     label: 'Forms' },
  { id: 'settings',  label: 'Settings' },
];

// wp_localize_script sets window.formiqConfig — use window explicitly so Vite
// doesn't evaluate the typeof check at bundle time and collapse it to false.
const wpConfig = (window as unknown as Record<string, unknown>)['formiqConfig'] as
  { restUrl: string; nonce: string; version: string; logoUrl?: string; plan?: string } | undefined;

export default function App() {
  const [activeTab, setActiveTab] = useState<Tab>('dashboard');
  const logoUrl = wpConfig?.logoUrl;
  const plan = wpConfig?.plan ?? 'free';
  const isPro = plan === 'pro';

  return (
    <div style={{ fontFamily: fonts.body, backgroundColor: colors.background, minHeight: '100vh' }}>
      {/* Branded header */}
      <header
        style={{
          background: `linear-gradient(135deg, ${colors.primary} 0%, #8B85FF 100%)`,
          padding: '16px 24px',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
        }}
      >
        <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          {/* GTS logo */}
          {logoUrl ? (
            <img
              src={logoUrl}
              alt="Ganda Tech Services"
              style={{
                width: 44,
                height: 44,
                borderRadius: 10,
                backgroundColor: 'rgba(255,255,255,0.95)',
                padding: 4,
                objectFit: 'contain',
                flexShrink: 0,
              }}
            />
          ) : (
            <div
              style={{
                width: 44,
                height: 44,
                backgroundColor: 'rgba(255,255,255,0.2)',
                borderRadius: 10,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                flexShrink: 0,
              }}
            >
              <span style={{ color: '#fff', fontWeight: 800, fontSize: 16, fontFamily: fonts.heading }}>GTS</span>
            </div>
          )}

          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <h1 style={{ fontFamily: fonts.heading, fontWeight: 700, fontSize: 20, color: '#fff', margin: 0, lineHeight: 1 }}>
                FormIQ
              </h1>
              <span
                style={{
                  fontSize: 11,
                  fontWeight: 600,
                  color: colors.primary,
                  backgroundColor: '#fff',
                  padding: '2px 8px',
                  borderRadius: 999,
                  lineHeight: 1.5,
                }}
              >
                WordPress
              </span>
            </div>
            <p style={{ color: 'rgba(255,255,255,0.8)', fontSize: 12, margin: '4px 0 0', fontFamily: fonts.body }}>
              AHPRA-compliant forms. Generated in 60 seconds.
            </p>
          </div>
        </div>

        <a
          href="https://g-t-s.com.au"
          target="_blank"
          rel="noopener noreferrer"
          style={{ color: 'rgba(255,255,255,0.7)', fontSize: 11, textDecoration: 'none' }}
        >
          by Ganda Tech Services
        </a>
      </header>

      {/* Tab nav */}
      <nav
        style={{
          backgroundColor: colors.card,
          borderBottom: `1px solid ${colors.border}`,
          display: 'flex',
          padding: '0 24px',
        }}
      >
        {TABS.map(({ id, label }) => (
          <button
            key={id}
            onClick={() => setActiveTab(id)}
            style={{
              padding: '12px 16px',
              fontFamily: fonts.body,
              fontSize: 14,
              fontWeight: 500,
              cursor: 'pointer',
              background: 'none',
              border: 'none',
              borderBottom: activeTab === id ? `2px solid ${colors.primary}` : '2px solid transparent',
              color: activeTab === id ? colors.primary : colors.textSecondary,
              marginBottom: -1,
            }}
          >
            {label}
          </button>
        ))}
      </nav>

      {/* Content */}
      <main style={{ padding: 24, maxWidth: 900 }}>
        {activeTab === 'dashboard' && <DashboardTab isPro={isPro} />}
        {activeTab === 'forms'     && <FormsTab />}
        {activeTab === 'settings'  && <SettingsPanel />}
      </main>

      {/* Footer */}
      <footer
        style={{
          padding: '12px 24px',
          borderTop: `1px solid ${colors.border}`,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          marginTop: 24,
        }}
      >
        <span style={{ fontSize: 12, color: colors.textSecondary }}>
          FormIQ by{' '}
          <a
            href="https://g-t-s.com.au"
            target="_blank"
            rel="noopener noreferrer"
            style={{ color: colors.primary, textDecoration: 'none' }}
          >
            Ganda Tech Services
          </a>
        </span>
        <span style={{ fontSize: 12, color: colors.textSecondary }}>
          Need help?{' '}
          <a
            href="https://formiq.cchk.info"
            target="_blank"
            rel="noopener noreferrer"
            style={{ color: colors.primary, textDecoration: 'none' }}
          >
            formiq.cchk.info
          </a>
        </span>
      </footer>
    </div>
  );
}

function StatCard({ label, value, accent, planColor }: { label: string; value: string; accent?: boolean; planColor?: string }) {
  const accentColor = planColor ?? colors.primary;
  return (
    <div
      style={{
        padding: '20px 24px',
        borderRadius: 12,
        backgroundColor: colors.card,
        border: `1px solid ${accent ? accentColor : colors.border}`,
        borderLeft: accent ? `4px solid ${accentColor}` : `1px solid ${colors.border}`,
        boxShadow: '0 2px 8px rgba(0,0,0,0.05)',
      }}
    >
      <p style={{ fontSize: 13, color: colors.textSecondary, margin: '0 0 8px', fontFamily: fonts.body }}>
        {label}
      </p>
      <p style={{ fontSize: 28, fontWeight: 700, color: accent ? accentColor : colors.textPrimary, margin: 0, fontFamily: fonts.heading }}>
        {value}
      </p>
    </div>
  );
}

function DashboardTab({ isPro }: { isPro: boolean }) {
  const planLabel = isPro ? 'Pro' : 'Free';
  const planColor = isPro ? '#f59e0b' : colors.primary;
  const calloutBg = isPro ? '#fffbeb' : colors.purpleLight;
  const calloutBorder = isPro ? 'rgba(245,158,11,0.3)' : 'rgba(108,99,255,0.2)';

  return (
    <div>
      <div style={{ marginBottom: 24 }}>
        <h2 style={{ fontFamily: fonts.heading, fontWeight: 700, fontSize: 18, color: colors.textPrimary, margin: '0 0 4px' }}>
          Your forms are ready to build.
        </h2>
        <p style={{ fontSize: 14, color: colors.textSecondary, margin: 0 }}>
          Select your specialty. FormIQ generates a complete, AHPRA-compliant intake form in under 60 seconds.
        </p>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16, marginBottom: 24 }}>
        <StatCard label="Forms Generated" value="0" />
        <StatCard label="Documents Indexed" value="0" />
        <StatCard label="Current Plan" value={planLabel} accent planColor={planColor} />
      </div>

      <div
        style={{
          padding: 20,
          borderRadius: 12,
          backgroundColor: calloutBg,
          border: `1px solid ${calloutBorder}`,
          display: 'flex',
          alignItems: 'flex-start',
          gap: 16,
        }}
      >
        <div
          style={{
            width: 36,
            height: 36,
            borderRadius: 8,
            backgroundColor: planColor,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            flexShrink: 0,
            fontSize: 18,
          }}
        >
          {isPro ? '★' : '✦'}
        </div>
        <div>
          {isPro ? (
            <>
              <p style={{ fontWeight: 600, fontSize: 14, color: '#f59e0b', margin: '0 0 4px', fontFamily: fonts.heading }}>
                Pro Plan Active
              </p>
              <p style={{ fontSize: 13, color: colors.textSecondary, margin: 0 }}>
                You have <strong>unlimited form generation</strong>, priority AI processing, AHPRA compliance checks, and bulk export — all premium features unlocked.
              </p>
            </>
          ) : (
            <>
              <p style={{ fontWeight: 600, fontSize: 14, color: colors.primary, margin: '0 0 4px', fontFamily: fonts.heading }}>
                Generate your first form — free
              </p>
              <p style={{ fontSize: 13, color: colors.textSecondary, margin: 0 }}>
                Head to the <strong>Forms</strong> tab, select your specialty, and FormIQ builds a complete intake form tailored to your practice — no templates, no guesswork.
              </p>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

function SettingsPanel() {
  return (
    <div
      style={{
        padding: 32,
        borderRadius: 12,
        backgroundColor: colors.card,
        border: `1px solid ${colors.border}`,
        textAlign: 'center',
      }}
    >
      <div style={{ fontSize: 32, marginBottom: 12 }}>⚙️</div>
      <p style={{ fontWeight: 600, fontSize: 15, color: colors.textPrimary, margin: '0 0 6px', fontFamily: fonts.heading }}>
        Settings
      </p>
      <p style={{ fontSize: 13, color: colors.textSecondary, margin: 0 }}>
        Manage your API key, license, and account preferences.
      </p>
    </div>
  );
}
