'use client'

import { useState, useCallback } from 'react'
import {
  ArrowUp,
  ArrowDown,
  Copy,
  Trash2,
  Plus,
  AlignLeft,
  AlignCenter,
  AlignRight,
  ArrowUpFromLine,
  ArrowDownToLine,
  Minus,
} from 'lucide-react'
import * as SwitchPrimitive from '@radix-ui/react-switch'
import type {
  BuilderNode,
  SectionNode,
  ContainerNode,
  RowNode,
  ColumnNode,
} from '@actuate-media/cms-core'

export interface NodeSettingsProps {
  node: SectionNode | ContainerNode | RowNode | ColumnNode
  onUpdateSettings: (id: string, settings: Record<string, unknown>) => void
  onRemoveNode: (id: string) => void
  onDuplicateNode: (id: string) => void
  onMoveNodeUp: (id: string) => void
  onMoveNodeDown: (id: string) => void
  onAddRow?: (sectionId: string) => void
}

const INPUT_CLASS =
  'w-full px-3 py-2 text-sm bg-background border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-ring'
const LABEL_CLASS = 'text-sm font-medium text-foreground mb-1 block'
const SECTION_HEADING_CLASS =
  'text-xs font-medium uppercase tracking-wider text-muted-foreground mb-2'

const COLUMN_PRESETS: { label: string; widths: number[] }[] = [
  { label: '12', widths: [12] },
  { label: '6 | 6', widths: [6, 6] },
  { label: '4 | 4 | 4', widths: [4, 4, 4] },
  { label: '3 | 3 | 3 | 3', widths: [3, 3, 3, 3] },
  { label: '8 | 4', widths: [8, 4] },
  { label: '4 | 8', widths: [4, 8] },
  { label: '3 | 6 | 3', widths: [3, 6, 3] },
]

export function NodeSettings({
  node,
  onUpdateSettings,
  onRemoveNode,
  onDuplicateNode,
  onMoveNodeUp,
  onMoveNodeDown,
  onAddRow,
}: NodeSettingsProps) {
  const [confirmDelete, setConfirmDelete] = useState(false)

  const updateSetting = useCallback(
    (key: string, value: unknown) => {
      onUpdateSettings(node.id, { [key]: value })
    },
    [node.id, onUpdateSettings],
  )

  const handleDelete = useCallback(() => {
    if (confirmDelete) {
      onRemoveNode(node.id)
      setConfirmDelete(false)
    } else {
      setConfirmDelete(true)
    }
  }, [confirmDelete, node.id, onRemoveNode])

  const nodeLabel =
    node.type === 'section'
      ? 'Section'
      : node.type === 'container'
        ? 'Container'
        : node.type === 'row'
          ? 'Row'
          : 'Column'

  return (
    <div className="flex h-full flex-col">
      <div className="border-border border-b p-4">
        <p className="text-foreground text-sm font-medium">{nodeLabel} Settings</p>
      </div>

      <div className="flex-1 overflow-y-auto">
        <div className="space-y-4 p-4">
          {node.type === 'section' && (
            <SectionFields node={node} updateSetting={updateSetting} onAddRow={onAddRow} />
          )}
          {node.type === 'container' && (
            <ContainerFields node={node} updateSetting={updateSetting} />
          )}
          {node.type === 'row' && <RowFields node={node} updateSetting={updateSetting} />}
          {node.type === 'column' && <ColumnFields node={node} updateSetting={updateSetting} />}
        </div>
      </div>

      <div className="border-border space-y-2 border-t p-4">
        <p className={SECTION_HEADING_CLASS}>Actions</p>
        <div className="flex gap-2">
          <button
            type="button"
            onClick={() => onMoveNodeUp(node.id)}
            aria-label="Move up"
            className="bg-background border-input hover:bg-accent flex flex-1 items-center justify-center gap-1.5 rounded-md border px-3 py-2 text-sm transition-colors"
          >
            <ArrowUp size={14} />
            Up
          </button>
          <button
            type="button"
            onClick={() => onMoveNodeDown(node.id)}
            aria-label="Move down"
            className="bg-background border-input hover:bg-accent flex flex-1 items-center justify-center gap-1.5 rounded-md border px-3 py-2 text-sm transition-colors"
          >
            <ArrowDown size={14} />
            Down
          </button>
        </div>
        <button
          type="button"
          onClick={() => onDuplicateNode(node.id)}
          className="bg-background border-input hover:bg-accent flex w-full items-center justify-center gap-2 rounded-md border px-3 py-2 text-sm font-medium transition-colors"
        >
          <Copy size={14} />
          Duplicate
        </button>
        <button
          type="button"
          onClick={handleDelete}
          onBlur={() => setConfirmDelete(false)}
          className={`flex w-full items-center justify-center gap-2 rounded-md px-3 py-2 text-sm font-medium transition-colors ${
            confirmDelete
              ? 'bg-destructive text-destructive-foreground'
              : 'bg-background border-destructive text-destructive hover:bg-destructive/10 border'
          }`}
        >
          <Trash2 size={14} />
          {confirmDelete ? 'Click again to confirm' : 'Delete'}
        </button>
      </div>
    </div>
  )
}

