import { useState, useEffect, useMemo } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { X, ChevronLeft, ChevronRight, Wrench, Paintbrush, Shapes, FlaskConical, HelpCircle } from 'lucide-react'
import { createMaterial, getNextCode } from '../api/materials'

interface Props {
  open: boolean
  onClose: () => void
  onCreated?: (name: string) => void
}

const MATERIAL_TYPES = [
  { code: '01', label: 'Metals', icon: Wrench, color: 'bg-slate-100 text-slate-700 border-slate-300', activeColor: 'bg-slate-600 text-white border-slate-600' },
  { code: '02', label: 'Coatings', icon: Paintbrush, color: 'bg-status-info-bg text-status-info-text border-border-default', activeColor: 'bg-blue-600 text-white border-blue-600' },
  { code: '03', label: 'Non-metals', icon: Shapes, color: 'bg-status-warning-bg text-status-warning-text border-border-default', activeColor: 'bg-amber-600 text-white border-amber-600' },
  { code: '04', label: 'Compounds', icon: FlaskConical, color: 'bg-purple-50 text-purple-700 border-purple-300', activeColor: 'bg-purple-600 text-white border-purple-600' },
  { code: '05', label: 'Misc', icon: HelpCircle, color: 'bg-surface-alt text-content-secondary border-border-default', activeColor: 'bg-gray-600 text-white border-gray-600' },
] as const

const SUBTYPE_PRESETS: Record<string, Array<{ code: string; label: string }>> = {
  '01': [
    { code: '01', label: 'Steel' },
    { code: '02', label: 'Niro' },
    { code: '03', label: 'Tin' },
    { code: '04', label: 'Aluminium' },
    { code: '05', label: 'Brass' },
    { code: '06', label: 'Bronze' },
  ],
  '02': [
    { code: '01', label: 'Durotect' },
    { code: '02', label: 'Coat' },
  ],
  '03': [
    { code: '01', label: 'Elastomer' },
    { code: '02', label: 'Plastic (opaque)' },
    { code: '03', label: 'Plastic (translucent)' },
    { code: '04', label: 'TPU' },
    { code: '05', label: 'Ceramic' },
  ],
  '04': [
    { code: '01', label: 'E-series' },
    { code: '02', label: 'Elgo-series' },
    { code: '03', label: 'PTFE / GFK' },
  ],
  '05': [],
}

