import React, { useState } from 'react';
import { CheckCircle2, Shield, Trash2 } from 'lucide-react';
import Panel from '@/components/scanforge/Panel';
import { useScanner } from '@/context/ScannerContext';
import { appConfig } from '@/lib/appConfig';

export default function BridgeSettings() {
  const { bridgeUrl, saveUrl, status, scanState, bridgeClient, test, reconnect, demo, setDemo } = useScanner();
  const [url, setUrl] = useState(bridgeUrl);
  const [code, setCode] = useState('');
  const [message, setMessage] = useState('');
  const moduleMode = appConfig.mode === 'SHIRE_MODULE';

  const pair = async () => {
    setMessage('Pairing…');
    try {
      const result = await bridgeClient.pair(code);
      if (result?.credential) bridgeClient.setCredential(result.credential);
      setCode('');
      setMessage('Scanner paired. Test the depth stream before scanning.');
    } catch {
      setMessage('Pairing rejected. Check the one-time code shown by SHiRE Scan Bridge.');
    }
  };

  const testNow = () => test().then(() => setMessage('ScanForge Agent responded. Device and stream checks complete.')).catch(() => setMessage('SCANFORGE AGENT OFFLINE — confirm the agent and local bridge services are running.'));

  return (
    <div className="mx-auto max-w-5xl space-y-5">
      <div><p className="text-xs uppercase tracking-[.28em] text-purple-300">Local scanner</p><h2 className="mt-2 text-3xl font-semibold">Scanner Bridge</h2></div>
      <div className={`rounded-2xl border p-4 font-semibold tracking-[.12em] ${status === 'offline' ? 'border-red-500/30 bg-red-500/[.07] text-red-300' : 'border-[#7dff72]/25 bg-[#7dff72]/5 text-[#b4ffad]'}`}>{status === 'offline' ? 'SCANFORGE AGENT OFFLINE' : `BRIDGE ${scanState.bridgeState.toUpperCase()}`}</div>
      {moduleMode ? (
        <Panel title="Managed by SHiRE" eyebrow="Native Agents integration">
          <p className="text-sm leading-6 text-zinc-400">In SHiRE module mode, browser controls communicate with the authenticated ScanForge Agent. The agent owns bridge credentials, Kinect access and local filesystem operations.</p>
          <div className="mt-5 flex flex-wrap gap-3"><button onClick={testNow} className="rounded-xl border border-white/15 px-5 py-3 text-sm">Run Scanner Test</button><button onClick={() => reconnect().then(() => setMessage('ScanForge Agent restarted.')).catch(() => setMessage('Agent restart failed.'))} className="rounded-xl border border-purple-400/30 px-5 py-3 text-sm">Restart ScanForge Agent</button></div>
          {message && <p className="mt-3 text-sm text-zinc-300">{message}</p>}
        </Panel>
      ) : (
        <Panel title="Connect SHiRE Mini" eyebrow="Secure local connection">
          <ol className="mb-6 space-y-2 text-sm text-zinc-400"><li>1. Connect Kinect v1 USB and its power adapter to SHiRE Mini.</li><li>2. Start SHiRE Scan Bridge and confirm it displays a one-time pairing code.</li><li>3. Trust the bridge’s local HTTPS certificate on this device.</li><li>4. Enter the secure URL and pairing code, then test the connection.</li></ol>
          <label className="text-xs text-zinc-500">Bridge URL or optional Tailscale hostname/IP</label>
          <div className="mt-2 flex flex-col gap-2 sm:flex-row"><input value={url} onChange={(event) => setUrl(event.target.value)} className="flex-1 rounded-xl border border-white/10 bg-black/40 px-4 py-3 text-sm outline-none focus:border-purple-400"/><button onClick={() => saveUrl(url)} className="rounded-xl border border-white/15 px-4 py-3 text-sm">Save URL</button></div>
          <div className="mt-3 flex flex-col gap-2 sm:flex-row"><input type="password" value={code} onChange={(event) => setCode(event.target.value)} placeholder="Pairing code" className="flex-1 rounded-xl border border-white/10 bg-black/40 px-4 py-3 text-sm"/><button onClick={pair} disabled={!code} className="rounded-xl bg-[#7dff72] px-5 py-3 text-sm font-bold text-black disabled:opacity-30">Pair Scanner</button><button onClick={testNow} className="rounded-xl border border-purple-400/30 px-5 py-3 text-sm">Test Connection</button></div>
          {message && <p className="mt-3 text-sm text-zinc-300">{message}</p>}
        </Panel>
      )}
      <div className="grid gap-5 md:grid-cols-2">
        <Panel title="Connection details">
          <dl className="space-y-3 text-sm">{[
            ['Agent state', scanState.agentState], ['Bridge state', scanState.bridgeState], ['Kinect state', scanState.kinectState], ['Capabilities', scanState.capabilities ? 'Reported' : 'Awaiting agent']
          ].map(([name, value]) => <div className="flex justify-between gap-4" key={name}><dt className="text-zinc-500">{name}</dt><dd className="capitalize">{String(value).replaceAll('_', ' ')}</dd></div>)}</dl>
          {!moduleMode && <button onClick={() => { bridgeClient.forget(); setMessage('Pairing credential removed from this browser session.'); }} className="mt-5 flex items-center gap-2 text-sm text-red-300"><Trash2 size={15}/>Forget Scanner</button>}
        </Panel>
        <Panel title="Local processing">
          <p className="flex items-center gap-2 text-[#7dff72]"><CheckCircle2 size={18}/>Raw capture stays on SHiRE Mini</p>
          <p className="mt-3 text-sm leading-6 text-zinc-400">Raw Kinect images and depth data remain on the paired SHiRE scanner unless you deliberately choose to export or upload them.</p>
          <div className="mt-5 flex items-center justify-between rounded-xl border border-purple-400/20 bg-purple-400/5 p-3"><span className="text-sm"><Shield size={16} className="mr-2 inline"/>DEMO SCANNER MODE</span><button onClick={() => setDemo(!demo)} className={`rounded-full px-3 py-1 text-xs ${demo ? 'bg-purple-500 text-white' : 'bg-zinc-800 text-zinc-400'}`}>{demo ? 'Enabled' : 'Disabled'}</button></div>
          <p className="mt-2 text-xs text-zinc-500">Demo mode is manual, visibly watermarked and cannot produce real-scan exports.</p>
        </Panel>
      </div>
    </div>
  );
}