function SectionFields({
  node,
  updateSetting,
  onAddRow,
}: {
  node: SectionNode
  updateSetting: (key: string, value: unknown) => void
  onAddRow?: (sectionId: string) => void
}) {
  const s = node.settings
  return (
    <>
      <p className={SECTION_HEADING_CLASS}>Background</p>
      <div>
        <label className={LABEL_CLASS}>Background Color</label>
        <div className="flex items-center gap-2">
          <input
            type="color"
            value={s.background ?? '#ffffff'}
            onChange={(e) => updateSetting('background', e.target.value)}
            className="border-input h-9 w-9 cursor-pointer rounded-md border"
          />
          <input
            type="text"
            value={s.background ?? ''}
            onChange={(e) => updateSetting('background', e.target.value)}
            placeholder="transparent"
            className={`${INPUT_CLASS} flex-1`}
          />
        </div>
      </div>

      <p className={SECTION_HEADING_CLASS}>Spacing</p>
      <div className="grid grid-cols-2 gap-3">
        <div>
          <label className={LABEL_CLASS}>Padding Top</label>
          <input
            type="text"
            value={s.paddingTop ?? ''}
            onChange={(e) => updateSetting('paddingTop', e.target.value)}
            placeholder="0px"
            className={INPUT_CLASS}
          />
        </div>
        <div>
          <label className={LABEL_CLASS}>Padding Bottom</label>
          <input
            type="text"
            value={s.paddingBottom ?? ''}
            onChange={(e) => updateSetting('paddingBottom', e.target.value)}
            placeholder="0px"
            className={INPUT_CLASS}
          />
        </div>
        <div>
          <label className={LABEL_CLASS}>Margin Top</label>
          <input
            type="text"
            value={s.marginTop ?? ''}
            onChange={(e) => updateSetting('marginTop', e.target.value)}
            placeholder="0px"
            className={INPUT_CLASS}
          />
        </div>
        <div>
          <label className={LABEL_CLASS}>Margin Bottom</label>
          <input
            type="text"
            value={s.marginBottom ?? ''}
            onChange={(e) => updateSetting('marginBottom', e.target.value)}
            placeholder="0px"
            className={INPUT_CLASS}
          />
        </div>
      </div>

      <p className={SECTION_HEADING_CLASS}>Attributes</p>
      <div className="flex items-center justify-between">
        <label className="text-foreground text-sm font-medium">Visibility</label>
        <SwitchPrimitive.Root
          checked={s.visibility !== 'hidden'}
          onCheckedChange={(checked) => updateSetting('visibility', checked ? 'visible' : 'hidden')}
          className="bg-input data-[state=checked]:bg-primary relative h-5 w-9 rounded-full transition-colors"
          aria-label="Section visibility"
        >
          <SwitchPrimitive.Thumb className="bg-background block h-3.5 w-3.5 translate-x-0.5 rounded-full shadow-sm transition-transform data-[state=checked]:translate-x-[18px]" />
        </SwitchPrimitive.Root>
      </div>
      <div>
        <label className={LABEL_CLASS}>HTML ID</label>
        <input
          type="text"
          value={s.htmlId ?? ''}
          onChange={(e) => updateSetting('htmlId', e.target.value)}
          placeholder="section-id"
          className={INPUT_CLASS}
        />
      </div>
      <div>
        <label className={LABEL_CLASS}>HTML Class</label>
        <input
          type="text"
          value={s.htmlClass ?? ''}
          onChange={(e) => updateSetting('htmlClass', e.target.value)}
          placeholder="my-class"
          className={INPUT_CLASS}
        />
      </div>

      {onAddRow && (
        <button
          type="button"
          onClick={() => onAddRow(node.id)}
          className="bg-primary text-primary-foreground hover:bg-primary/90 flex w-full items-center justify-center gap-2 rounded-md px-3 py-2 text-sm font-medium transition-colors"
        >
          <Plus size={14} />
          Add Row
        </button>
      )}
    </>
  )
}

