"use client"

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"

const MAX_QUICK_STATS = 4

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

export interface ContactHeroSectionData {
  eyebrow: string
  title: string
  description: string
  imageEyebrow: string
  image: string
  imagePublicId: string
  quickStats: ContactQuickStat[]
}

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

interface Props {
  value: ContactHeroSectionData
  onChange: (value: ContactHeroSectionData) => void
  defaultImageUrl?: string
  isDefaultLanguage?: boolean
  validation?: ContactHeroValidationState
  disabled?: boolean
}

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 ${
    invalid
      ? "border-red-500 focus:ring-2 focus:ring-red-200 focus:border-red-500"
      : "border-border focus:ring-2 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 (
    <span className="text-xs font-semibold text-muted-foreground font-sans">
      {children}
    </span>
  )
}

export function ContactHeroSection({
  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 ContactHeroSectionData>(key: K, val: ContactHeroSectionData[K]) {
    onChange({ ...value, [key]: val })
  }

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

  function addStat() {
    if (disabled) return
    if (!canAddStat) return
    set("quickStats", [...value.quickStats, { label: "", value: "", icon: "" }])
  }

  function removeStat(index: number) {
    set("quickStats", value.quickStats.filter((_, i) => i !== index))
  }

  function updateStat(index: number, field: keyof ContactQuickStat, val: string) {
    set(
      "quickStats",
      value.quickStats.map((s, i) => (i === index ? { ...s, [field]: val } : s))
    )
  }

  return (
    <div className="flex flex-col gap-5">
      {/* 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. Contact Us"
          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. Get In Touch With Us"
          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 hero section..."
          rows={4}
          className={`${fieldClass(!!validation?.description)} resize-none leading-relaxed`}
        />
      </div>

    

      {/* Quick Stats — max {MAX_QUICK_STATS} lines */}
      <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>
          <button
            type="button"
            onClick={addStat}
            disabled={disabled || !canAddStat}
            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:enabled:brightness-105 active:enabled:scale-[0.98] disabled:cursor-not-allowed disabled:opacity-50 disabled:brightness-100"
            style={{ background: "rgba(43,182,115,0.10)", color: "var(--brand-green)" }}
          >
            <Plus className="w-3.5 h-3.5" aria-hidden="true" />
            Add Stat
          </button>
        </div>

        {value.quickStats.length === 0 ? (
          <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 stats yet.</p>
            <button
              type="button"
              onClick={addStat}
              disabled={disabled || !canAddStat}
              className="text-xs font-semibold font-sans disabled:cursor-not-allowed disabled:opacity-50"
              style={{ color: "var(--brand-green)" }}
            >
              Add your first stat
            </button>
          </div>
        ) : (
          <div className="flex flex-col gap-3">
            {value.quickStats.map((stat, index) => (
              <div
                key={index}
                className="flex flex-col gap-3 p-4 rounded-xl border border-border bg-muted/40"
              >
                <div className="flex items-center justify-between">
                  <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)" }}
                  >
                    Stat {index + 1}
                  </span>
                  <button
                    type="button"
                    onClick={() => removeStat(index)}
                    disabled={disabled}
                    className="p-1.5 cursor-pointer rounded-lg text-muted-foreground hover:text-red-500 hover:bg-red-50 transition-colors"
                    aria-label={`Remove stat ${index + 1}`}
                  >
                    <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
                  </button>
                </div>
                <div className="grid grid-cols-2 gap-3">
                    <div className="flex flex-col gap-1.5">
                    <label className="text-xs font-semibold text-muted-foreground font-sans">Label</label>
                    <input
                      type="text"
                      value={stat.label}
                      disabled={disabled}
                      onChange={(e) => updateStat(index, "label", e.target.value)}
                      placeholder="e.g. Happy Patients"
                      className={fieldClass(!!validation?.quickStatsItems?.[index]?.label)}
                    />
                  </div>
                  <div className="flex flex-col gap-1.5">
                    <label className="text-xs font-semibold text-muted-foreground font-sans">Value</label>
                    <input
                      type="text"
                      value={stat.value}
                      disabled={disabled}
                      onChange={(e) => updateStat(index, "value", e.target.value)}
                      placeholder="e.g. 5000+"
                      className={fieldClass(!!validation?.quickStatsItems?.[index]?.value)}
                    />
                  </div>
                
                </div>
                <div className="flex flex-col gap-1.5">
                  <label className="text-xs font-semibold text-muted-foreground font-sans">Icon</label>
                  <div className={disabled ? "pointer-events-none opacity-60" : ""}>
                    <IconPicker
                      value={stat.icon}
                      onChange={(key) => updateStat(index, "icon", key)}
                      invalid={!!validation?.quickStatsItems?.[index]?.icon}
                    />
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Hero Image */}
      <div className="flex flex-col gap-1.5">
        <Label>Image</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/contact-us/upload-image?section=hero",
            })
          }
          onClearStagedImage={() => {
            clearStaged("hero")
            onChange({ ...value, image: "", imagePublicId: "" })
          }}
          height="h-48"
        />
        </div>
      </div>
        {/* Image Eyebrow */}
        <div className="flex flex-col gap-1.5">
        <Label>Image Eyebrow</Label>
        <input
          type="text"
          value={value.imageEyebrow}
          disabled={disabled}
          onChange={(e) => set("imageEyebrow", e.target.value)}
          placeholder="e.g. Our Clinic in Istanbul"
          className={fieldClass(!!validation?.imageEyebrow)}
        />
      </div>
    </div>
  )
}
