"use client"

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

interface Props {
  value: ProceduresQuickLinksSectionData
  onChange: (value: ProceduresQuickLinksSectionData) => void
  disabled?: boolean
  validation?: {
    links?: boolean
    linkItems?: Array<{ icon?: boolean; title?: boolean; subtitle?: boolean; link?: boolean }>
  }
}

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 ProceduresQuickLinksSection({ value, onChange, disabled = false, validation }: Props) {
  function addLink() {
    if (disabled) return
    onChange({ links: [...value.links, { icon: "", title: "", subtitle: "", link: "" }] })
  }

  function removeLink(index: number) {
    onChange({ links: value.links.filter((_, i) => i !== index) })
  }

  function updateLink<K extends keyof ProceduresQuickLink>(index: number, field: K, val: ProceduresQuickLink[K]) {
    onChange({
      links: value.links.map((l, i) => (i === index ? { ...l, [field]: val } : l)),
    })
  }

  return (
    <div
      className={`flex flex-col gap-3 rounded-xl ${
        validation?.links && value.links.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>Quick Links</Label>
          <span className="text-xs text-muted-foreground font-sans">Each link card has an icon, title, subtitle, and URL</span>
        </div>
        <button
          type="button"
          onClick={addLink}
          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 Link
        </button>
      </div>

      {value.links.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 quick links yet.</p>
          <button
            type="button"
            onClick={addLink}
            disabled={disabled}
            className="text-xs font-semibold font-sans disabled:opacity-50"
            style={{ color: "var(--brand-green)" }}
          >
            Add your first link
          </button>
        </div>
      ) : (
        <div className="flex flex-col gap-3">
          {value.links.map((link, index) => {
            const err = validation?.linkItems?.[index]
            return (
              <div
                key={index}
                className="flex flex-col gap-3 p-4 rounded-xl border border-border bg-muted/40"
              >
                <div className="flex items-center justify-between">
                  <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)" }}
                  >
                    Link {index + 1}
                  </span>
                  <button
                    type="button"
                    onClick={() => removeLink(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 link ${index + 1}`}
                  >
                    <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
                  </button>
                </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={link.icon}
                      onChange={(key) => updateLink(index, "icon", key)}
                      invalid={!!err?.icon}
                    />
                  </div>
                </div>

                <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">Title</label>
                    <input
                      type="text"
                      value={link.title}
                      disabled={disabled}
                      onChange={(e) => updateLink(index, "title", e.target.value)}
                      placeholder="e.g. Free Consultation"
                      className={fieldClass(!!err?.title)}
                    />
                  </div>
                  <div className="flex flex-col gap-1.5">
                    <label className="text-xs font-semibold text-muted-foreground font-sans">Subtitle</label>
                    <input
                      type="text"
                      value={link.subtitle}
                      disabled={disabled}
                      onChange={(e) => updateLink(index, "subtitle", e.target.value)}
                      placeholder="e.g. Talk to an expert today"
                      className={fieldClass(!!err?.subtitle)}
                    />
                  </div>
                </div>

                <div className="flex flex-col gap-1.5">
                  <label className="text-xs font-semibold text-muted-foreground font-sans">Link URL</label>
                  <input
                    type="text"
                    value={link.link}
                    disabled={disabled}
                    onChange={(e) => updateLink(index, "link", e.target.value)}
                    placeholder="e.g. /contact"
                    className={fieldClass(!!err?.link)}
                  />
                </div>
              </div>
            )
          })}
        </div>
      )}
    </div>
  )
}