export default function MaterialWizard({ open, onClose, onCreated }: Props) {
  const qc = useQueryClient()
  const [step, setStep] = useState(1)
  const [typeCode, setTypeCode] = useState('')
  const [subTypeCode, setSubTypeCode] = useState('')
  const [customSubType, setCustomSubType] = useState('')
  const [consecutive, setConsecutive] = useState<number | null>(null)
  const [nameParts, setNameParts] = useState('')
  const [description, setDescription] = useState('')
  const [loadingCode, setLoadingCode] = useState(false)

  const effectiveSubType = subTypeCode || customSubType

  // Reset on open
  useEffect(() => {
    if (open) {
      setStep(1)
      setTypeCode('')
      setSubTypeCode('')
      setCustomSubType('')
      setConsecutive(null)
      setNameParts('')
      setDescription('')
    }
  }, [open])

  // Fetch next consecutive number when type + subtype are set
  useEffect(() => {
    if (!typeCode || !effectiveSubType || effectiveSubType.length !== 2) {
      setConsecutive(null)
      return
    }
    const prefix = typeCode + effectiveSubType
    setLoadingCode(true)
    getNextCode(prefix)
      .then((res) => setConsecutive(res.next_consecutive))
      .catch(() => setConsecutive(1))
      .finally(() => setLoadingCode(false))
  }, [typeCode, effectiveSubType])

  const fullCode = useMemo(() => {
    if (!typeCode || !effectiveSubType || consecutive === null) return null
    return `${typeCode}${effectiveSubType}${String(consecutive).padStart(2, '0')}`
  }, [typeCode, effectiveSubType, consecutive])

  const sanitizedName = nameParts
    .replace(/\s+/g, '-')
    .replace(/[^a-zA-Z0-9\-]/g, '')
    .replace(/-+/g, '-')
    .replace(/^-|-$/g, '')

  const fullMaterialName = fullCode && sanitizedName
    ? `SCHAEFFLER_${fullCode}_${sanitizedName}`
    : null

  const schaefflerCodeInt = fullCode ? parseInt(fullCode, 10) : null

  const createMut = useMutation({
    mutationFn: () =>
      createMaterial({
        name: fullMaterialName!,
        description: description.trim() || undefined,
        source: 'manual',
        schaeffler_code: schaefflerCodeInt,
      }),
    onSuccess: () => {
      toast.success('Material created')
      qc.invalidateQueries({ queryKey: ['materials'] })
      if (onCreated && fullMaterialName) onCreated(fullMaterialName)
      onClose()
    },
    onError: (e: any) => toast.error(e.response?.data?.detail || 'Failed to create material'),
  })

  if (!open) return null

  const nameValid = sanitizedName.length >= 2

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40" onClick={onClose}>
      <div
        className="bg-surface rounded-xl shadow-2xl w-full max-w-lg mx-4 overflow-hidden"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-border-default">
          <div>
            <h2 className="text-lg font-semibold text-content">Schaeffler Material Wizard</h2>
            <p className="text-xs text-content-muted mt-0.5">Step {step} of 3</p>
          </div>
          <button onClick={onClose} className="text-content-muted hover:text-content-secondary">
            <X size={20} />
          </button>
        </div>

        {/* Steps */}
        <div className="px-6 py-5 min-h-[260px]">
          {step === 1 && (
            <div>
              <p className="text-sm font-medium text-content-secondary mb-4">Select material type:</p>
              <div className="grid grid-cols-2 gap-3">
                {MATERIAL_TYPES.map((t) => {
                  const Icon = t.icon
                  const active = typeCode === t.code
                  return (
                    <button
                      key={t.code}
                      onClick={() => {
                        setTypeCode(t.code)
                        setSubTypeCode('')
                        setCustomSubType('')
                        setStep(2)
                      }}
                      className={`flex items-center gap-3 px-4 py-3 rounded-lg border-2 transition-all text-left ${
                        active ? t.activeColor : t.color + ' hover:shadow-md'
                      }`}
                    >
                      <Icon size={20} />
                      <div>
                        <p className="text-sm font-semibold">{t.label}</p>
                        <p className={`text-xs ${active ? 'opacity-80' : 'opacity-60'}`}>Code {t.code}</p>
                      </div>
                    </button>
                  )
                })}
              </div>
            </div>
          )}

          {step === 2 && (
            <div>
              <p className="text-sm font-medium text-content-secondary mb-3">
                Sub-type for <span className="font-bold">{MATERIAL_TYPES.find((t) => t.code === typeCode)?.label}</span>:
              </p>
              {(SUBTYPE_PRESETS[typeCode] ?? []).length > 0 && (
                <div className="flex flex-wrap gap-2 mb-4">
                  {SUBTYPE_PRESETS[typeCode]!.map((st) => (
                    <button
                      key={st.code}
                      onClick={() => {
                        setSubTypeCode(st.code)
                        setCustomSubType('')
                      }}
                      className={`px-3 py-1.5 rounded-full text-sm border transition-all ${
                        subTypeCode === st.code
                          ? 'text-white'
                          : 'bg-surface text-content-secondary border-border-default hover:border-accent'
                      }`}
                      style={subTypeCode === st.code ? { backgroundColor: 'var(--color-accent)', borderColor: 'var(--color-accent)' } : undefined}
                    >
                      {st.label} ({st.code})
                    </button>
                  ))}
                </div>
              )}

              <div className="mb-4">
                <label className="block text-xs font-medium text-content-muted mb-1">
                  {(SUBTYPE_PRESETS[typeCode] ?? []).length > 0 ? 'Or enter custom sub-type (2 digits):' : 'Enter sub-type (2 digits):'}
                </label>
                <input
                  maxLength={2}
                  placeholder="e.g. 07"
                  value={customSubType}
                  onChange={(e) => {
                    const v = e.target.value.replace(/\D/g, '')
                    setCustomSubType(v)
                    if (v.length > 0) setSubTypeCode('')
                  }}
                  className="w-24 px-3 py-1.5 border border-border-default rounded-md text-sm focus:outline-none focus:border-accent"
                />
              </div>

              {effectiveSubType.length === 2 && (
                <div className="bg-surface-alt rounded-lg px-4 py-3">
                  <p className="text-xs text-content-muted mb-1">Next consecutive number:</p>
                  <p className="text-lg font-mono font-bold text-content">
                    {loadingCode ? '...' : consecutive !== null ? String(consecutive).padStart(2, '0') : '--'}
                  </p>
                </div>
              )}
            </div>
          )}

          {step === 3 && (
            <div>
              <p className="text-sm font-medium text-content-secondary mb-3">Material name and description:</p>
              <div className="space-y-3">
                <div>
                  <label className="block text-xs font-medium text-content-secondary mb-1">Name (dash-separated) *</label>
                  <input
                    autoFocus
                    placeholder="e.g. Chrome-Steel-Hardened"
                    value={nameParts}
                    onChange={(e) => setNameParts(e.target.value)}
                    className="w-full px-3 py-2 border border-border-default rounded-md text-sm focus:outline-none focus:border-accent"
                  />
                  {nameParts && !nameValid && (
                    <p className="text-xs text-red-500 mt-1">Name must be at least 2 characters (a-z, 0-9, dashes)</p>
                  )}
                </div>
                <div>
                  <label className="block text-xs font-medium text-content-secondary mb-1">Description (optional)</label>
                  <input
                    placeholder="e.g. Gehärteter Chromstahl"
                    value={description}
                    onChange={(e) => setDescription(e.target.value)}
                    className="w-full px-3 py-2 border border-border-default rounded-md text-sm focus:outline-none focus:border-accent"
                  />
                </div>
              </div>
            </div>
          )}
        </div>

        {/* Live preview bar */}
        <div className="px-6 py-3 bg-surface-alt border-t border-border-light">
          <p className="text-xs text-content-muted mb-0.5">Preview:</p>
          <p className="font-mono text-sm font-semibold text-content truncate">
            {fullMaterialName || (
              <span className="text-content-muted">
                SCHAEFFLER_{typeCode || 'XX'}{effectiveSubType || 'YY'}{consecutive !== null ? String(consecutive).padStart(2, '0') : 'ZZ'}_{sanitizedName || 'Name'}
              </span>
            )}
          </p>
        </div>

        {/* Footer buttons */}
        <div className="flex items-center justify-between px-6 py-4 border-t border-border-default">
          <button
            onClick={() => setStep(Math.max(1, step - 1))}
            disabled={step === 1}
            className="flex items-center gap-1 text-sm text-content-secondary hover:text-content disabled:opacity-30"
          >
            <ChevronLeft size={16} /> Back
          </button>

          {step < 3 ? (
            <button
              onClick={() => setStep(step + 1)}
              disabled={step === 2 && effectiveSubType.length !== 2}
              className="flex items-center gap-1 btn-primary text-sm"
            >
              Next <ChevronRight size={16} />
            </button>
          ) : (
            <button
              onClick={() => createMut.mutate()}
              disabled={!fullMaterialName || !nameValid || createMut.isPending}
              className="btn-primary text-sm"
            >
              {createMut.isPending ? 'Creating...' : 'Create Material'}
            </button>
          )}
        </div>
      </div>
    </div>
  )
}
