"use client"

import React from "react"
import { Plus, Trash2 } from "lucide-react"
import { IconPicker } from "@/components/dashboard/shared/IconPicker"

// ─── Color picker constants (same as CategoryFormModal) ───────────────────────

const PRESET_COLORS = [
  "#2BB673", // brand green
  "#1D2D68", // brand navy
  "#0EA5E9", // sky blue
  "#F59E0B", // amber
  "#EF4444", // red
  "#8B5CF6", // violet
  "#EC4899", // pink
  "#14B8A6", // teal
  "#F97316", // orange
  "#6366F1", // indigo
]

// ─── Types ────────────────────────────────────────────────────────────────────

export interface HospitalsPageAccreditationItem {
  cardColor: string
  icon: string
  title: string
  subtitle: string
  description: string
}

export interface HospitalsPageAccreditationSectionData {
  title: string
  subTitle: string
  accreditationItems: HospitalsPageAccreditationItem[]
}

// ─── Shared UI helpers ────────────────────────────────────────────────────────

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>
  )
}

function SubLabel({ children }: { children: React.ReactNode }) {
  return (
    <label className="text-xs font-semibold text-muted-foreground font-sans">
      {children}
    </label>
  )
}

function ItemBadge({ index, label }: { index: number; label: string }) {
  return (
    <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)" }}
    >
      {label} {index + 1}
    </span>
  )
}

function AddButton({ onClick, label }: { onClick: () => void; label: string }) {
  return (
    <button
      type="button"
      onClick={onClick}
      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]"
      style={{ background: "rgba(43,182,115,0.10)", color: "var(--brand-green)" }}
    >
      <Plus className="w-3.5 h-3.5" aria-hidden="true" />
      {label}
    </button>
  )
}

function RemoveButton({ onClick, label }: { onClick: () => void; label: string }) {
  return (
    <button
      type="button"
      onClick={onClick}
      className="p-1.5 cursor-pointer rounded-lg text-muted-foreground hover:text-red-500 hover:bg-red-50 transition-colors"
      aria-label={label}
    >
      <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
    </button>
  )
}

function EmptyState({ label, onAdd }: { label: string; onAdd: () => void }) {
  return (
    <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 {label} yet.</p>
      <button
        type="button"
        onClick={onAdd}
        className="text-xs cursor-pointer font-semibold font-sans"
        style={{ color: "var(--brand-green)" }}
      >
        Add your first {label}
      </button>
    </div>
  )
}

// ─── Inline color picker ──────────────────────────────────────────────────────

