"use client";

import { useMemo, useState } from 'react';
import Link from 'next/link';
import { AdminShell } from '../components/admin/admin-page.jsx';

const DEFAULT_INPUT = {
  businessName: 'Villa 515',
  city: 'Dubai / Jumeirah',
  market: 'luxury fragrance, workshops, hospitality, and gifting',
  website: 'https://villa515.example',
  description: 'Luxury Jumeirah niche perfumery destination with bespoke scent workshops, private dining, premium gifting, and WhatsApp concierge.',
  goals: ['marketing', 'concierge', 'events', 'commerce', 'website_qa', 'competitor_research', 'pr', 'creative_assets'],
  channels: ['website', 'whatsapp', 'instagram', 'google_calendar', 'image_generation'],
  autonomy: 'approval',
  briefingTime: '07:45',
};

const goalOptions = [
  ['marketing', 'Marketing'],
  ['concierge', 'Concierge'],
  ['events', 'Events'],
  ['commerce', 'Commerce'],
  ['website_qa', 'Website QA'],
  ['competitor_research', 'Competitors'],
  ['pr', 'PR'],
  ['creative_assets', 'Creative assets'],
];

const channelOptions = [
  ['website', 'Website'],
  ['whatsapp', 'WhatsApp'],
  ['instagram', 'Instagram'],
  ['google_calendar', 'Calendar'],
  ['image_generation', 'Image generation'],
  ['crm', 'CRM'],
];

function ToggleChips({ label, options, selected, onChange }) {
  function toggle(value) {
    const next = selected.includes(value) ? selected.filter(item => item !== value) : [...selected, value];
    onChange(next);
  }
  return (
    <div className="onboarding-field-block">
      <span>{label}</span>
      <div className="onboarding-chips">
        {options.map(([value, text]) => (
          <button key={value} type="button" className={selected.includes(value) ? 'selected' : ''} onClick={() => toggle(value)}>
            {text}
          </button>
        ))}
      </div>
    </div>
  );
}

