import { Save, Copy, CheckCircle2, Eye, GitCompare, Send, History, Lock, AlertTriangle } from 'lucide-react';
import StatusPill from '@/components/workshop/StatusPill';
import { DESIGN_CATEGORIES, DESIGN_INTENSITY, SYMMETRY_OPTIONS, PRIMARY_STYLES, ACCENT_STYLES, PATTERN_STYLES, TEXT_STYLES, PLACEMENTS, LOGO_PLACEMENTS, COLOURS, FINISHES, TEXT_SIZES, LOGO_SIZES, PATTERN_LIBRARY } from '@/services/designService';

export default function DesignInspector({ element, form, set, project, design, ossiguard, busy, onSave, onDuplicate, onApprove, onPreview, conflicts, logoValidation }) {
  const hasConflicts = conflicts && Object.keys(conflicts).length > 0;
  const blocked = design && design.validation_status === 'Blocked';

  return (
    <div className="panel flex h-full flex-col">
      <div className="border-b border-shire-border px-4 py-3">
        <h2 className="section-title mb-0">{elementLabel(element)}</h2>
        <p className="text-xs text-slate-500">{elementHint(element)}</p>
      </div>
      <div className="flex-1 overflow-y-auto p-4">
        {element === 'fit' && <FitLocked project={project} />}
        {element === 'cover-shell' && <ShellControls form={form} set={set} />}
        {element === 'panels' && <PanelControls form={form} set={set} />}
        {element === 'vent' && <VentControls form={form} set={set} />}
        {element === 'ossiguard' && <OssiguardInterface ossiguard={ossiguard} project={project} conflicts={conflicts} />}
        {element === 'zones' && <ZonesLocked project={project} ossiguard={ossiguard} />}
        {element === 'branding' && <BrandingControls form={form} set={set} logoValidation={logoValidation} />}
        {element === 'custom-text' && <TextControls form={form} set={set} />}
        {element === 'patterns' && <PatternControls form={form} set={set} />}
        {element === 'accents' && <AccentControls form={form} set={set} />}
        {element === 'colour' && <ColourControls form={form} set={set} />}
        {element === 'cover' && <Overview form={form} set={set} design={design} />}
      </div>

      <div className="space-y-2 border-t border-shire-border p-3">
        {hasConflicts && (
          <div className="rounded-lg border border-red-400/40 bg-red-400/5 p-2.5 text-xs text-red-200">
            <AlertTriangle className="mr-1.5 inline h-3.5 w-3.5" />
            {Object.entries(conflicts).map(([k, v]) => <div key={k}>{v}</div>)}
          </div>
        )}
        <div className="flex flex-wrap gap-2">
          <button disabled={busy} onClick={onSave} className="btn-primary flex-1"><Save className="h-4 w-4" />Save Revision</button>
          <button disabled={busy || !design} onClick={onDuplicate} className="btn-secondary" title="Duplicate concept"><Copy className="h-4 w-4" /></button>
        </div>
        <button disabled={busy || !design || blocked} onClick={onApprove} className="btn-secondary w-full"><CheckCircle2 className="h-4 w-4" />Approve for Quote</button>
      </div>
    </div>
  );
}

function elementLabel(el) {
  return { fit: 'Locked Fit Geometry', 'cover-shell': 'Conceptual Outer Cover', panels: 'Cover Panels', vent: 'Ventilation Concept', ossiguard: 'Ossiguard Interface', zones: 'Protected Zones', branding: 'SHiRE Branding', 'custom-text': 'Custom Text', patterns: 'Patterns', accents: 'Surface Accents', colour: 'Colour and Finish', cover: 'Cover Design' }[el] || 'Inspector';
}
function elementHint(el) {
  const m = {
    fit: 'Locked — fit geometry is never altered by cosmetic design.',
    'cover-shell': 'Conceptual shell styling — not manufacturing CAD.',
    panels: 'Panel layering and access-door styling concepts.',
    vent: 'Conceptual ventilation pattern idea only.',
    ossiguard: 'Connector interface — conflicts highlighted in red.',
    zones: 'Locked — keep-out and sensitive zones protected.',
    branding: 'Mandatory SHiRE logo — always readable, never mirrored.',
    'custom-text': 'Personalised text — conceptual surface plate only.',
    patterns: 'Conceptual exterior pattern library.',
    accents: 'Raised / recessed surface accent concepts.',
    colour: 'Colour palette and finish concept.',
    cover: 'Overall design category and intensity.',
  };
  return m[el] || '';
}

