import { useState, useEffect } from 'react';
import { Save, Copy, CheckCircle2, Eye } from 'lucide-react';
import StatusPill from '@/components/workshop/StatusPill';
import { DESIGN_CATEGORIES, PRIMARY_STYLES, ACCENT_STYLES, PATTERN_STYLES, TEXT_STYLES, PLACEMENTS, LOGO_PLACEMENTS, COLOURS, FINISHES, TEXT_SIZES, LOGO_SIZES, defaultConfig } from '@/services/designService';
import DesignValidation from './DesignValidation';
import DesignHistory from './DesignHistory';

export default function CustomDesignPanel({ project, design, revisions, busy, onSave, onDuplicate, onRestore, onApprove, onPreview, onChange }) {
  const [form, setForm] = useState(() => ({ ...defaultConfig(project), ...(design || {}) }));

  useEffect(() => {
    setForm({ ...defaultConfig(project), ...(design || {}) });
  }, [design, project]);

  useEffect(() => { onChange && onChange(form); }, [form, onChange]);

  const set = (key, value) => setForm((f) => ({ ...f, [key]: value }));

  return (
    <div className="space-y-5">
      <div className="panel p-5">
        <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
          <div>
            <h2 className="section-title mb-1">Custom Design</h2>
            <p className="text-xs text-slate-500">Conceptual cover styling only — does not alter measured fit or safety constraints. Not manufacturing-ready geometry.</p>
          </div>
          {design && <StatusPill tone={design.validation_status === 'Pass' ? 'green' : design.validation_status === 'Blocked' ? 'red' : 'amber'}>Validation: {design.validation_status || 'Warning'}</StatusPill>}
        </div>

        <div className="grid gap-4 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="Finish">
            <Select value={form.finish} onChange={(v) => set('finish', v)} options={FINISHES} />
          </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="Pattern style">
            <Select value={form.pattern_style} onChange={(v) => set('pattern_style', v)} options={PATTERN_STYLES} />
          </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={['symmetric', 'left asymmetric', 'right asymmetric']} />
          </Field>
        </div>
      </div>

      <div className="panel p-5">
        <h2 className="section-title">Colours</h2>
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
          <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>
        </div>
      </div>

      <div className="panel p-5">
        <h2 className="section-title">SHiRE Logo Placement</h2>
        <p className="mb-3 text-xs text-slate-500">The required SHiRE logo is always present, readable, and never mirrored. Repositioning does not flip it backwards.</p>
        <div className="grid gap-4 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>
        </div>
      </div>

      <div className="panel p-5">
        <div className="mb-3 flex items-center justify-between">
          <h2 className="section-title mb-0">Custom Text</h2>
          <label className="flex cursor-pointer items-center gap-2 text-sm text-slate-300">
            <input type="checkbox" checked={!!form.custom_text_enabled} onChange={(e) => set('custom_text_enabled', e.target.checked)} className="h-5 w-5 accent-shire-purple" />
            Enable custom text
          </label>
        </div>
        {form.custom_text_enabled && (
          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
            <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, short name" /></Field>
            <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="Depth/intensity"><Select value={form.text_depth} onChange={(v) => set('text_depth', v)} options={['shallow', 'medium', 'deep']} /></Field>
            <Field label="Raised or engraved">
              <Select value={form.text_raised ? 'raised' : 'engraved'} onChange={(v) => set('text_raised', v === 'raised')} options={['raised', 'engraved']} />
            </Field>
          </div>
        )}
        {form.custom_text_enabled && (form.custom_text || '').length > 24 && (
          <p className="mt-3 rounded-lg bg-amber-400/10 p-3 text-xs text-amber-200">Text is long — visual quality may reduce. Maximum 40 characters.</p>
        )}
      </div>

      <div className="panel p-5">
        <h2 className="section-title">Notes</h2>
        <div className="grid gap-4">
          <Field label="Surface notes" full><textarea className="workshop-input min-h-20" value={form.surface_notes} onChange={(e) => set('surface_notes', e.target.value)} placeholder="Describe the surface treatment concept" /></Field>
          <Field label="Inspiration notes" full><textarea className="workshop-input min-h-20" value={form.inspiration_notes} onChange={(e) => set('inspiration_notes', e.target.value)} placeholder="Inspiration, reference ideas, customer wishes" /></Field>
          <Field label="Vent concept" full><input className="workshop-input" value={form.vent_concept} onChange={(e) => set('vent_concept', e.target.value)} placeholder="Conceptual vent pattern idea" /></Field>
        </div>
      </div>

      <div className="flex flex-wrap gap-2">
        <button disabled={busy} onClick={() => onSave(form)} className="btn-primary"><Save />Save Design Revision</button>
        <button disabled={busy} onClick={onPreview} className="btn-secondary"><Eye />Preview Design</button>
        <button disabled={busy || !design} onClick={onDuplicate} className="btn-secondary"><Copy />Duplicate Design</button>
        {design && !design.approved_for_quote && <button disabled={busy} onClick={onApprove} className="btn-secondary"><CheckCircle2 />Approve Design for Quote</button>}
      </div>

      <DesignValidation design={design} project={project} />
      <DesignHistory revisions={revisions} currentUuid={design && design.uuid} onRestore={onRestore} busy={busy} />
    </div>
  );
}

function Field({ label, children, full }) {
  return <div className={full ? 'sm:col-span-2 lg:col-span-3' : ''}><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>;
}