export default function OnboardingPage() {
  const [form, setForm] = useState(DEFAULT_INPUT);
  const [blueprint, setBlueprint] = useState(null);
  const [busy, setBusy] = useState(false);
  const [launch, setLaunch] = useState(null);
  const [error, setError] = useState('');

  const preview = blueprint;
  const progress = useMemo(() => {
    const checks = [form.businessName, form.description, form.goals.length, form.channels.length, preview?.agents?.length, launch?.ok];
    return Math.round((checks.filter(Boolean).length / checks.length) * 100);
  }, [form, preview, launch]);

  function update(key, value) {
    setForm(current => ({ ...current, [key]: value }));
  }

  async function generateBlueprint() {
    setBusy(true);
    setError('');
    setLaunch(null);
    try {
      const res = await fetch('/api/onboarding/blueprint', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      });
      if (!res.ok) throw new Error(await res.text());
      setBlueprint(await res.json());
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setBusy(false);
    }
  }

  async function launchTeam() {
    setBusy(true);
    setError('');
    try {
      const res = await fetch('/api/onboarding/launch', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ blueprint: blueprint || form }),
      });
      if (!res.ok) throw new Error(await res.text());
      setLaunch(await res.json());
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setBusy(false);
    }
  }

  const headerActions = (
    <div className="onboarding-progress" aria-label="Onboarding progress">
      <b>{progress}%</b>
      <span>OS assembled</span>
      <i style={{ width: `${progress}%` }} />
    </div>
  );

  return (
    <AdminShell
      kicker="MADARX OS · ACCOUNT SETUP"
      title="AI onboarding wizard"
      description="Tell the onboarding agent what the business is. It designs the first AI operating system: agents, schedules, skills, memory, tools, and approval rules."
      actions={headerActions}
    >
      <div className="mkt-page" data-page="onboarding">
        {error ? <div className="onboarding-error">{error}</div> : null}

        <section className="onboarding-grid">
          <aside className="onboarding-panel onboarding-steps">
            <span className="panel-label">Sequence</span>
            {['Business', 'Goals', 'Tools', 'Autonomy', 'Blueprint', 'Launch'].map((step, index) => (
              <div key={step} className={`onboarding-step ${progress >= ((index + 1) / 6) * 100 ? 'done' : ''}`}>
                <b>{String(index + 1).padStart(2, '0')}</b>
                <span>{step}</span>
              </div>
            ))}
            <div className="voice-card">
              <span>Voice intelligence ready path</span>
              <p>gpt-realtime-2 for voice onboarding, gpt-realtime-translate for multilingual concierge, and gpt-realtime-whisper for word-level live command capture.</p>
            </div>
          </aside>

          <section className="onboarding-panel onboarding-conversation">
            <span className="panel-label">Onboarding AI Agent</span>
            <div className="agent-bubble">
              <b>I’ll build your AI team.</b>
              <p>Give me the business context. I’ll return a launchable operating-system blueprint with safe approval gates.</p>
            </div>

            <label>
              Business name
              <input value={form.businessName} onChange={event => update('businessName', event.target.value)} />
            </label>
            <label>
              City / market
              <input value={form.city} onChange={event => update('city', event.target.value)} />
            </label>
            <label>
              Website or landing page
              <input value={form.website} onChange={event => update('website', event.target.value)} />
            </label>
            <label>
              What does the business do?
              <textarea value={form.description} onChange={event => update('description', event.target.value)} rows={5} />
            </label>

            <ToggleChips label="Business goals" options={goalOptions} selected={form.goals} onChange={goals => update('goals', goals)} />
            <ToggleChips label="Channels / tools" options={channelOptions} selected={form.channels} onChange={channels => update('channels', channels)} />

            <div className="onboarding-field-block">
              <span>Autonomy mode</span>
              <div className="autonomy-grid">
                {[
                  ['safe', 'Safe', 'Drafts only'],
                  ['approval', 'Approval', 'Recommended'],
                  ['operator', 'Operator', 'Low-risk auto'],
                  ['full', 'Full', 'Later'],
                ].map(([value, label, note]) => (
                  <button key={value} type="button" className={form.autonomy === value ? 'selected' : ''} onClick={() => update('autonomy', value)}>
                    <b>{label}</b><small>{note}</small>
                  </button>
                ))}
              </div>
            </div>

            <div className="onboarding-actions">
              <button className="admin-button" type="button" onClick={generateBlueprint} disabled={busy}>
                {busy ? 'Thinking…' : 'Generate blueprint'}
              </button>
              <button className="admin-button secondary" type="button" onClick={() => { setForm(DEFAULT_INPUT); setBlueprint(null); setLaunch(null); }}>
                Villa515 sample
              </button>
            </div>
          </section>

          <section className="onboarding-panel blueprint-panel">
            <span className="panel-label">Live OS blueprint</span>
            {preview ? (
              <>
                <h2>{preview.business.name} AI team</h2>
                <p>{preview.summary}</p>
                <div className="blueprint-stats">
                  <div><b>{preview.agents.length}</b><span>agents</span></div>
                  <div><b>{preview.schedule_plan.length}</b><span>schedules</span></div>
                  <div><b>{preview.tool_plan.reduce((sum, item) => sum + item.tools.length, 0)}</b><span>tool links</span></div>
                </div>
                <div className="agent-blueprint-list">
                  {preview.agents.map(agent => (
                    <article key={agent.id}>
                      <div>
                        <b>{agent.name}</b>
                        <span>{agent.schedule} · {agent.engine}/{agent.model}</span>
                      </div>
                      <p>{agent.mission}</p>
                    </article>
                  ))}
                </div>
                <div className="voice-opportunities">
                  {preview.voice_opportunities.map(item => (
                    <div key={item.model}>
                      <b>{item.model}</b>
                      <span>{item.title}</span>
                    </div>
                  ))}
                </div>
                <div className="onboarding-actions sticky-actions">
                  <button className="admin-button mars" type="button" onClick={launchTeam} disabled={busy}>
                    {busy ? 'Launching…' : 'Create my AI team'}
                  </button>
                </div>
              </>
            ) : (
              <div className="blueprint-empty">
                <b>No blueprint yet.</b>
                <p>Generate the blueprint to preview the AI agents, schedules, tools, voice opportunities, and approval policy.</p>
              </div>
            )}

            {launch?.ok ? (
              <div className="launch-result">
                <b>AI team created.</b>
                <p>{launch.created_agents.length} agents and {launch.schedules.length} schedules are now live.</p>
                <div>
                  <Link className="admin-button" href="/agents">View agents</Link>
                  <Link className="admin-button secondary" href="/schedules">View schedules</Link>
                </div>
              </div>
            ) : null}
          </section>
        </section>
      </div>
    </AdminShell>
  );
}
