"use client"

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

const MAX_IMAGE_EYEBROW_ITEMS = 3
const MAX_QUICK_STATS = 4

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

export interface DoctorsQuickStat {
  label: string
  value: string
}

export interface DoctorsImageEyebrowItem {
  label: string
  value: string
  icon: string
}

export interface DoctorsHeroSectionData {
  eyebrow: string
  title: string
  description: string
  imageEyebrow: DoctorsImageEyebrowItem[]
  quickStats: DoctorsQuickStat[]
}

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

function fieldClassWithValidation(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,
  disabled,
}: {
  onClick: () => void
  label: string
  disabled?: boolean
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      disabled={disabled}
      className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold font-sans transition-all disabled:cursor-not-allowed disabled:opacity-50 disabled:brightness-100 hover:enabled:brightness-105 active:enabled:scale-[0.98] cursor-pointer"
      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: DoctorsHeroSectionData
  onChange: (value: DoctorsHeroSectionData) => void
  validation?: {
    eyebrow?: boolean
    title?: boolean
    description?: boolean
    quickStats?: boolean
    imageEyebrow?: boolean
    quickStatsItems?: Array<{ label?: boolean; value?: boolean }>
    imageEyebrowItems?: Array<{ label?: boolean; value?: boolean; icon?: boolean }>
  }
}

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

  // Image Eyebrow (max 3 items)
  const imageEyebrowCount = (value.imageEyebrow ?? []).length
  const canAddImageEyebrow = imageEyebrowCount < MAX_IMAGE_EYEBROW_ITEMS

  function addImageEyebrow() {
    if (!canAddImageEyebrow) return
    set("imageEyebrow", [...(value.imageEyebrow ?? []), { label: "", value: "", icon: "" }])
  }
  function removeImageEyebrow(i: number) {
    set("imageEyebrow", (value.imageEyebrow ?? []).filter((_, idx) => idx !== i))
  }
  function updateImageEyebrow(i: number, field: keyof DoctorsImageEyebrowItem, val: string) {
    set(
      "imageEyebrow",
      (value.imageEyebrow ?? []).map((item, idx) => (idx === i ? { ...item, [field]: val } : item))
    )
  }

  // Quick Stats (max 4 items)
  const quickStatsCount = value.quickStats.length
  const canAddQuickStat = quickStatsCount < MAX_QUICK_STATS

  function addStat() {
    if (!canAddQuickStat) return
    set("quickStats", [...value.quickStats, { label: "", value: "" }])
  }
  function removeStat(i: number) {
    set("quickStats", value.quickStats.filter((_, idx) => idx !== i))
  }
  function updateStat(i: number, field: keyof DoctorsQuickStat, val: string) {
    set("quickStats", value.quickStats.map((s, idx) => (idx === i ? { ...s, [field]: val } : s)))
  }

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

      {/* Eyebrow */}
      <div className="flex flex-col gap-1.5">
        <Label>Eyebrow</Label>
        <input
          type="text"
          value={value.eyebrow}
          onChange={(e) => set("eyebrow", e.target.value)}
          placeholder="e.g. Our Medical Team"
          className={fieldClassWithValidation(!!validation?.eyebrow)}
        />
      </div>

      {/* 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. Meet Our Expert Doctors"
          className={fieldClassWithValidation(!!validation?.title)}
        />
      </div>

      {/* Description */}
      <div className="flex flex-col gap-1.5">
        <Label>Description</Label>
        <textarea
          value={value.description}
          onChange={(e) => set("description", e.target.value)}
          placeholder="Write a short description for the doctors hero section..."
          rows={4}
          className={`${fieldClassWithValidation(!!validation?.description)} resize-none leading-relaxed`}
        />
      </div>



      {/* Quick Stats */}
      <div
        className={`flex flex-col gap-3 rounded-xl ${
          validation?.quickStats && value.quickStats.length === 0 ? "border border-red-300 p-3 bg-red-50/40" : ""
        }`}
      >
        <div className="flex items-center justify-between gap-2 flex-wrap">
          <div className="flex flex-col gap-0.5 min-w-0">
            <Label>Quick Stats</Label>
            <SubLabel>Up to {MAX_QUICK_STATS} lines</SubLabel>
          </div>
          <AddButton onClick={addStat} label="Add Stat" disabled={!canAddQuickStat} />
        </div>

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

                <div className="grid grid-cols-2 gap-3">
                  <div className="flex flex-col gap-1.5">
                    <SubLabel>Label</SubLabel>
                    <input
                      type="text"
                      value={stat.label}
                      onChange={(e) => updateStat(i, "label", e.target.value)}
                      placeholder="e.g. Expert Doctors"
                      className={fieldClassWithValidation(!!validation?.quickStatsItems?.[i]?.label)}
                    />
                  </div>
                  <div className="flex flex-col gap-1.5">
                    <SubLabel>Value</SubLabel>
                    <input
                      type="text"
                      value={stat.value}
                      onChange={(e) => updateStat(i, "value", e.target.value)}
                      placeholder="e.g. 50+"
                      className={fieldClassWithValidation(!!validation?.quickStatsItems?.[i]?.value)}
                    />
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>


            {/* Image Eyebrow */}
            <div
              className={`flex flex-col gap-3 rounded-xl ${
                validation?.imageEyebrow && (value.imageEyebrow ?? []).length === 0
                  ? "border border-red-300 p-3 bg-red-50/40"
                  : ""
              }`}
            >
        <div className="flex items-center justify-between gap-2 flex-wrap">
          <div className="flex flex-col gap-0.5 min-w-0">
            <Label>Image Eyebrow</Label>
            <SubLabel>Up to {MAX_IMAGE_EYEBROW_ITEMS} lines</SubLabel>
          </div>
          <AddButton
            onClick={addImageEyebrow}
            label="Add Item"
            disabled={!canAddImageEyebrow}
          />
        </div>

        {(value.imageEyebrow ?? []).length === 0 ? (
          <EmptyState label="image eyebrow item" onAdd={addImageEyebrow} />
        ) : (
          <div className="flex flex-col gap-3">
            {(value.imageEyebrow ?? []).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">
                  <ItemBadge index={i} label="Item" />
                  <RemoveButton onClick={() => removeImageEyebrow(i)} label={`Remove item ${i + 1}`} />
                </div>

                <div className="grid grid-cols-2 gap-3">
                  <div className="flex flex-col gap-1.5">
                    <SubLabel>Label</SubLabel>
                    <input
                      type="text"
                      value={item.label}
                      onChange={(e) => updateImageEyebrow(i, "label", e.target.value)}
                      placeholder="e.g. Experience"
                      className={fieldClassWithValidation(!!validation?.imageEyebrowItems?.[i]?.label)}
                    />
                  </div>
                  <div className="flex flex-col gap-1.5">
                    <SubLabel>Value</SubLabel>
                    <input
                      type="text"
                      value={item.value}
                      onChange={(e) => updateImageEyebrow(i, "value", e.target.value)}
                      placeholder="e.g. 10+ Years"
                      className={fieldClassWithValidation(!!validation?.imageEyebrowItems?.[i]?.value)}
                    />
                  </div>
                </div>

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

    </div>
  )
}
