"use client"

import React from "react"
import { Plus, Trash2 } 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"

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

export interface HospitalsPageStat {
  icon: string
  title: string
  subtitle: string
  value: string
}

export interface HospitalsPageCertification {
  title: string
  subtitle: string
  logo?: string
  image: string
}

export interface HospitalsPageHeroSectionData {
  icon: string
  eyebrow: string
  title: string
  description: string
  image: string
  imagePublicId: string
  statistics: HospitalsPageStat[]
  certifications: HospitalsPageCertification[]
}

// ─── 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, disabled }: { onClick: () => void; label: string; disabled?: boolean }) {
  return (
    <button
      type="button"
      onClick={onClick}
      disabled={disabled}
      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] disabled:opacity-50 disabled:cursor-not-allowed"
      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: HospitalsPageHeroSectionData
  onChange: (value: HospitalsPageHeroSectionData) => void
  isDefaultLanguage?: boolean
  defaultSharedData?: HospitalsPageHeroSectionData
  disabled?: boolean
  validation?: {
    icon?: boolean
    eyebrow?: boolean
    title?: boolean
    description?: boolean
    image?: boolean
    statistics?: boolean
    statisticsItems?: Array<{ icon?: boolean; title?: boolean; subtitle?: boolean; value?: boolean }>
    certifications?: boolean
    certificationsItems?: Array<{ title?: boolean; subtitle?: boolean; image?: boolean }>
  }
}

