"use client"

import { Plus, Trash2 } from "lucide-react"
import { IconPicker } from "@/components/dashboard/shared/IconPicker"
import type {
  ProceduresWhyTurkeySectionData,
  ProceduresWhyTurkeyFeature,
} from "@/lib/pages/procedures-page/form-types"

interface Props {
  value: ProceduresWhyTurkeySectionData
  onChange: (value: ProceduresWhyTurkeySectionData) => void
  disabled?: boolean
  validation?: {
    eyebrow?: boolean
    title?: boolean
    features?: boolean
    featureItems?: Array<{
      cardColor?: boolean
      icon?: boolean
      title?: boolean
      description?: boolean
      label?: boolean
      value?: boolean
    }>
  }
}

const PRESET_COLORS = [
  "#2BB673",
  "#1D2D68",
  "#0EA5E9",
  "#F59E0B",
  "#EF4444",
  "#8B5CF6",
  "#EC4899",
  "#14B8A6",
  "#F97316",
  "#6366F1",
]

function fieldClass(invalid = false) {
  return `w-full bg-card border rounded-xl px-3 py-2.5 text-sm text-foreground font-sans placeholder:text-muted-foreground outline-none transition-colors focus:ring-2 ${
    invalid
      ? "border-red-400 focus:ring-red-200/70 focus:border-red-500"
      : "border-border focus:ring-[#2BB673]/30 focus:border-[#2BB673]"
  }`
}

function Label({ children }: { children: React.ReactNode }) {
  return (
    <label className="text-xs font-bold text-foreground font-sans uppercase tracking-wider">
      {children}
    </label>
  )
}