function ContainerFields({
  node,
  updateSetting,
}: {
  node: ContainerNode
  updateSetting: (key: string, value: unknown) => void
}) {
  const s = node.settings
  return (
    <>
      <p className={SECTION_HEADING_CLASS}>Layout</p>
      <div>
        <label className={LABEL_CLASS}>Max Width</label>
        <input
          type="text"
          value={s.maxWidth ?? ''}
          onChange={(e) => updateSetting('maxWidth', e.target.value)}
          placeholder="1200px"
          className={INPUT_CLASS}
        />
      </div>
      <div>
        <label className={LABEL_CLASS}>Alignment</label>
        <div className="flex gap-1">
          {(['left', 'center', 'right'] as const).map((align) => {
            const Icon =
              align === 'left' ? AlignLeft : align === 'center' ? AlignCenter : AlignRight
            return (
              <button
                key={align}
                type="button"
                onClick={() => updateSetting('alignment', align)}
                aria-label={`Align ${align}`}
                className={`flex flex-1 items-center justify-center rounded-md border py-2 transition-colors ${
                  s.alignment === align
                    ? 'bg-primary text-primary-foreground border-primary'
                    : 'bg-background border-input hover:bg-accent'
                }`}
              >
                <Icon size={14} />
              </button>
            )
          })}
        </div>
      </div>
      <div>
        <label className={LABEL_CLASS}>Padding</label>
        <input
          type="text"
          value={s.padding ?? ''}
          onChange={(e) => updateSetting('padding', e.target.value)}
          placeholder="0px"
          className={INPUT_CLASS}
        />
      </div>
    </>
  )
}