function Field({ label, children, full }) {
  return <div className={full ? 'sm:col-span-2' : ''}><label className="text-xs font-medium uppercase tracking-wide text-slate-400">{label}</label>{children}</div>;
}
function Select({ value, onChange, options }) {
  return <select className="workshop-input" value={value || ''} onChange={(e) => onChange(e.target.value)}>{options.map((o) => <option key={o} value={o}>{o}</option>)}</select>;
}

function FitLocked({ project }) {
  return <div className="space-y-3"><div className="flex items-center gap-2 rounded-lg border border-emerald-400/30 bg-emerald-400/5 p-3 text-sm text-emerald-200"><Lock className="h-4 w-4" />Fit Geometry Locked — cosmetic operations cannot alter measured fit.</div><div className="space-y-1 text-xs text-slate-400">{['Inner cover envelope','Verified clearances','Socket clearance','Sensitive zones','No-contact zones','Keep-out zones','Access points','Knee movement envelope','Cover boundaries','Opening direction','Removal direction'].map((z) => <div key={z} className="flex items-center gap-2"><span className="h-1.5 w-1.5 rounded-full bg-emerald-400" />{z}</div>)}</div>{project && <div className="rounded-lg border border-shire-border bg-shire-raised p-3 text-xs text-slate-400">Cover boundaries: {project.cover_boundaries || 'Not described'}</div>}</div>;
}

function ShellControls({ form, set }) {
  return <div className="grid gap-3 sm:grid-cols-2"><Field label="Design category"><Select value={form.design_category} onChange={(v) => set('design_category', v)} options={DESIGN_CATEGORIES} /></Field><Field label="Design intensity"><Select value={form.design_intensity} onChange={(v) => set('design_intensity', v)} options={DESIGN_INTENSITY} /></Field><Field label="Primary shell style"><Select value={form.primary_style} onChange={(v) => set('primary_style', v)} options={PRIMARY_STYLES} /></Field><Field label="Accent style"><Select value={form.accent_style} onChange={(v) => set('accent_style', v)} options={['none', ...ACCENT_STYLES.filter((s) => s !== 'none')]} /></Field><Field label="Accent density"><Select value={form.accent_density} onChange={(v) => set('accent_density', v)} options={['subtle', 'moderate', 'aggressive']} /></Field><Field label="Symmetry"><Select value={form.symmetry} onChange={(v) => set('symmetry', v)} options={SYMMETRY_OPTIONS} /></Field></div>;
}

function PanelControls({ form, set }) {
  return <div className="space-y-3"><Toggle label="Panel layering" checked={form.detail_panel_layering} onChange={(v) => set('detail_panel_layering', v)} /><Toggle label="Raised ribs" checked={form.detail_raised_ribs} onChange={(v) => set('detail_raised_ribs', v)} /><Toggle label="Recessed channels" checked={form.detail_recessed_channels} onChange={(v) => set('detail_recessed_channels', v)} /><Field label="Access-door styling"><input className="workshop-input" value={form.detail_access_door_styling || ''} onChange={(e) => set('detail_access_door_styling', e.target.value)} placeholder="e.g. flush latch panel" /></Field><Field label="Connector concealment"><input className="workshop-input" value={form.detail_connector_concealment || ''} onChange={(e) => set('detail_connector_concealment', e.target.value)} placeholder="e.g. shroud over connector" /></Field></div>;
}

function VentControls({ form, set }) {
  return <div className="space-y-3"><Field label="Ventilation concept" full><input className="workshop-input" value={form.vent_concept || ''} onChange={(e) => set('vent_concept', e.target.value)} placeholder="e.g. lateral slots, hex mesh" /></Field><p className="text-xs text-slate-500">Conceptual only — actual perforations require real CAD geometry.</p></div>;
}

function OssiguardInterface({ ossiguard, project, conflicts }) {
  if (!ossiguard) return <div className="text-sm text-slate-500">No Ossiguard connector assigned to this project. Assign one from the project Ossiguard tab.</div>;
  return <div className="space-y-3"><div className="rounded-lg border border-shire-border bg-shire-raised p-3 text-sm"><div className="font-medium text-violet-200">{ossiguard.profile_name}</div><div className="mt-1 text-xs text-slate-400">rev{ossiguard.connector_revision} · {ossiguard.approval_status}</div></div><div className="space-y-1 text-xs text-slate-400">{['Connector body','Attachment points','Fastener positions','Insertion path','Removal path','Keep-out volume','Access clearance','Release clearance'].map((z) => <div key={z} className="flex items-center gap-2"><span className="h-1.5 w-1.5 rounded-full bg-red-400" />{z}</div>)}<p className="pt-1 text-slate-500">Design operations must avoid all Ossiguard regions. Conflicts are highlighted in red.</p></div>{conflicts && Object.keys(conflicts).length > 0 && <div className="rounded-lg border border-red-400/40 bg-red-400/5 p-2.5 text-xs text-red-200">{Object.values(conflicts).join('; ')}</div>}</div>;
}

