import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { scanPath } from '@/lib/appConfig';
import WizardStep from '@/components/scanforge/WizardStep';
import { useShireModule } from '@/context/ShireModuleContext';
import { createProject } from '@/services/projectRepository';

const input = 'w-full rounded-xl border border-white/10 bg-black/30 px-4 py-3 text-sm';
const safety = [
  'The scan is not being used as certified medical geometry',
  'Critical measurements will be manually checked',
  'The area is clear of trip hazards',
  'The Kinect and cables are secure'
];

export default function NewScan() {
  const navigate = useNavigate();
  const shire = useShireModule();
  const [form, setForm] = useState({
    project_name: '', description: '', scan_mode: 'object_orbit', object_category: 'Household object',
    intended_use: 'Shape reference', privacy_level: 'Local only', size: 'medium', target: 'Printable mesh', scale: 'Calibration board'
  });
  const [checks, setChecks] = useState([]);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState('');
  const update = (event) => setForm({ ...form, [event.target.name]: event.target.value });

  const submit = async () => {
    setBusy(true);
    setError('');
    try {
      const project = await createProject({ shireClient: shire?.client, project: form, safetyStatements: safety });
      navigate(`${scanPath('capture')}?projectId=${encodeURIComponent(project.id)}`);
    } catch (reason) {
      setError(reason?.message || 'Project creation failed');
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="mx-auto max-w-4xl space-y-4">
      <div><p className="text-xs uppercase tracking-[.28em] text-purple-300">Guided setup</p><h2 className="mt-2 text-3xl font-semibold">New Scan</h2></div>
      {error && <div className="rounded-xl border border-red-500/30 bg-red-500/10 p-3 text-sm text-red-200">{error}</div>}
      <WizardStep step="1" title="Project details">
        <div className="grid gap-3 sm:grid-cols-2">
          <input name="project_name" value={form.project_name} onChange={update} placeholder="Project name" className={input}/>
          <select name="scan_mode" value={form.scan_mode} onChange={update} className={input}><option value="object_orbit">Object Orbit</option><option value="turntable">Turntable</option><option value="large_object">Large Object</option><option value="prosthetic_cover_reference">Prosthetic Cover Reference</option></select>
          <input name="description" value={form.description} onChange={update} placeholder="Description" className={input}/>
          <input name="object_category" value={form.object_category} onChange={update} placeholder="Object category" className={input}/>
          <select name="intended_use" value={form.intended_use} onChange={update} className={input}><option>Shape reference</option><option>Editable point cloud</option><option>Printable mesh</option><option>Cosmetic cover reference</option><option>Replacement-part reference</option><option>Archive only</option></select>
          <select name="privacy_level" value={form.privacy_level} onChange={update} className={input}><option>Local only</option><option>Private project</option><option>Approved shared project</option></select>
        </div>
      </WizardStep>
      <WizardStep step="2–4" title="Size, target output and scale">
        <div className="grid gap-3 sm:grid-cols-3">
          <select name="size" value={form.size} onChange={update} className={input}><option value="small">Small</option><option value="medium">Medium</option><option value="large">Large</option><option value="custom">Custom dimensions</option></select>
          <select name="target" value={form.target} onChange={update} className={input}><option>Shape reference</option><option>Editable point cloud</option><option>Printable mesh</option><option>Cosmetic cover reference</option><option>Replacement-part reference</option><option>Archive only</option></select>
          <select name="scale" value={form.scale} onChange={update} className={input}><option>Calibration board</option><option>Known-size cube</option><option>Known measured distance</option><option>Manual dimension after scanning</option><option>Unscaled reference scan</option></select>
        </div>
      </WizardStep>
      <WizardStep step="5" title="Background setup"><div className="grid gap-2 text-sm text-zinc-400 sm:grid-cols-2">{['Use a clear background','Choose non-reflective surfaces','Keep lighting stable','Avoid sunlight on the infrared sensor','Avoid transparent or highly reflective objects','Keep people out of the capture area'].map((item) => <p key={item}>• {item}</p>)}</div></WizardStep>
      <WizardStep step="6" title="Safety confirmation">
        <div className="space-y-3">{safety.map((item) => <label key={item} className="flex gap-3 text-sm text-zinc-300"><input type="checkbox" checked={checks.includes(item)} onChange={() => setChecks(checks.includes(item) ? checks.filter((value) => value !== item) : [...checks, item])}/>{item}</label>)}</div>
        <p className="mt-5 rounded-xl border border-amber-400/20 bg-amber-400/5 p-3 text-sm text-amber-200">Kinect scans are suitable for shape reference, visualisation and non-load-bearing design work. Confirm all critical measurements manually before printing.</p>
      </WizardStep>
      <button onClick={submit} disabled={busy || !form.project_name || checks.length !== safety.length} className="w-full rounded-xl bg-[#7dff72] py-4 font-bold text-black disabled:opacity-30">{busy ? 'Creating through ScanForge Agent…' : 'Confirm and open Live Capture'}</button>
    </div>
  );
}