function ColorPicker({
  value,
  onChange,
  invalid,
}: {
  value: string
  onChange: (color: string) => void
  invalid?: boolean
}) {
  return (
    <div className={`flex flex-col gap-2 ${invalid ? "border border-red-300 p-2 rounded-xl bg-red-50/40" : ""}`}>
      <div className="flex items-center gap-2 flex-wrap">
        {PRESET_COLORS.map((c) => (
          <button
            key={c}
            type="button"
            onClick={() => onChange(c)}
            className="w-7 h-7 rounded-lg transition-all cursor-pointer shrink-0"
            style={{
              background: c,
              outline: value === c ? `3px solid ${c}` : "none",
              outlineOffset: "2px",
            }}
            aria-label={`Select color ${c}`}
            aria-pressed={value === 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={value || "#2BB673"}
            onChange={(e) => onChange(e.target.value)}
            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: value || "#2BB673" }} />
        </div>
      </div>
      {/* Color preview */}
      <div className="flex items-center gap-2 p-2 rounded-lg border border-border bg-muted/50">
        <div
          className="w-6 h-6 rounded-md shrink-0"
          style={{ background: value || "#2BB673" }}
          aria-hidden="true"
        />
        <span className="text-xs font-mono text-muted-foreground">{value || "#2BB673"}</span>
      </div>
    </div>
  )
}

// ─── Main component ───────────────────────────────────────────────────────────

interface Props {
  value: HospitalsPageAccreditationSectionData
  onChange: (value: HospitalsPageAccreditationSectionData) => void
  validation?: {
    title?: boolean
    subTitle?: boolean
    accreditationItems?: boolean
    accreditationItemErrors?: Array<{ title?: boolean; subtitle?: boolean; description?: boolean; icon?: boolean; cardColor?: boolean }>
  }
}

export function HospitalsPageAccreditationSection({ value, onChange, validation }: Props) {
  function set<K extends keyof HospitalsPageAccreditationSectionData>(key: K, val: HospitalsPageAccreditationSectionData[K]) {
    onChange({ ...value, [key]: val })
  }

  function addItem() {
    set("accreditationItems", [
      ...value.accreditationItems,
      { cardColor: PRESET_COLORS[0], icon: "", title: "", subtitle: "", description: "" },
    ])
  }
  function removeItem(i: number) {
    set("accreditationItems", value.accreditationItems.filter((_, idx) => idx !== i))
  }
  function updateItem(i: number, field: keyof HospitalsPageAccreditationItem, val: string) {
    set(
      "accreditationItems",
      value.accreditationItems.map((item, idx) => (idx === i ? { ...item, [field]: val } : item))
    )
  }

  return (
    <div className="flex flex-col gap-6">

      {/* Title */}
      <div className="flex flex-col gap-1.5">
        <Label>Title</Label>
        <input
          type="text"
          value={value.title}
          onChange={(e) => set("title", e.target.value)}
          placeholder="e.g. Our Accreditations"
          className={fieldClass(!!validation?.title)}
        />
      </div>

      {/* SubTitle */}
      <div className="flex flex-col gap-1.5">
        <Label>Subtitle</Label>
        <textarea
          value={value.subTitle}
          onChange={(e) => set("subTitle", e.target.value)}
          placeholder="Write a short subtitle for the accreditation section..."
          rows={3}
          className={`${fieldClass(!!validation?.subTitle)} resize-none leading-relaxed`}
        />
      </div>

      {/* Accreditation Items */}
      <div
        className={`flex flex-col gap-3 rounded-xl ${
          validation?.accreditationItems && value.accreditationItems.length === 0
            ? "border border-red-300 p-3 bg-red-50/40"
            : ""
        }`}
      >
        <div className="flex items-center justify-between">
          <Label>Accreditation Items</Label>
          <AddButton onClick={addItem} label="Add Item" />
        </div>

        {value.accreditationItems.length === 0 ? (
          <EmptyState label="accreditation item" onAdd={addItem} />
        ) : (
          <div className="flex flex-col gap-4">
            {value.accreditationItems.map((item, i) => (
              <div key={i} className="flex flex-col gap-3 p-4 rounded-xl border border-border bg-muted/40">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <ItemBadge index={i} label="Item" />
                    {item.cardColor && (
                      <div
                        className="w-4 h-4 rounded-md shrink-0 border border-white/20"
                        style={{ background: item.cardColor }}
                        aria-hidden="true"
                      />
                    )}
                  </div>
                  <RemoveButton onClick={() => removeItem(i)} label={`Remove item ${i + 1}`} />
                </div>

                {/* Card Color */}
                <div className="flex flex-col gap-1.5">
                  <SubLabel>Card Color</SubLabel>
                  <ColorPicker
                    value={item.cardColor}
                    onChange={(color) => updateItem(i, "cardColor", color)}
                    invalid={!!validation?.accreditationItemErrors?.[i]?.cardColor}
                  />
                </div>

                {/* Icon */}
                <div className="flex flex-col gap-1.5">
                  <SubLabel>Icon</SubLabel>
                  <div
                    className={`rounded-xl ${
                      validation?.accreditationItemErrors?.[i]?.icon ? "border border-red-400 p-2 bg-red-50/40" : ""
                    }`}
                  >
                    <IconPicker value={item.icon} onChange={(key) => updateItem(i, "icon", key)} />
                  </div>
                </div>

                {/* Title & Subtitle */}
                <div className="grid grid-cols-2 gap-3">
                  <div className="flex flex-col gap-1.5">
                    <SubLabel>Title</SubLabel>
                    <input
                      type="text"
                      value={item.title}
                      onChange={(e) => updateItem(i, "title", e.target.value)}
                      placeholder="e.g. JCI Accreditation"
                      className={fieldClass(!!validation?.accreditationItemErrors?.[i]?.title)}
                    />
                  </div>
                  <div className="flex flex-col gap-1.5">
                    <SubLabel>Subtitle</SubLabel>
                    <input
                      type="text"
                      value={item.subtitle}
                      onChange={(e) => updateItem(i, "subtitle", e.target.value)}
                      placeholder="e.g. International Standard"
                      className={fieldClass(!!validation?.accreditationItemErrors?.[i]?.subtitle)}
                    />
                  </div>
                </div>

                {/* Description */}
                <div className="flex flex-col gap-1.5">
                  <SubLabel>Description</SubLabel>
                  <textarea
                    value={item.description}
                    onChange={(e) => updateItem(i, "description", e.target.value)}
                    placeholder="Describe this accreditation..."
                    rows={3}
                    className={`${fieldClass(!!validation?.accreditationItemErrors?.[i]?.description)} resize-none leading-relaxed`}
                  />
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

    </div>
  )
}