function ZonesLocked({ project, ossiguard }) {
  return <div className="space-y-3"><div className="flex items-center gap-2 rounded-lg border border-amber-400/30 bg-amber-400/5 p-3 text-sm text-amber-200"><Lock className="h-4 w-4" />Protected zones — no design alteration permitted.</div><div className="space-y-1 text-xs text-slate-400"><div>Sensitive areas: {project?.sensitive_area_summary || 'None described'}</div>{ossiguard && <div>Keep-out zones: defined by Ossiguard profile</div>}</div></div>;
}

function BrandingControls({ form, set, logoValidation }) {
  return <div className="space-y-4"><div className="rounded-lg border border-emerald-400/30 bg-emerald-400/5 p-3 text-xs text-emerald-200">SHiRE logo orientation fix active — outward-facing, back-face culled, never mirrored. Logo reads normally from outside the cover.</div><div className="grid gap-3 sm:grid-cols-2"><Field label="Logo placement"><Select value={form.logo_placement} onChange={(v) => set('logo_placement', v)} options={LOGO_PLACEMENTS} /></Field><Field label="Logo size"><Select value={form.logo_size} onChange={(v) => set('logo_size', v)} options={LOGO_SIZES} /></Field><Field label="Logo colour"><Select value={form.logo_colour} onChange={(v) => set('logo_colour', v)} options={COLOURS} /></Field></div>{logoValidation && <div className="space-y-1.5 rounded-lg border border-shire-border bg-shire-raised p-3 text-xs"><div className="flex items-center justify-between"><span className="text-slate-400">Logo present</span><StatusPill tone={logoValidation.present ? 'green' : 'red'}>{logoValidation.present ? 'Yes' : 'No'}</StatusPill></div><div className="flex items-center justify-between"><span className="text-slate-400">Orientation correct</span><StatusPill tone={logoValidation.orientationCorrect ? 'green' : 'red'}>{logoValidation.orientationCorrect ? 'Yes' : 'Mirrored'}</StatusPill></div><div className="flex items-center justify-between"><span className="text-slate-400">Not mirrored</span><StatusPill tone={logoValidation.notMirrored ? 'green' : 'red'}>{logoValidation.notMirrored ? 'Yes' : 'No'}</StatusPill></div><div className="flex items-center justify-between"><span className="text-slate-400">Exterior facing</span><StatusPill tone="green">Yes</StatusPill></div></div>}</div>;
}

function TextControls({ form, set }) {
  return <div className="space-y-3"><Toggle label="Enable custom text" checked={form.custom_text_enabled} onChange={(v) => set('custom_text_enabled', v)} />{form.custom_text_enabled && <><Field label="Text content" full><input className="workshop-input" maxLength={40} value={form.custom_text} onChange={(e) => set('custom_text', e.target.value)} placeholder="e.g. Ray, initials" /></Field><div className="grid gap-3 sm:grid-cols-2"><Field label="Text style"><Select value={form.text_style} onChange={(v) => set('text_style', v)} options={TEXT_STYLES} /></Field><Field label="Placement"><Select value={form.text_placement} onChange={(v) => set('text_placement', v)} options={PLACEMENTS} /></Field><Field label="Orientation"><Select value={form.text_orientation} onChange={(v) => set('text_orientation', v)} options={['horizontal', 'vertical']} /></Field><Field label="Size"><Select value={form.text_size} onChange={(v) => set('text_size', v)} options={TEXT_SIZES} /></Field><Field label="Raised or engraved"><Select value={form.text_raised ? 'raised' : 'engraved'} onChange={(v) => set('text_raised', v === 'raised')} options={['raised', 'engraved']} /></Field><Field label="Conceptual depth"><Select value={form.text_depth} onChange={(v) => set('text_depth', v)} options={['shallow', 'medium', 'deep']} /></Field><Field label="Text colour"><Select value={form.text_colour} onChange={(v) => set('text_colour', v)} options={COLOURS} /></Field></div>{(form.custom_text || '').length > 24 && <p className="text-xs text-amber-200">Text is long — visual quality may reduce.</p>}</>}</div>;
}

