"use client"

import { Plus as PlusIcon, Trash2 as RemoveIcon } from "lucide-react"
import { IconPicker } from "@/components/dashboard/shared/IconPicker"
import { InlineImageUploader } from "@/components/dashboard/home/InlineImageUploader"
import { useCmsPagePending } from "@/components/dashboard/cms-pages/CmsPagePendingContext"

const MAX_QUICK_STATS = 3

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

export interface BlogQuickStat {
  label: string
  icon: string
}

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

export interface BlogHeroSectionData {
  eyebrow: string
  title: string
  description: string
  quickStats: BlogQuickStat[]
  image: string
  imagePublicId: string
  imageStats: BlogImageStat
}

export interface BlogHeroValidationState {
  eyebrow?: boolean
  title?: boolean
  description?: boolean
  image?: boolean
  quickStats?: boolean
  quickStatsItems?: Array<{ label?: boolean; icon?: boolean }>
  imageStats?: { icon?: boolean; label?: boolean; value?: boolean }
}

// ─── 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,
  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)" }}
    >
      <PlusIcon 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}
    >
      <RemoveIcon 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: BlogHeroSectionData
  onChange: (value: BlogHeroSectionData) => void
  /** Shared default image preview shown when current language has no override image. */
  defaultImageUrl?: string
  isDefaultLanguage?: boolean
  validation?: BlogHeroValidationState
  disabled?: boolean
}

