import { useState } from 'react';
import { Link } from 'react-router-dom';
import { base44 } from '@/api/base44Client';
import { CheckCircle2, ShieldAlert, ArrowRight, ArrowLeft, Send, Heart, User, Ruler, Camera, Palette, DollarSign, ClipboardCheck } from 'lucide-react';

function uuid() { return (crypto.randomUUID && crypto.randomUUID()) || 'id-' + Math.random().toString(36).slice(2); }
const today = () => new Date().toISOString().slice(0, 10);

const STEPS = [
  { id: 'welcome', title: 'Welcome', icon: Heart },
  { id: 'about', title: 'About You', icon: User },
  { id: 'limb', title: 'Your Limb', icon: User },
  { id: 'prosthesis', title: 'Prosthesis Type', icon: User },
  { id: 'component', title: 'Component', icon: Camera },
  { id: 'measure', title: 'Measurements', icon: Ruler },
  { id: 'sensitive', title: 'Sensitive Areas', icon: ShieldAlert },
  { id: 'design', title: 'Design', icon: Palette },
  { id: 'funding', title: 'Funding', icon: DollarSign },
  { id: 'review', title: 'Review & Submit', icon: ClipboardCheck },
];

const SAFETY = 'SHiRE prosthetic covers are non-load-bearing cosmetic covers only. They are not part of the prosthesis, must not support body weight, alter alignment, obstruct movement or replace any prosthetic component. Manual workshop review is required before manufacturing.';

const initialForm = {
  existingCustomer: 'no', refCode: '',
  full_name: '', email: '', phone: '', postcode: '', contact_method: 'Email',
  limb: 'Leg', side: 'Left', level: 'Below-knee',
  prosthesisType: 'Socket',
  manufacturer: '', model: '', photos: [],
  measurements: { coverLength: '', calfWidth: '', ankleWidth: '', footLength: '', footWidth: '' },
  sensitive: { scars: false, raised: false, pinch: false, pain: false, skinfold: false, noTouch: false, changes: false, notes: '' },
  design: { style: 'Elegant anatomical', colour: 'SHiRE Purple', secondary: 'Bright Green', finish: 'Matte', vents: 'Standard', text: '', notes: '' },
  ossiguard: { use: 'Unsure', version: '', photo: '', prevCover: '', note: '' },
  funding: 'Pay privately',
  declarations: false,
};