function PatternControls({ form, set }) {
  return <div className="space-y-4"><Field label="Pattern style"><Select value={form.pattern_style} onChange={(v) => set('pattern_style', v)} options={PATTERN_STYLES} /></Field>{form.pattern_style && form.pattern_style !== 'none' && <><div className="grid gap-3 sm:grid-cols-2"><Field label="Scale"><Select value={form.pattern_scale} onChange={(v) => set('pattern_scale', v)} options={['small', 'medium', 'large']} /></Field><Field label="Density"><Select value={form.pattern_density} onChange={(v) => set('pattern_density', v)} options={['sparse', 'moderate', 'dense']} /></Field><Field label="Placement region"><Select value={form.pattern_placement_region} onChange={(v) => set('pattern_placement_region', v)} options={PLACEMENTS} /></Field><Field label="Raised / recessed"><Select value={form.pattern_raised ? 'raised' : 'recessed'} onChange={(v) => set('pattern_raised', v === 'raised')} options={['raised', 'recessed']} /></Field></div><Field label="Rotation (degrees)"><input type="number" className="workshop-input" value={form.pattern_rotation_degrees || 0} onChange={(e) => set('pattern_rotation_degrees', Number(e.target.value))} /></Field><Toggle label="Raised ornament" checked={form.detail_raised_ornament} onChange={(v) => set('detail_raised_ornament', v)} /><Toggle label="Engraving concept" checked={form.detail_engraving_concept} onChange={(v) => set('detail_engraving_concept', v)} /></>}</div>;
}

function AccentControls({ form, set }) {
  return <div className="space-y-3"><Field label="Edge treatment"><input className="workshop-input" value={form.detail_edge_treatment || ''} onChange={(e) => set('detail_edge_treatment', e.target.value)} placeholder="e.g. chamfered, rounded" /></Field><Field label="Lower transition style"><input className="workshop-input" value={form.detail_lower_transition || ''} onChange={(e) => set('detail_lower_transition', e.target.value)} placeholder="e.g. tapered fade" /></Field><Field label="Surface notes" full><textarea className="workshop-input min-h-16" value={form.surface_notes || ''} onChange={(e) => set('surface_notes', e.target.value)} /></Field><Field label="Inspiration notes" full><textarea className="workshop-input min-h-16" value={form.inspiration_notes || ''} onChange={(e) => set('inspiration_notes', e.target.value)} /></Field></div>;
}

function ColourControls({ form, set }) {
  return <div className="grid gap-3 sm:grid-cols-2"><Field label="Main cover colour"><Select value={form.main_colour} onChange={(v) => set('main_colour', v)} options={COLOURS} /></Field><Field label="Accent colour"><Select value={form.accent_colour} onChange={(v) => set('accent_colour', v)} options={COLOURS} /></Field><Field label="Logo colour"><Select value={form.logo_colour} onChange={(v) => set('logo_colour', v)} options={COLOURS} /></Field><Field label="Text colour"><Select value={form.text_colour} onChange={(v) => set('text_colour', v)} options={COLOURS} /></Field><Field label="Finish"><Select value={form.finish} onChange={(v) => set('finish', v)} options={FINISHES} /></Field></div>;
}

function Overview({ form, set, design }) {
  return <div className="space-y-4"><div className="grid gap-3 sm:grid-cols-2"><Field label="Design category"><Select value={form.design_category} onChange={(v) => set('design_category', v)} options={DESIGN_CATEGORIES} /></Field><Field label="Design intensity"><Select value={form.design_intensity} onChange={(v) => set('design_intensity', v)} options={DESIGN_INTENSITY} /></Field></div>{design && <div className="rounded-lg border border-shire-border bg-shire-raised p-3 text-xs"><div className="flex items-center justify-between"><span className="text-slate-400">Current revision</span><StatusPill tone={design.validation_status === 'Pass' ? 'green' : design.validation_status === 'Blocked' ? 'red' : 'amber'}>v{design.version} · {design.validation_status || 'Warning'}</StatusPill></div>{design.approved_for_quote && <div className="mt-2 text-emerald-300">Approved for quote</div>}</div>}<div className="text-xs text-slate-500">Design Forge produces conceptual previews — not manufacturing CAD. Approval for Quote does not mean CAD or Print Ready.</div></div>;
}

function Toggle({ label, checked, onChange }) {
  return <label className="choice-card cursor-pointer"><input type="checkbox" checked={!!checked} onChange={(e) => onChange(e.target.checked)} className="h-5 w-5 accent-shire-purple" /><span>{label}</span></label>;
}