function RowFields({
  node,
  updateSetting,
}: {
  node: RowNode
  updateSetting: (key: string, value: unknown) => void
}) {
  const s = node.settings
  return (
    <>
      <p className={SECTION_HEADING_CLASS}>Layout</p>
      <div>
        <label className={LABEL_CLASS}>Gap</label>
        <input
          type="text"
          value={s.gap ?? ''}
          onChange={(e) => updateSetting('gap', e.target.value)}
          placeholder="16px"
          className={INPUT_CLASS}
        />
      </div>
      <div>
        <label className={LABEL_CLASS}>Vertical Align</label>
        <div className="flex gap-1">
          {(['top', 'center', 'bottom', 'stretch'] as const).map((align) => {
            const Icon =
              align === 'top'
                ? ArrowUpFromLine
                : align === 'bottom'
                  ? ArrowDownToLine
                  : align === 'center'
                    ? Minus
                    : AlignCenter
            return (
              <button
                key={align}
                type="button"
                onClick={() => updateSetting('verticalAlign', align)}
                aria-label={`Align ${align}`}
                className={`flex flex-1 items-center justify-center rounded-md border py-2 text-xs transition-colors ${
                  s.verticalAlign === align
                    ? 'bg-primary text-primary-foreground border-primary'
                    : 'bg-background border-input hover:bg-accent'
                }`}
              >
                <Icon size={14} />
              </button>
            )
          })}
        </div>
      </div>

      <p className={SECTION_HEADING_CLASS}>Mobile</p>
      <div className="flex items-center justify-between">
        <label className="text-foreground text-sm font-medium">Reverse on Mobile</label>
        <SwitchPrimitive.Root
          checked={!!s.reverseOnMobile}
          onCheckedChange={(checked) => updateSetting('reverseOnMobile', checked)}
          className="bg-input data-[state=checked]:bg-primary relative h-5 w-9 rounded-full transition-colors"
          aria-label="Reverse column order on mobile"
        >
          <SwitchPrimitive.Thumb className="bg-background block h-3.5 w-3.5 translate-x-0.5 rounded-full shadow-sm transition-transform data-[state=checked]:translate-x-[18px]" />
        </SwitchPrimitive.Root>
      </div>
      <div className="flex items-center justify-between">
        <label className="text-foreground text-sm font-medium">Wrap on Mobile</label>
        <SwitchPrimitive.Root
          checked={!!s.wrapOnMobile}
          onCheckedChange={(checked) => updateSetting('wrapOnMobile', checked)}
          className="bg-input data-[state=checked]:bg-primary relative h-5 w-9 rounded-full transition-colors"
          aria-label="Wrap columns on mobile"
        >
          <SwitchPrimitive.Thumb className="bg-background block h-3.5 w-3.5 translate-x-0.5 rounded-full shadow-sm transition-transform data-[state=checked]:translate-x-[18px]" />
        </SwitchPrimitive.Root>
      </div>

      <p className={SECTION_HEADING_CLASS}>Column Presets</p>
      <div className="grid grid-cols-2 gap-1.5">
        {COLUMN_PRESETS.map((preset) => (
          <button
            key={preset.label}
            type="button"
            onClick={() => updateSetting('__columnPreset', preset.widths)}
            className="border-input bg-background hover:bg-accent rounded-md border px-2 py-2 transition-colors"
          >
            <div className="flex h-4 gap-0.5">
              {preset.widths.map((w, i) => (
                <div key={i} className="bg-muted-foreground/30 rounded-sm" style={{ flex: w }} />
              ))}
            </div>
            <p className="text-muted-foreground mt-1 text-center text-xs">
              {preset.widths.join(' | ')}
            </p>
          </button>
        ))}
      </div>
    </>
  )
}

function ColumnFields({
  node,
  updateSetting,
}: {
  node: ColumnNode
  updateSetting: (key: string, value: unknown) => void
}) {
  const s = node.settings
  return (
    <>
      <p className={SECTION_HEADING_CLASS}>Size</p>
      <div>
        <label className={LABEL_CLASS}>Width (1-12)</label>
        <input
          type="number"
          min={1}
          max={12}
          value={s.width}
          onChange={(e) => updateSetting('width', Number(e.target.value))}
          className={INPUT_CLASS}
        />
      </div>

      <p className={SECTION_HEADING_CLASS}>Layout</p>
      <div>
        <label className={LABEL_CLASS}>Vertical Align</label>
        <div className="flex gap-1">
          {(['top', 'center', 'bottom'] as const).map((align) => {
            const Icon =
              align === 'top' ? ArrowUpFromLine : align === 'bottom' ? ArrowDownToLine : Minus
            return (
              <button
                key={align}
                type="button"
                onClick={() => updateSetting('verticalAlign', align)}
                aria-label={`Align ${align}`}
                className={`flex flex-1 items-center justify-center rounded-md border py-2 transition-colors ${
                  s.verticalAlign === align
                    ? 'bg-primary text-primary-foreground border-primary'
                    : 'bg-background border-input hover:bg-accent'
                }`}
              >
                <Icon size={14} />
              </button>
            )
          })}
        </div>
      </div>
      <div>
        <label className={LABEL_CLASS}>Padding</label>
        <input
          type="text"
          value={s.padding ?? ''}
          onChange={(e) => updateSetting('padding', e.target.value)}
          placeholder="0px"
          className={INPUT_CLASS}
        />
      </div>
      <div>
        <label className={LABEL_CLASS}>Background Color</label>
        <div className="flex items-center gap-2">
          <input
            type="color"
            value={s.background ?? '#ffffff'}
            onChange={(e) => updateSetting('background', e.target.value)}
            className="border-input h-9 w-9 cursor-pointer rounded-md border"
          />
          <input
            type="text"
            value={s.background ?? ''}
            onChange={(e) => updateSetting('background', e.target.value)}
            placeholder="transparent"
            className={`${INPUT_CLASS} flex-1`}
          />
        </div>
      </div>
    </>
  )
}