export function BlogHeroSection({
  value,
  onChange,
  defaultImageUrl,
  isDefaultLanguage = false,
  validation,
  disabled = false,
}: Props) {
  const { registerStaged, clearStaged } = useCmsPagePending()
  const showDefaultFallback = !value.image?.trim() && !isDefaultLanguage && (defaultImageUrl?.trim() ?? "") !== ""
  function set<K extends keyof BlogHeroSectionData>(key: K, val: BlogHeroSectionData[K]) {
    onChange({ ...value, [key]: val })
  }

  const quickStatsCount = value.quickStats.length
  const canAddQuickStat = quickStatsCount < MAX_QUICK_STATS

  // Quick Stats helpers
  function addQuickStat() {
    if (disabled) return
    if (!canAddQuickStat) return
    set("quickStats", [...value.quickStats, { label: "", icon: "" }])
  }
  function removeQuickStat(i: number) {
    set("quickStats", value.quickStats.filter((_, idx) => idx !== i))
  }
  function updateQuickStat(i: number, field: keyof BlogQuickStat, val: string) {
    set("quickStats", value.quickStats.map((s, idx) => (idx === i ? { ...s, [field]: val } : s)))
  }

  // Image Stats helper
  function updateImageStat(field: keyof BlogImageStat, val: string) {
    set("imageStats", { ...value.imageStats, [field]: val })
  }

  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}
          disabled={disabled}
          onChange={(e) => set("eyebrow", e.target.value)}
          placeholder="e.g. Our Blog"
          className={fieldClass(!!validation?.eyebrow)}
        />
      </div>

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

      {/* Description */}
      <div className="flex flex-col gap-1.5">
        <Label>Description</Label>
        <textarea
          value={value.description}
          disabled={disabled}
          onChange={(e) => set("description", e.target.value)}
          placeholder="Write a short description for the blog hero section..."
          rows={4}
          className={`${fieldClass(!!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={addQuickStat} label="Add Stat" disabled={disabled || !canAddQuickStat} />
        </div>

        {value.quickStats.length === 0 ? (
          <EmptyState label="stat" onAdd={addQuickStat} />
        ) : (
          <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={() => {
                      if (disabled) return
                      removeQuickStat(i)
                    }}
                    label={`Remove stat ${i + 1}`}
                  />
                </div>

                <div className="flex flex-col gap-1.5">
                  <SubLabel>Label</SubLabel>
                  <input
                    type="text"
                    value={stat.label}
                    disabled={disabled}
                    onChange={(e) => updateQuickStat(i, "label", e.target.value)}
                    placeholder="e.g. Expert Doctors"
                    className={fieldClass(!!validation?.quickStatsItems?.[i]?.label)}
                  />
                </div>

                <div className="flex flex-col gap-1.5">
                  <SubLabel>Icon</SubLabel>
                  <div
                    className={`rounded-xl ${
                      validation?.quickStatsItems?.[i]?.icon ? "border border-red-400 p-2 bg-red-50/40" : ""
                    }`}
                  >
                    <div className={disabled ? "pointer-events-none opacity-60" : ""}>
                      <IconPicker
                        value={stat.icon}
                        onChange={(key) => updateQuickStat(i, "icon", key)}
                      />
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
      {/* Image Stats */}
      <div className="flex flex-col gap-3 rounded-xl">
        <Label>Image Stats</Label>
        <div className="flex flex-col gap-3 p-4 rounded-xl border border-border bg-muted/40">
          <div className="flex flex-col gap-1.5">
            <SubLabel>Icon</SubLabel>
            <div
              className={`rounded-xl ${
                validation?.imageStats?.icon ? "border border-red-400 p-2 bg-red-50/40" : ""
              }`}
            >
              <div className={disabled ? "pointer-events-none opacity-60" : ""}>
                <IconPicker
                  value={value.imageStats.icon}
                  onChange={(key) => updateImageStat("icon", key)}
                />
              </div>
            </div>
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div className="flex flex-col gap-1.5">
              <SubLabel>Label</SubLabel>
              <input
                type="text"
                value={value.imageStats.label}
                disabled={disabled}
                onChange={(e) => updateImageStat("label", e.target.value)}
                placeholder="e.g. Articles Published"
                className={fieldClass(!!validation?.imageStats?.label)}
              />
            </div>
            <div className="flex flex-col gap-1.5">
              <SubLabel>Value</SubLabel>
              <input
                type="text"
                value={value.imageStats.value}
                disabled={disabled}
                onChange={(e) => updateImageStat("value", e.target.value)}
                placeholder="e.g. 120+"
                className={fieldClass(!!validation?.imageStats?.value)}
              />
            </div>
          </div>
        </div>
      </div>

      {/* Hero Image */}
      <div className="flex flex-col gap-1.5">
        <Label>{isDefaultLanguage ? "Image" : "Image Override (Optional)"}</Label>
        {showDefaultFallback && defaultImageUrl && (
          <div className="flex flex-col gap-2 p-3 rounded-xl border border-dashed border-border bg-muted/30">
            <SubLabel>Using English image</SubLabel>
            <div
              className="relative h-32 rounded-lg overflow-hidden border border-border bg-card"
            >
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img
                src={defaultImageUrl.trim()}
                alt=""
                className="w-full h-full object-cover"
              />
            </div>
            <p className="text-[11px] text-muted-foreground font-sans">
              Upload below to use a different image for this language; leaving this empty keeps the English image.
            </p>
          </div>
        )}
        <div className={validation?.image ? "rounded-xl border border-red-400 p-2 bg-red-50/40" : ""}>
          <InlineImageUploader
            value={value.image}
            fileBaseName="heroimage"
            disabled={disabled}
            onChange={(url) => {
              const trimmedUrl = url.trim()
              onChange({
                ...value,
                image: trimmedUrl,
                imagePublicId: trimmedUrl.startsWith("blob:")
                  ? value.imagePublicId
                  : trimmedUrl
                    ? value.imagePublicId
                    : "",
              })
            }}
            onStageImage={(staged) =>
              registerStaged("hero", staged, {
                uploadEndpoint: "/api/admin/blog-page/upload-image?section=hero",
              })
            }
            onClearStagedImage={() => {
              clearStaged("hero")
              onChange({ ...value, image: "", imagePublicId: "" })
            }}
            height="h-48"
          />
        </div>
      </div>

      

    </div>
  )
}
