"use client"

import React from "react"
import { Plus, Trash2 } from "lucide-react"
import { IconPicker } from "@/components/dashboard/shared/IconPicker"
import { InlineImageUploader } from "./InlineImageUploader"
import { useCmsPagePending } from "@/components/dashboard/cms-pages/CmsPagePendingContext"

export interface ProcessStep {
  title: string
  description: string
  image: string
  imageTitle: string
  imageSubtitle: string
  imageIcon: string
}

export interface ProcessSectionData {
  title: string
  steps: ProcessStep[]
}

interface Props {
  value: ProcessSectionData
  onChange: (value: ProcessSectionData) => void
  showValidation?: boolean
  defaultSharedData?: ProcessSectionData
  isDefaultLanguage?: 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 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>
  )
}

export function ProcessSection({
  value,
  onChange,
  showValidation = false,
  defaultSharedData,
  isDefaultLanguage = false,
}: Props) {
  const { registerStaged, clearStaged } = useCmsPagePending()

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

  function addStep() {
    set("steps", [...value.steps, { title: "", description: "", image: "", imageTitle: "", imageSubtitle: "", imageIcon: "" }])
  }

  function removeStep(i: number) {
    set("steps", value.steps.filter((_, idx) => idx !== i))
  }

  function updateStep(i: number, field: keyof ProcessStep, val: string) {
    set("steps", value.steps.map((s, idx) => (idx === i ? { ...s, [field]: val } : s)))
  }

  return (
    <div className="flex flex-col gap-5">
      <div className="flex flex-col gap-1.5">
        <Label>Section Title</Label>
        <input type="text" value={value.title} onChange={(e) => set("title", e.target.value)} placeholder="e.g. Our Treatment Process" className={fieldClass(showValidation && !value.title.trim())} />
      </div>

      <div className={`flex flex-col gap-3 rounded-xl ${showValidation && value.steps.length === 0 ? "border border-red-300 p-3 bg-red-50/40" : ""}`}>
        <div className="flex items-center justify-between">
          <Label>Steps</Label>
          <button
            type="button"
            onClick={addStep}
            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" />
            Add Step
          </button>
        </div>

        {value.steps.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 steps yet.</p>
            <button type="button" onClick={addStep} className="text-xs cursor-pointer font-semibold font-sans" style={{ color: "var(--brand-green)" }}>
              Add your first step
            </button>
          </div>
        ) : (
          <div className="flex flex-col gap-3">
            {value.steps.map((step, 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">
                  <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)" }}>
                    Step {i + 1}
                  </span>
                  <button type="button" onClick={() => removeStep(i)} className="p-1.5 cursor-pointer rounded-lg text-muted-foreground hover:text-red-500 hover:bg-red-50 transition-colors" aria-label={`Remove step ${i + 1}`}>
                    <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
                  </button>
                </div>

                <div className="flex flex-col gap-1.5">
                  <label className="text-xs font-semibold text-muted-foreground font-sans">Title</label>
                  <input type="text" value={step.title} onChange={(e) => updateStep(i, "title", e.target.value)} placeholder="Step title..." className={fieldClass(showValidation && !step.title.trim())} />
                </div>

                <div className="flex flex-col gap-1.5">
                  <label className="text-xs font-semibold text-muted-foreground font-sans">Description</label>
                  <textarea value={step.description} onChange={(e) => updateStep(i, "description", e.target.value)} placeholder="Step description..." rows={2} className={`${fieldClass(showValidation && !step.description.trim())} resize-none leading-relaxed`} />
                </div>

                <div className={showValidation && !step.image.trim() ? "rounded-xl border border-red-400 p-2 bg-red-50/40" : ""}>
                  <InlineImageUploader
                    label="Step Image"
                    value={step.image}
                    fallbackValue={
                      isDefaultLanguage
                        ? undefined
                        : defaultSharedData?.steps?.[i]?.image
                    }
                    onChange={(url) => updateStep(i, "image", url)}
                    fileBaseName="Process"
                    fileIndex={i}
                    onStageImage={(staged) =>
                      registerStaged(
                        "process",
                        staged,
                        {
                          uploadEndpoint: "/api/admin/home-page/upload-image?section=process",
                          fileIndex: i,
                        },
                        i
                      )
                    }
                    onClearStagedImage={() => clearStaged("process", i)}
                    height="h-44"
                  />
                </div>

                <div
                  className="rounded-xl p-3 border border-border flex flex-col gap-3"
                  style={{ background: "rgba(29,45,104,0.03)" }}
                >
                  <p className="text-xs font-bold font-sans uppercase tracking-wider text-muted-foreground">Image Overlay Details</p>
                  <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">Image Title</label>
                      <input type="text" value={step.imageTitle} onChange={(e) => updateStep(i, "imageTitle", e.target.value)} placeholder="e.g. Expert Team" className={fieldClass(showValidation && !step.imageTitle.trim())} />
                    </div>
                    <div className="flex flex-col gap-1.5">
                      <label className="text-xs font-semibold text-muted-foreground font-sans">Image Subtitle</label>
                      <input type="text" value={step.imageSubtitle} onChange={(e) => updateStep(i, "imageSubtitle", e.target.value)} placeholder="e.g. 50+ Specialists" className={fieldClass(showValidation && !step.imageSubtitle.trim())} />
                    </div>
                  </div>
                  <div className="flex flex-col gap-1.5">
                    <label className="text-xs font-semibold text-muted-foreground font-sans">Image Icon</label>
                    <IconPicker value={step.imageIcon} onChange={(key) => updateStep(i, "imageIcon", key)} invalid={showValidation && !step.imageIcon.trim()} />
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}
