"use client"

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

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

export interface HospitalsPageWhyFeature {
  icon: string
  title: string
  description: string
}

export interface HospitalsPageWhySectionData {
  title: string
  subTitle: string
  features: HospitalsPageWhyFeature[]
}

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

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

interface Props {
  value: HospitalsPageWhySectionData
  onChange: (value: HospitalsPageWhySectionData) => void
  validation?: {
    title?: boolean
    subTitle?: boolean
    features?: boolean
    featureItems?: Array<{ icon?: boolean; title?: boolean; description?: boolean }>
  }
}

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

  function addFeature() {
    set("features", [...value.features, { icon: "", title: "", description: "" }])
  }
  function removeFeature(i: number) {
    set("features", value.features.filter((_, idx) => idx !== i))
  }
  function updateFeature(i: number, field: keyof HospitalsPageWhyFeature, val: string) {
    set("features", value.features.map((f, idx) => (idx === i ? { ...f, [field]: val } : f)))
  }

  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. Why Choose Our Hospitals?"
          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 this section..."
          rows={3}
          className={`${fieldClass(!!validation?.subTitle)} resize-none leading-relaxed`}
        />
      </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">
          <Label>Features</Label>
          <AddButton onClick={addFeature} label="Add Feature" />
        </div>

        {value.features.length === 0 ? (
          <EmptyState label="feature" onAdd={addFeature} />
        ) : (
          <div className="flex flex-col gap-3">
            {value.features.map((feature, 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">
                  <ItemBadge index={i} label="Feature" />
                  <RemoveButton onClick={() => removeFeature(i)} label={`Remove feature ${i + 1}`} />
                </div>

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

                {/* Title */}
                <div className="flex flex-col gap-1.5">
                  <SubLabel>Title</SubLabel>
                  <input
                    type="text"
                    value={feature.title}
                    onChange={(e) => updateFeature(i, "title", e.target.value)}
                    placeholder="e.g. State-of-the-art Equipment"
                    className={fieldClass(!!validation?.featureItems?.[i]?.title)}
                  />
                </div>

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

    </div>
  )
}