export function ProceduresWhyTurkeySection({ value, onChange, disabled = false, validation }: Props) {
  function set<K extends keyof ProceduresWhyTurkeySectionData>(key: K, val: ProceduresWhyTurkeySectionData[K]) {
    onChange({ ...value, [key]: val })
  }

  function addFeature() {
    if (disabled) return
    set("features", [
      ...value.features,
      { cardColor: PRESET_COLORS[0], icon: "", title: "", description: "", label: "", value: "" },
    ])
  }

  function removeFeature(index: number) {
    set("features", value.features.filter((_, i) => i !== index))
  }

  function updateFeature<K extends keyof ProceduresWhyTurkeyFeature>(
    index: number,
    field: K,
    val: ProceduresWhyTurkeyFeature[K]
  ) {
    set(
      "features",
      value.features.map((f, i) => (i === index ? { ...f, [field]: val } : f))
    )
  }

  return (
    <div className="flex flex-col gap-5">
      {/* Eyebrow */}
      <div className="flex flex-col gap-1.5">
        <Label>Eyebrow</Label>
        <input
          type="text"
          value={value.eyebrow}
          disabled={disabled}
          onChange={(e) => set("eyebrow", e.target.value)}
          placeholder="e.g. Why Choose Turkey"
          className={fieldClass(!!validation?.eyebrow)}
        />
      </div>

      {/* Title */}
      <div className="flex flex-col gap-1.5">
        <Label>Title</Label>
        <input
          type="text"
          value={value.title}
          disabled={disabled}
          onChange={(e) => set("title", e.target.value)}
          placeholder="e.g. The Advantages of Medical Tourism in Turkey"
          className={fieldClass(!!validation?.title)}
        />
      </div>

      {/* Features */}
      <div
        className={`flex flex-col gap-3 rounded-xl ${
          validation?.features && value.features.length === 0
            ? "border border-red-300 p-3 bg-red-50/40"
            : ""
        }`}
      >
        <div className="flex items-center justify-between gap-2">
          <div className="flex flex-col gap-0.5">
            <Label>Features</Label>
            <span className="text-xs text-muted-foreground font-sans">Each feature card includes color, icon, title, description, and a stat</span>
          </div>
          <button
            type="button"
            onClick={addFeature}
            disabled={disabled}
            className="flex cursor-pointer items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold font-sans transition-all hover:brightness-105 active:scale-[0.98] disabled:opacity-50 disabled:cursor-not-allowed"
            style={{ background: "rgba(43,182,115,0.10)", color: "var(--brand-green)" }}
          >
            <Plus className="w-3.5 h-3.5" aria-hidden="true" />
            Add Feature
          </button>
        </div>

        {value.features.length === 0 ? (
          <div className="flex flex-col items-center justify-center gap-2 py-8 rounded-xl border border-dashed border-border">
            <p className="text-xs text-muted-foreground font-sans">No features yet.</p>
            <button
              type="button"
              onClick={addFeature}
              disabled={disabled}
              className="text-xs font-semibold font-sans disabled:opacity-50"
              style={{ color: "var(--brand-green)" }}
            >
              Add your first feature
            </button>
          </div>
        ) : (
          <div className="flex flex-col gap-4">
            {value.features.map((feature, index) => {
              const err = validation?.featureItems?.[index]
              return (
                <div
                  key={index}
                  className="flex flex-col gap-4 p-4 rounded-xl border border-border bg-muted/40"
                >
                  {/* Header */}
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <div
                        className="w-5 h-5 rounded-md shrink-0"
                        style={{ background: feature.cardColor }}
                        aria-hidden="true"
                      />
                      <span
                        className="text-xs font-bold font-sans px-2 py-0.5 rounded-md"
                        style={{ background: "rgba(29,45,104,0.08)", color: "var(--brand-navy)" }}
                      >
                        Feature {index + 1}
                      </span>
                    </div>
                    <button
                      type="button"
                      onClick={() => removeFeature(index)}
                      disabled={disabled}
                      className="p-1.5 cursor-pointer rounded-lg text-muted-foreground hover:text-red-500 hover:bg-red-50 transition-colors"
                      aria-label={`Remove feature ${index + 1}`}
                    >
                      <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
                    </button>
                  </div>

                  {/* Card Color */}
                  <div className="flex flex-col gap-2">
                    <label className="text-xs font-semibold text-muted-foreground font-sans">
                      Card Color
                    </label>
                    <div className="flex items-center gap-2 flex-wrap">
                      {PRESET_COLORS.map((c) => (
                        <button
                          key={c}
                          type="button"
                          onClick={() => updateFeature(index, "cardColor", c)}
                          disabled={disabled}
                          className="w-7 h-7 rounded-lg transition-all cursor-pointer shrink-0 disabled:opacity-60"
                          style={{
                            background: c,
                            outline: feature.cardColor === c ? `3px solid ${c}` : "none",
                            outlineOffset: "2px",
                          }}
                          aria-label={`Select color ${c}`}
                          aria-pressed={feature.cardColor === c}
                        />
                      ))}
                      {/* Custom color input */}
                      <div
                        className="relative w-7 h-7 rounded-lg overflow-hidden border border-dashed border-border cursor-pointer"
                        title="Custom color"
                      >
                        <input
                          type="color"
                          value={feature.cardColor}
                          onChange={(e) => updateFeature(index, "cardColor", e.target.value)}
                          disabled={disabled}
                          className="absolute inset-0 w-full h-full cursor-pointer opacity-0"
                          aria-label="Custom color"
                        />
                        <div
                          className="w-full h-full rounded-lg"
                          style={{ background: feature.cardColor }}
                        />
                      </div>
                    </div>
                    {/* Color preview */}
                    <div
                      className="flex items-center gap-2 px-3 py-2 rounded-lg border border-border"
                      style={{ background: `${feature.cardColor}12` }}
                    >
                      <div
                        className="w-4 h-4 rounded-md shrink-0"
                        style={{ background: feature.cardColor }}
                        aria-hidden="true"
                      />
                      <span className="text-xs font-mono text-muted-foreground">{feature.cardColor}</span>
                    </div>
                  </div>

                  {/* Icon */}
                  <div className="flex flex-col gap-1.5">
                    <label className="text-xs font-semibold text-muted-foreground font-sans">Icon</label>
                    <div className={disabled ? "pointer-events-none opacity-60" : ""}>
                      <IconPicker
                        value={feature.icon}
                        onChange={(key) => updateFeature(index, "icon", key)}
                        invalid={!!err?.icon}
                      />
                    </div>
                  </div>

                  {/* Title */}
                  <div className="flex flex-col gap-1.5">
                    <label className="text-xs font-semibold text-muted-foreground font-sans">Title</label>
                    <input
                      type="text"
                      value={feature.title}
                      disabled={disabled}
                      onChange={(e) => updateFeature(index, "title", e.target.value)}
                      placeholder="e.g. World-Class Surgeons"
                      className={fieldClass(!!err?.title)}
                    />
                  </div>

                  {/* Description */}
                  <div className="flex flex-col gap-1.5">
                    <label className="text-xs font-semibold text-muted-foreground font-sans">Description</label>
                    <textarea
                      value={feature.description}
                      disabled={disabled}
                      onChange={(e) => updateFeature(index, "description", e.target.value)}
                      placeholder="Write a brief description..."
                      rows={3}
                      className={`${fieldClass(!!err?.description)} resize-none leading-relaxed`}
                    />
                  </div>

                  {/* Stat: Label + Value */}
                  <div className="grid grid-cols-2 gap-3">
                    <div className="flex flex-col gap-1.5">
                      <label className="text-xs font-semibold text-muted-foreground font-sans">Stat Label</label>
                      <input
                        type="text"
                        value={feature.label}
                        disabled={disabled}
                        onChange={(e) => updateFeature(index, "label", e.target.value)}
                        placeholder="e.g. Certified Surgeons"
                        className={fieldClass(!!err?.label)}
                      />
                    </div>
                    <div className="flex flex-col gap-1.5">
                      <label className="text-xs font-semibold text-muted-foreground font-sans">Stat Value</label>
                      <input
                        type="text"
                        value={feature.value}
                        disabled={disabled}
                        onChange={(e) => updateFeature(index, "value", e.target.value)}
                        placeholder="e.g. 500+"
                        className={fieldClass(!!err?.value)}
                      />
                    </div>
                  </div>
                </div>
              )
            })}
          </div>
        )}
      </div>
    </div>
  )
}