export function HospitalsPageHeroSection({
  value,
  onChange,
  isDefaultLanguage = false,
  defaultSharedData,
  disabled = false,
  validation,
}: Props) {
  const { registerStaged, clearStaged } = useCmsPagePending()

  function set<K extends keyof HospitalsPageHeroSectionData>(key: K, val: HospitalsPageHeroSectionData[K]) {
    onChange({ ...value, [key]: val })
  }

  // Statistics
  function addStat() {
    set("statistics", [...value.statistics, { icon: "", title: "", subtitle: "", value: "" }])
  }
  function removeStat(i: number) {
    set("statistics", value.statistics.filter((_, idx) => idx !== i))
  }
  function updateStat(i: number, field: keyof HospitalsPageStat, val: string) {
    set("statistics", value.statistics.map((s, idx) => (idx === i ? { ...s, [field]: val } : s)))
  }

  // Certifications
  function addCert() {
    set("certifications", [...value.certifications, { title: "", subtitle: "", logo: "", image: "" }])
  }
  function removeCert(i: number) {
    set("certifications", value.certifications.filter((_, idx) => idx !== i))
  }
  function updateCert(i: number, field: keyof HospitalsPageCertification, val: string) {
    set("certifications", value.certifications.map((c, idx) => (idx === i ? { ...c, [field]: val } : c)))
  }

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

      {/* Icon */}
      <div className="flex flex-col gap-1.5">
        <Label>Section Icon</Label>
        <div className={`rounded-xl ${validation?.icon ? "border border-red-400 p-2 bg-red-50/40" : ""}`}>
          <fieldset disabled={disabled} className="min-w-0">
            <IconPicker value={value.icon} onChange={(key) => set("icon", key)} />
          </fieldset>
        </div>
      </div>

      {/* 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)}
          disabled={disabled}
          placeholder="e.g. World-Class Medical Facilities"
          className={fieldClass(!!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)}
          disabled={disabled}
          placeholder="e.g. Find the Best Hospitals in Turkey"
          className={fieldClass(!!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)}
          disabled={disabled}
          placeholder="Write a short description for the hospitals page hero..."
          rows={4}
          className={`${fieldClass(!!validation?.description)} resize-none leading-relaxed`}
        />
      </div>

      {/* Hero Image */}
      <div className="flex flex-col gap-1.5">
        <Label>Hero Image</Label>
        <div className={validation?.image ? "rounded-xl border border-red-400 p-2 bg-red-50/40" : ""}>
          <InlineImageUploader
            value={value.image ?? ""}
            fallbackValue={isDefaultLanguage ? undefined : defaultSharedData?.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/hospitals-page/upload-image?section=hero",
              })
            }
            onClearStagedImage={() => {
              clearStaged("hero")
              onChange({ ...value, image: "", imagePublicId: "" })
            }}
            height="h-48"
          />
        </div>
      </div>

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

        {value.statistics.length === 0 ? (
          <EmptyState label="statistic" onAdd={addStat} />
        ) : (
          <div className="flex flex-col gap-3">
            {value.statistics.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="Statistic" />
                  {!disabled ? <RemoveButton onClick={() => removeStat(i)} label={`Remove statistic ${i + 1}`} /> : null}
                </div>

                <div className="flex flex-col gap-1.5">
                  <SubLabel>Icon</SubLabel>
                  <div className={`rounded-xl ${validation?.statisticsItems?.[i]?.icon ? "border border-red-400 p-2 bg-red-50/40" : ""}`}>
                    <fieldset disabled={disabled} className="min-w-0">
                      <IconPicker value={stat.icon} onChange={(key) => updateStat(i, "icon", key)} />
                    </fieldset>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-3">
                  <div className="flex flex-col gap-1.5">
                    <SubLabel>Title</SubLabel>
                    <input
                      type="text"
                      value={stat.title}
                      onChange={(e) => updateStat(i, "title", e.target.value)}
                      disabled={disabled}
                      placeholder="e.g. Hospitals"
                      className={fieldClass(!!validation?.statisticsItems?.[i]?.title)}
                    />
                  </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)}
                      disabled={disabled}
                      placeholder="e.g. 500+"
                      className={fieldClass(!!validation?.statisticsItems?.[i]?.value)}
                    />
                  </div>
                </div>

                <div className="flex flex-col gap-1.5">
                  <SubLabel>Subtitle</SubLabel>
                  <input
                    type="text"
                    value={stat.subtitle}
                    onChange={(e) => updateStat(i, "subtitle", e.target.value)}
                    disabled={disabled}
                    placeholder="e.g. Accredited facilities"
                    className={fieldClass(!!validation?.statisticsItems?.[i]?.subtitle)}
                  />
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

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

        {value.certifications.length === 0 ? (
          <EmptyState label="certification" onAdd={addCert} />
        ) : (
          <div className="flex flex-col gap-3">
            {value.certifications.map((cert, 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="Certification" />
                  {!disabled ? <RemoveButton onClick={() => removeCert(i)} label={`Remove certification ${i + 1}`} /> : null}
                </div>

                <div className="grid grid-cols-2 gap-3">
                  <div className="flex flex-col gap-1.5">
                    <SubLabel>Title</SubLabel>
                    <input
                      type="text"
                      value={cert.title}
                      onChange={(e) => updateCert(i, "title", e.target.value)}
                      disabled={disabled}
                      placeholder="e.g. JCI Accredited"
                      className={fieldClass(!!validation?.certificationsItems?.[i]?.title)}
                    />
                  </div>
                  <div className="flex flex-col gap-1.5">
                    <SubLabel>Subtitle</SubLabel>
                    <input
                      type="text"
                      value={cert.subtitle}
                      onChange={(e) => updateCert(i, "subtitle", e.target.value)}
                      disabled={disabled}
                      placeholder="e.g. International standard"
                      className={fieldClass(!!validation?.certificationsItems?.[i]?.subtitle)}
                    />
                  </div>
                </div>

                <div className="flex flex-col gap-1.5">
                  <SubLabel>Logo (optional)</SubLabel>
                  <InlineImageUploader
                    value={cert.logo ?? ""}
                    fallbackValue={isDefaultLanguage ? undefined : defaultSharedData?.certifications?.[i]?.logo}
                    fileBaseName="Certifications"
                    fileIndex={i}
                    disabled={disabled}
                    onChange={(url) => updateCert(i, "logo", url.trim())}
                    onStageImage={(staged) =>
                      registerStaged(
                        "certifications",
                        staged,
                        {
                          uploadEndpoint:
                            "/api/admin/hospitals-page/upload-image?section=certifications",
                          fileIndex: i,
                          slot: "logo",
                        },
                        i,
                        "logo"
                      )
                    }
                    onClearStagedImage={() => clearStaged("certifications", i, "logo")}
                    height="h-36"
                  />
                </div>

                <div className="flex flex-col gap-1.5">
                  <SubLabel>Image</SubLabel>
                  <div className={validation?.certificationsItems?.[i]?.image ? "rounded-xl border border-red-400 p-2 bg-red-50/40" : ""}>
                    <InlineImageUploader
                      value={cert.image}
                      fallbackValue={isDefaultLanguage ? undefined : defaultSharedData?.certifications?.[i]?.image}
                      fileBaseName="Certifications"
                      fileIndex={i}
                      disabled={disabled}
                      onChange={(url) => updateCert(i, "image", url.trim())}
                      onStageImage={(staged) =>
                        registerStaged(
                          "certifications",
                          staged,
                          {
                            uploadEndpoint:
                              "/api/admin/hospitals-page/upload-image?section=certifications",
                            fileIndex: i,
                            slot: "image",
                          },
                          i,
                          "image"
                        )
                      }
                      onClearStagedImage={() => clearStaged("certifications", i, "image")}
                      height="h-44"
                    />
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

    </div>
  )
}
