import { useEffect, useState } from 'react';
import { Save, HardDrive, Server, Sparkles, SlidersHorizontal } from 'lucide-react';
import { base44 } from '@/api/base44Client';
import { useExperienceMode } from '@/lib/ExperienceMode';
import PageHeader from '@/components/app/PageHeader';
import StatusBadge from '@/components/app/StatusBadge';
import { storageAdapter } from '@/lib/storageAdapter';

const defaults = {
  geometryServiceUrl: 'https://geometry.shire.example/v1', geometryServiceAuth: 'none', healthCheckEndpoint: '/health',
  maxUploadSize: 50, defaultEmbossHeight: 1.2, defaultEngravingDepth: 0.8, minimumFeatureSize: 0.6, minimumWallThickness: 2,
  geometryServiceStatus: 'simulation_only', shireVaultStatus: 'not_connected', shireVaultPath: '/SHiRELimbs', shireVaultWritable: false,
  aiConceptServiceUrl: 'built-in InvokeLLM', defaultStorageType: 'prototype', allowedFileFormats: ['stl', 'obj', 'glb', 'png', 'jpg', 'jpeg', 'webp', 'svg']
};

export default function Settings() {
  const [s, setS] = useState(defaults);
  const [id, setId] = useState(null);
  const [saved, setSaved] = useState(false);
  const { mode, setMode } = useExperienceMode();
  const [user, setUser] = useState(null);

  useEffect(() => {
    base44.entities.SystemSettings.list(null, 1)
      .then(x => { const safe = Array.isArray(x) ? x : []; if (safe[0]) { setS({ ...defaults, ...safe[0] }); setId(safe[0].id); } })
      .catch(() => {});
    base44.auth.me().then(setUser).catch(() => setUser(null));
  }, []);

  const setPref = async (key, value) => {
    setUser(u => ({ ...(u || {}), [key]: value }));
    try { await base44.auth.updateMe({ [key]: value }); setSaved(true); setTimeout(() => setSaved(false), 1500); } catch { /* non-fatal */ }
  };

  const save = async () => {
    const next = id ? await base44.entities.SystemSettings.update(id, s) : await base44.entities.SystemSettings.create(s);
    setId(next.id);
    setSaved(true);
    setTimeout(() => setSaved(false), 1500);
  };
  const v = storageAdapter.verifyFinalStorage(s);

  return (
    <>
      <PageHeader eyebrow="Systems" title="Settings" description="Choose your experience, then configure the LimbForge Geometry Engine, SHiREVault storage and manufacturing defaults." />
      <section className="panel mb-5">
        <h2 className="section-title">Experience</h2>
        <div className="grid gap-3 sm:grid-cols-2">
          <button onClick={() => setMode('guided')} className={`rounded-xl border p-4 text-left transition ${mode === 'guided' ? 'border-cyan-400/50 bg-cyan-400/[0.08]' : 'border-white/10 bg-white/[0.02] hover:border-white/25'}`}>
            <span className="mb-1 inline-flex items-center gap-1.5 rounded-full border border-cyan-400/40 bg-cyan-400/10 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wider text-cyan-200">Recommended</span>
            <span className="mt-2 block text-sm font-semibold text-white">Guided Mode</span>
            <span className="mt-1 block text-xs leading-5 text-slate-400">Simple step-by-step experience for most users.</span>
          </button>
          <button onClick={() => setMode('advanced')} className={`rounded-xl border p-4 text-left transition ${mode === 'advanced' ? 'border-violet-400/50 bg-violet-400/[0.08]' : 'border-white/10 bg-white/[0.02] hover:border-white/25'}`}>
            <span className="mb-1 inline-flex items-center gap-1.5 rounded-full border border-violet-400/40 bg-violet-400/10 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wider text-violet-200">Advanced</span>
            <span className="mt-2 block text-sm font-semibold text-white">Advanced Mode</span>
            <span className="mt-1 block text-xs leading-5 text-slate-400">Full professional design controls.</span>
          </button>
        </div>
        <div className="mt-4 grid gap-4 sm:grid-cols-3">
          <label className="form-label">Graphics quality
            <select className="field" value={user?.preferredGraphicsQuality || 'auto'} onChange={e => setPref('preferredGraphicsQuality', e.target.value)}>
              <option value="auto">Auto</option><option value="high">High</option><option value="balanced">Balanced</option><option value="basic">Basic</option>
            </select>
          </label>
          <label className="mt-2 flex items-center gap-3 text-sm text-slate-300"><input type="checkbox" checked={!!user?.reducedMotion} onChange={e => setPref('reducedMotion', e.target.checked)} className="h-5 w-5 accent-cyan-400" />Reduced motion</label>
          <label className="mt-2 flex items-center gap-3 text-sm text-slate-300"><input type="checkbox" checked={!!user?.highContrast} onChange={e => setPref('highContrast', e.target.checked)} className="h-5 w-5 accent-cyan-400" />High contrast</label>
        </div>
      </section>
      <div className="grid gap-5 xl:grid-cols-2">
        <section className="panel">
          <h2 className="section-title"><Server size={18} />Geometry service</h2>
          <label className="form-label">Geometry service URL<input className="field" value={s.geometryServiceUrl} onChange={e => setS({ ...s, geometryServiceUrl: e.target.value })} /></label>
          <label className="form-label">Authentication<select className="field" value={s.geometryServiceAuth} onChange={e => setS({ ...s, geometryServiceAuth: e.target.value })}><option value="none">None</option><option value="api_key">API key</option><option value="oauth">OAuth</option></select></label>
          <label className="form-label">Health-check endpoint<input className="field" value={s.healthCheckEndpoint} onChange={e => setS({ ...s, healthCheckEndpoint: e.target.value })} /></label>
          <div className="readout"><span className="readout-label">Service status</span><StatusBadge status={s.geometryServiceStatus} /></div>
        </section>
        <section className="panel">
          <h2 className="section-title"><HardDrive size={18} />SHiREVault final storage</h2>
          <label className="form-label">Required case-sensitive path<input className="field mono" value={s.shireVaultPath} onChange={e => setS({ ...s, shireVaultPath: e.target.value })} /></label>
          <div className="readout"><span className="readout-label">Network mount</span><StatusBadge status={s.shireVaultStatus} /></div>
          <label className="mt-4 flex items-center gap-3 text-sm text-slate-300"><input type="checkbox" checked={s.shireVaultWritable} onChange={e => setS({ ...s, shireVaultWritable: e.target.checked })} className="h-5 w-5 accent-cyan-400" />Verified writable by deployment adapter</label>
          {(!v.mounted || !v.writable || !v.pathValid) && <p className="warning-box mt-4">Final processing and export are blocked. Temporary Base44 files are prototype storage only; there is no local final-output fallback.</p>}
        </section>
        <section className="panel">
          <h2 className="section-title"><Sparkles size={18} className="text-violet-300" />AI concept service</h2>
          <label className="form-label">Concept generation service<input className="field" value={s.aiConceptServiceUrl} onChange={e => setS({ ...s, aiConceptServiceUrl: e.target.value })} /></label>
          <p className="text-xs text-slate-500">PromptForge concept text uses the built-in InvokeLLM integration; preview images use GenerateImage (integration credits).</p>
        </section>
        <section className="panel">
          <h2 className="section-title">Storage & formats</h2>
          <label className="form-label">Default project storage<select className="field" value={s.defaultStorageType} onChange={e => setS({ ...s, defaultStorageType: e.target.value })}><option value="prototype">Prototype (Base44-hosted)</option><option value="shirevault">SHiREVault</option></select></label>
          <label className="form-label">Allowed file formats<input className="field mono" value={(s.allowedFileFormats || []).join(', ')} onChange={e => setS({ ...s, allowedFileFormats: e.target.value.split(',').map(x => x.trim()).filter(Boolean) })} /></label>
        </section>
        <section className="panel xl:col-span-2">
          <h2 className="section-title"><SlidersHorizontal size={18} />Manufacturing defaults</h2>
          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
            {[['maxUploadSize', 'Maximum upload (MB)'], ['defaultEmbossHeight', 'Emboss height (mm)'], ['defaultEngravingDepth', 'Engraving depth (mm)'], ['minimumFeatureSize', 'Minimum feature (mm)'], ['minimumWallThickness', 'Minimum wall (mm)']].map(([k, label]) => (
              <label className="form-label" key={k}>{label}<input type="number" step="0.1" className="field" value={s[k]} onChange={e => setS({ ...s, [k]: Number(e.target.value) })} /></label>
            ))}
          </div>
        </section>
      </div>
      <div className="mt-5 flex justify-end"><button onClick={save} className="btn-primary"><Save size={17} />{saved ? 'Saved' : 'Save settings'}</button></div>
    </>
  );
}