export default function DesignYourCover() {
  const [step, setStep] = useState(0);
  const [form, setForm] = useState(initialForm);
  const [submitting, setSubmitting] = useState(false);
  const [result, setResult] = useState(null);
  const [error, setError] = useState('');
  const set = (patch) => setForm((f) => ({ ...f, ...patch }));

  const next = () => setStep((s) => Math.min(s + 1, STEPS.length - 1));
  const back = () => setStep((s) => Math.max(s - 1, 0));

  const submit = async () => {
    if (!form.declarations) { setError('Please acknowledge the declarations before submitting.'); return; }
    setSubmitting(true); setError('');
    try {
      // All record creation, validation and rate-limiting happen server-side;
      // the client sends form data only — no direct database writes from the browser.
      const res = await base44.functions.invoke('submitPublicIntake', { form });
      if (res.data?.error) { setError(res.data.error); return; }
      setResult({ intakeRef: res.data?.intakeRef, customer: { full_name: res.data?.customerName || form.full_name } });
    } catch (e) {
      setError(e && e.message ? e.message : 'Could not submit your request. Please try again.');
    } finally {
      setSubmitting(false);
    }
  };

  if (result) {
    return (
      <div className="min-h-screen bg-workshop flex items-center justify-center p-6">
        <div className="panel max-w-lg space-y-4 p-8 text-center">
          <CheckCircle2 className="mx-auto h-12 w-12 text-emerald-400" />
          <h1 className="text-xl font-semibold text-white">Request received</h1>
          <p className="text-sm text-slate-300">Thank you, {result.customer.full_name}. Your SHiRE cover request <span className="font-semibold text-violet-300">{result.intakeRef}</span> has been submitted to the workshop for review.</p>
          <p className="text-xs text-slate-500">Manufacturing has not started. A SHiRE team member will contact you via {form.contact_method.toLowerCase()} to verify measurements and confirm your design. No payment has been taken.</p>
          <div className="rounded-lg border border-amber-400/30 bg-amber-400/5 px-4 py-3 text-left text-xs text-amber-200">{SAFETY}</div>
          <button onClick={() => { setResult(null); setForm(initialForm); setStep(0); }} className="btn-primary w-full">Start another request</button>
        </div>
      </div>
    );
  }

  const Step = STEPS[step];
  const Icon = Step.icon;

  return (
    <div className="min-h-screen bg-workshop">
      <header className="border-b border-shire-border px-6 py-4">
        <div className="mx-auto max-w-3xl">
          <h1 className="text-lg font-semibold text-white">Design Your SHiRE Prosthetic Cover</h1>
          <p className="text-xs text-slate-500">A cosmetic, non-load-bearing cover — workshop review required before manufacturing.</p>
        </div>
      </header>

      <div className="mx-auto max-w-3xl px-6 py-6">
        <div className="mb-6 flex flex-wrap items-center gap-1.5">
          {STEPS.map((s, i) => (
            <div key={s.id} className={`flex items-center gap-1.5 text-[11px] font-medium ${i === step ? 'text-violet-300' : i < step ? 'text-emerald-400' : 'text-slate-600'}`}>
              <span className={`flex h-5 w-5 items-center justify-center rounded-full border ${i === step ? 'border-violet-400 bg-violet-400/10' : i < step ? 'border-emerald-400 bg-emerald-400/10' : 'border-slate-600'}`}>{i < step ? '✓' : i + 1}</span>
              <span className="hidden sm:inline">{s.title}</span>
              {i < STEPS.length - 1 && <span className="mx-1 h-px w-4 bg-slate-700" />}
            </div>
          ))}
        </div>

        <div className="panel p-6">
          <div className="mb-4 flex items-center gap-2">
            <Icon className="h-5 w-5 text-violet-300" />
            <h2 className="text-base font-semibold text-white">{Step.title}</h2>
          </div>

          {step === 0 && (
            <div className="space-y-4">
              <p className="text-sm text-slate-300">A SHiRE cover is a cosmetic shell that sits over your prosthesis. It does not support your weight or change how your prosthesis works. We'll guide you through a few simple questions — you can save and return later.</p>
              <div className="rounded-lg border border-amber-400/30 bg-amber-400/5 px-4 py-3 text-xs text-amber-200">{SAFETY}</div>
              <div className="flex gap-2">
                <button onClick={next} className="btn-primary"><ArrowRight className="h-4 w-4" />Start New Request</button>
              </div>
            </div>
          )}

          {step === 1 && (
            <div className="space-y-3">
              <Radio label="Are you an existing SHiRE customer?" value={form.existingCustomer} options={['no', 'yes']} onChange={(v) => set({ existingCustomer: v })} />
              {form.existingCustomer === 'yes' && <TextInput label="Private reference code (optional)" value={form.refCode} onChange={(v) => set({ refCode: v })} placeholder="We'll verify privately — never expose your records" />}
              <TextInput label="Full name" value={form.full_name} onChange={(v) => set({ full_name: v })} />
              <TextInput label="Email" type="email" value={form.email} onChange={(v) => set({ email: v })} />
              <TextInput label="Phone" value={form.phone} onChange={(v) => set({ phone: v })} />
              <TextInput label="Shipping postcode" value={form.postcode} onChange={(v) => set({ postcode: v })} />
              <Select label="Preferred contact method" value={form.contact_method} options={['Email', 'Phone', 'SMS']} onChange={(v) => set({ contact_method: v })} />
              <NavRow onBack={back} onNext={next} canNext={!!form.full_name && !!form.email} />
            </div>
          )}

          {step === 2 && (
            <div className="space-y-3">
              <Radio label="Limb" value={form.limb} options={['Leg', 'Arm']} onChange={(v) => set({ limb: v })} />
              <Radio label="Side" value={form.side} options={['Left', 'Right']} onChange={(v) => set({ side: v })} />
              <Select label="Level" value={form.level} options={['Below-knee', 'Above-knee', 'Below-elbow', 'Above-elbow', 'Other']} onChange={(v) => set({ level: v })} />
              <NavRow onBack={back} onNext={next} />
            </div>
          )}

          {step === 3 && (
            <div className="space-y-3">
              <Radio label="How does your prosthesis attach?" value={form.prosthesisType} options={['Socket', 'Osseointegration', 'Unsure']} onChange={(v) => set({ prosthesisType: v })} />
              <p className="text-xs text-slate-500">Socket: your limb sits inside a socket. Osseointegration: a direct connector through the skin. Unsure is fine — we'll help.</p>
              <NavRow onBack={back} onNext={next} />
            </div>
          )}

          {step === 4 && (
            <div className="space-y-4">
              <div className="space-y-3">
                <TextInput label="Manufacturer (e.g. Ottoback, Össur)" value={form.manufacturer} onChange={(v) => set({ manufacturer: v })} placeholder="If known" />
                <TextInput label="Model" value={form.model} onChange={(v) => set({ model: v })} placeholder="If known" />
                <p className="text-xs text-slate-500">Upload a clear photo of the label on your prosthesis if you can — this helps us identify exact parts. You don't need to know article numbers.</p>
              </div>
              <div className="rounded-lg border border-shire-border bg-shire-raised px-4 py-4 space-y-3">
                <Radio label="Does your prosthesis already use a SHiRE Ossiguard connector?" value={form.ossiguard.use} options={['Yes', 'No', 'Unsure']} onChange={(v) => set({ ossiguard: { ...form.ossiguard, use: v } })} />
                {form.ossiguard.use === 'Yes' && (
                  <div className="space-y-3">
                    <TextInput label="Version if known" value={form.ossiguard.version} onChange={(v) => set({ ossiguard: { ...form.ossiguard, version: v } })} placeholder="e.g. v2" />
                    <TextInput label="Previous cover reference if known" value={form.ossiguard.prevCover} onChange={(v) => set({ ossiguard: { ...form.ossiguard, prevCover: v } })} placeholder="Optional" />
                    <TextInput label="Note about your connector" value={form.ossiguard.note} onChange={(v) => set({ ossiguard: { ...form.ossiguard, note: v } })} placeholder="Anything helpful" />
                    <p className="text-xs text-emerald-300">If you're a securely matched returning customer, the workshop may reuse your approved Ossiguard fit — we'll verify this privately.</p>
                  </div>
                )}
                {(form.ossiguard.use === 'No' || form.ossiguard.use === 'Unsure') && (
                  <p className="text-xs text-amber-200">No problem — the workshop will review Ossiguard compatibility. We do not promise compatibility until verified.</p>
                )}
              </div>
              <NavRow onBack={back} onNext={next} />
            </div>
          )}

          {step === 5 && (
            <div className="space-y-3">
              <p className="text-xs text-slate-500">Enter what you can — estimates are fine. We'll verify everything before manufacturing. All measurements in millimetres.</p>
              {[
                ['coverLength', 'Cover overall length (mm)'],
                ['calfWidth', 'Widest calf width (mm)'],
                ['ankleWidth', 'Ankle width (mm)'],
                ['footLength', 'Foot length (mm)'],
                ['footWidth', 'Foot width (mm)'],
              ].map(([k, label]) => (
                <TextInput key={k} label={label} type="number" value={form.measurements[k]} onChange={(v) => set({ measurements: { ...form.measurements, [k]: v } })} />
              ))}
              <NavRow onBack={back} onNext={next} />
            </div>
          )}

          {step === 6 && (
            <div className="space-y-3">
              <p className="text-sm text-slate-300">Tick anything that applies to the area where the cover will sit:</p>
              {[
                ['scars', 'Scars'], ['raised', 'Raised closure areas'], ['pinch', 'Pinch spots'],
                ['pain', 'Painful contact areas'], ['skinfold', 'Skin folds'], ['noTouch', 'Areas that must not be touched'], ['changes', 'Areas that change when sitting or bending'],
              ].map(([k, label]) => (
                <label key={k} className="choice-card">
                  <input type="checkbox" checked={form.sensitive[k]} onChange={(e) => set({ sensitive: { ...form.sensitive, [k]: e.target.checked } })} />
                  <span>{label}</span>
                </label>
              ))}
              <textarea placeholder="Notes about sensitive areas" value={form.sensitive.notes} onChange={(e) => set({ sensitive: { ...form.sensitive, notes: e.target.value } })} className="workshop-input min-h-16" />
              <div className="rounded-lg border border-red-400/30 bg-red-400/5 px-4 py-3 text-xs text-red-300">Do not continue if there is an active wound, infection or unhealed area. Seek advice from your prosthetist or health professional.</div>
              <NavRow onBack={back} onNext={next} />
            </div>
          )}

          {step === 7 && (
            <div className="space-y-3">
              <Select label="Style" value={form.design.style} options={['Minimal', 'Elegant anatomical', 'Gothic', 'Biomechanical', 'Cybernetic', 'Industrial', 'Skeletal', 'Organic', 'Geometric', 'Futuristic', 'Floral', 'Child friendly']} onChange={(v) => set({ design: { ...form.design, style: v } })} />
              <Select label="Main colour" value={form.design.colour} options={['SHiRE Purple', 'Deep Purple', 'Black', 'White', 'Bright Green']} onChange={(v) => set({ design: { ...form.design, colour: v } })} />
              <Select label="Secondary colour" value={form.design.secondary} options={['Bright Green', 'SHiRE Purple', 'Black', 'White']} onChange={(v) => set({ design: { ...form.design, secondary: v } })} />
              <Select label="Finish" value={form.design.finish} options={['Matte', 'Satin']} onChange={(v) => set({ design: { ...form.design, finish: v } })} />
              <Select label="Ventilation" value={form.design.vents} options={['Minimal', 'Standard', 'High']} onChange={(v) => set({ design: { ...form.design, vents: v } })} />
              <TextInput label="Personal text (optional)" value={form.design.text} onChange={(v) => set({ design: { ...form.design, text: v } })} />
              <textarea label="Design notes" placeholder="Anything you'd like us to know" value={form.design.notes} onChange={(e) => set({ design: { ...form.design, notes: e.target.value } })} className="workshop-input min-h-16" />
              <p className="text-xs text-emerald-300">SHiRE branding is always included — it can't be removed.</p>
              <NavRow onBack={back} onNext={next} />
            </div>
          )}

          {step === 8 && (
            <div className="space-y-3">
              <Radio label="Funding / payment pathway" value={form.funding} options={['Pay privately', 'Self-managed NDIS', 'Plan-managed NDIS', 'NDIA-managed', 'Request quote only', 'Unsure']} onChange={(v) => set({ funding: v })} />
              <div className="rounded-lg border border-shire-border bg-shire-raised px-4 py-3 text-xs text-slate-400">NDIS funding may be available depending on the participant's plan, goals, evidence, funding management and approval. Manufacturing will not begin until payment or written approval is received. We do not promise NDIS approval.</div>
              <NavRow onBack={back} onNext={next} />
            </div>
          )}

          {step === 9 && (
            <div className="space-y-4">
              <div className="space-y-1 text-sm text-slate-200">
                <Row k="Limb" v={`${form.side} ${form.level} ${form.limb}`} />
                <Row k="Prosthesis type" v={form.prosthesisType} />
                <Row k="Component" v={form.manufacturer ? `${form.manufacturer} ${form.model}`.trim() : 'To be identified'} />
                <Row k="Measurements" v={countMeasures(form.measurements) ? `${countMeasures(form.measurements)} entered` : 'None — workshop will measure'} />
                <Row k="Sensitive areas" v={Object.values(form.sensitive).some(Boolean) ? 'Some flagged' : 'None flagged'} />
                <Row k="Design" v={`${form.design.style} · ${form.design.colour}`} />
                <Row k="Ossiguard" v={form.ossiguard.use === 'Yes' ? `Yes${form.ossiguard.version ? ` (${form.ossiguard.version})` : ''}` : form.ossiguard.use} />
                <Row k="Funding" v={form.funding} />
                <Row k="Shipping" v={form.postcode || 'Not provided'} />
              </div>
              <label className="choice-card items-start">
                <input type="checkbox" checked={form.declarations} onChange={(e) => set({ declarations: e.target.checked })} />
                <span className="text-xs text-slate-300">I understand this is a cosmetic, non-load-bearing cover; workshop review is required; measurements may need verification; the final design may require prosthetist approval; and manufacturing has not started.</span>
              </label>
              {error && <p className="text-xs text-red-300">{error}</p>}
              <div className="flex gap-2">
                <button onClick={back} className="btn-secondary"><ArrowLeft className="h-4 w-4" />Back</button>
                <button onClick={submit} disabled={submitting || !form.declarations} className="btn-primary flex-1"><Send className="h-4 w-4" />{submitting ? 'Submitting…' : 'Submit Request'}</button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function mapFunding(f) { return { 'Pay privately': 'Private payer', 'Self-managed NDIS': 'Self-managed NDIS', 'Plan-managed NDIS': 'Plan-managed NDIS', 'NDIA-managed': 'NDIA-managed', 'Request quote only': 'Quote-only', 'Unsure': 'Quote-only' }[f] || 'Quote-only'; }
function sensitiveSummary(s) { const keys = ['scars','raised','pinch','pain','skinfold','noTouch','changes']; const on = keys.filter(k => s[k]); return on.length ? `Flagged: ${on.join(', ')}. Notes: ${s.notes || '—'}` : 'None flagged'; }
function designSummary(d) { return `${d.style} · ${d.colour}/${d.secondary} · ${d.finish} · vents ${d.vents}${d.text ? ` · text "${d.text}"` : ''}${d.notes ? ` · ${d.notes}` : ''}`; }
function countMeasures(m) { return Object.values(m).filter(v => v !== '' && v != null).length; }

function Row({ k, v }) { return <div className="flex justify-between gap-3 border-b border-white/5 py-1"><span className="text-slate-500">{k}</span><span className="text-right text-slate-100">{v}</span></div>; }
function NavRow({ onBack, onNext, canNext = true }) {
  return (
    <div className="flex gap-2 pt-2">
      <button onClick={onBack} className="btn-secondary"><ArrowLeft className="h-4 w-4" />Back</button>
      <button onClick={onNext} disabled={!canNext} className="btn-primary flex-1">Continue<ArrowRight className="h-4 w-4" /></button>
    </div>
  );
}
function TextInput({ label, value, onChange, type = 'text', placeholder }) {
  return (
    <label className="flex flex-col gap-1">
      <span className="text-xs font-medium text-slate-400">{label}</span>
      <input type={type} value={value} onChange={(e) => onChange(e.target.value)} placeholder={placeholder} className="workshop-input !mt-0" />
    </label>
  );
}
function Select({ label, value, options, onChange }) {
  return (
    <label className="flex flex-col gap-1">
      <span className="text-xs font-medium text-slate-400">{label}</span>
      <select value={value} onChange={(e) => onChange(e.target.value)} className="workshop-input !mt-0">
        {options.map((o) => <option key={o} value={o}>{o}</option>)}
      </select>
    </label>
  );
}
function Radio({ label, value, options, onChange }) {
  return (
    <div>
      <span className="text-xs font-medium text-slate-400">{label}</span>
      <div className="mt-1 flex flex-wrap gap-2">
        {options.map((o) => (
          <button key={o} onClick={() => onChange(o)} className={`rounded-xl border px-3 py-2 text-sm transition ${value === o ? 'border-violet-400 bg-violet-400/10 text-violet-200' : 'border-shire-border bg-shire-raised text-slate-300 hover:border-violet-400/40'}`}>{o}</button>
        ))}
      </div>
    </div>
  );
}