"use client"

import React from "react"
import { Plus, Trash2 } from "lucide-react"

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

export interface HospitalsPageFAQ {
  question: string
  answer: string
}

export interface HospitalsPageFAQSectionData {
  title: string
  faqs: HospitalsPageFAQ[]
}

// ─── 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: HospitalsPageFAQSectionData
  onChange: (value: HospitalsPageFAQSectionData) => void
  validation?: {
    title?: boolean
    faqs?: boolean
    faqItems?: Array<{ question?: boolean; answer?: boolean }>
  }
}

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

  function addFAQ() {
    set("faqs", [...value.faqs, { question: "", answer: "" }])
  }
  function removeFAQ(i: number) {
    set("faqs", value.faqs.filter((_, idx) => idx !== i))
  }
  function updateFAQ(i: number, field: keyof HospitalsPageFAQ, val: string) {
    set("faqs", value.faqs.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. Frequently Asked Questions"
          className={fieldClass(!!validation?.title)}
        />
      </div>

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

        {value.faqs.length === 0 ? (
          <EmptyState label="FAQ" onAdd={addFAQ} />
        ) : (
          <div className="flex flex-col gap-3">
            {value.faqs.map((faq, 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="FAQ" />
                  <RemoveButton onClick={() => removeFAQ(i)} label={`Remove FAQ ${i + 1}`} />
                </div>

                <div className="flex flex-col gap-1.5">
                  <SubLabel>Question</SubLabel>
                  <input
                    type="text"
                    value={faq.question}
                    onChange={(e) => updateFAQ(i, "question", e.target.value)}
                    placeholder="e.g. Which hospitals are JCI accredited?"
                    className={fieldClass(!!validation?.faqItems?.[i]?.question)}
                  />
                </div>

                <div className="flex flex-col gap-1.5">
                  <SubLabel>Answer</SubLabel>
                  <textarea
                    value={faq.answer}
                    onChange={(e) => updateFAQ(i, "answer", e.target.value)}
                    placeholder="Write the answer to this question..."
                    rows={4}
                    className={`${fieldClass(!!validation?.faqItems?.[i]?.answer)} resize-none leading-relaxed`}
                  />
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

    </div>
  )
}
