"use client"

import { Plus, Trash2, ImagePlus, X } from "lucide-react"
import { useRef, useState } from "react"
import { MEDIA_FILE_BASE } from "@/lib/media-manager/file-names"
import { stageImage } from "@/lib/media-manager/stage"
import type { StagedImage } from "@/lib/media-manager/types"

export interface BeforeAfterItem {
  image: string
  imagePublicId: string
  procedureType: string
  graftsLabel: string
  grafts: string
  monthsPostOpLabel: string
  monthsPostOp: string
  ageLabel: string
  age: string
  satisfactionLabel: string
  satisfaction: string
}

function CaseImageUploader({
  value,
  imagePublicId: _imagePublicId,
  onChange,
  index,
  getDoctorName,
  onStageCaseImage,
  onClearStagedCaseImage,
  disabled = false,
}: {
  value: string
  imagePublicId: string
  onChange: (url: string, publicId: string) => void
  index: number
  getDoctorName?: () => string
  onStageCaseImage?: (index: number, staged: StagedImage) => void
  onClearStagedCaseImage?: (index: number) => void
  disabled?: boolean
}) {
  const inputRef = useRef<HTMLInputElement>(null)
  const [dragOver, setDragOver] = useState(false)
  const [error, setError] = useState<string | null>(null)

  function handleFile(file: File) {
    if (disabled) return
    setError(null)
    if (!file.type.startsWith("image/")) {
      setError("Please upload a valid image.")
      return
    }
    if (file.size > 2 * 1024 * 1024) {
      setError("Max 2 MB.")
      return
    }
    const doctorName = getDoctorName?.().trim() ?? ""
    if (!doctorName) {
      setError("Enter doctor name first.")
      return
    }
    try {
      const staged = stageImage(file, {
        fileBaseName: MEDIA_FILE_BASE.beforeAfter,
        fileIndex: index,
      })
      onStageCaseImage?.(index, staged)
      onChange(staged.previewUrl, "")
    } catch {
      setError("Failed to prepare image.")
    }
  }

  return (
    <div className="flex flex-col gap-1">
      <label className="text-[10px] font-bold text-muted-foreground font-sans uppercase tracking-wider">
        Case Image
      </label>
      {value ? (
        <div className="relative w-full h-36 rounded-xl overflow-hidden border border-border bg-card">
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img src={value} alt={`Before/after case ${index + 1}`} className="w-full h-full object-cover" />
          <button
            type="button"
            onClick={() => {
              onClearStagedCaseImage?.(index)
              onChange("", "")
            }}
            disabled={disabled}
            className="absolute top-1.5 right-1.5 w-6 h-6 rounded-md bg-black/60 flex items-center justify-center text-white hover:bg-black/80 transition-colors cursor-pointer"
            aria-label="Remove case image"
          >
            <X className="w-3 h-3" aria-hidden="true" />
          </button>
        </div>
      ) : (
        <div
          role="button"
          tabIndex={0}
          onClick={() => !disabled && inputRef.current?.click()}
          onKeyDown={(e) => e.key === "Enter" && !disabled && inputRef.current?.click()}
          onDragOver={(e) => { e.preventDefault(); setDragOver(true) }}
          onDragLeave={() => setDragOver(false)}
          onDrop={(e) => {
            e.preventDefault()
            setDragOver(false)
            const file = e.dataTransfer.files[0]
            if (file) handleFile(file)
          }}
          className="flex flex-col items-center justify-center gap-1.5 w-full h-36 rounded-xl border-2 border-dashed cursor-pointer transition-all"
          style={{
            borderColor: dragOver ? "var(--brand-green)" : "var(--border)",
            background: dragOver ? "rgba(43,182,115,0.04)" : "var(--muted)",
          }}
          aria-label="Upload case image"
        >
          <>
            <ImagePlus className="w-5 h-5" style={{ color: "var(--brand-green)" }} aria-hidden="true" />
            <p className="text-[10px] text-muted-foreground font-sans text-center">
              Click or drag (saved on submit)
            </p>
          </>
        </div>
      )}
      {error && <p className="text-[10px] text-red-500 font-sans" role="alert">{error}</p>}
      <input
        ref={inputRef}
        type="file"
        accept="image/*"
        className="sr-only"
        aria-hidden="true"
        onChange={(e) => {
          if (disabled) return
          const file = e.target.files?.[0]
          if (file) handleFile(file)
          e.target.value = ""
        }}
      />
    </div>
  )
}

interface Props {
  value: BeforeAfterItem[]
  onChange: (value: BeforeAfterItem[]) => void
  getDoctorName?: () => string
  onStageCaseImage?: (index: number, staged: StagedImage) => void
  onClearStagedCaseImage?: (index: number) => void
  imageLocked?: boolean
  sharedValuesLocked?: boolean
}

export function DoctorBeforeAfter({
  value,
  onChange,
  getDoctorName,
  onStageCaseImage,
  onClearStagedCaseImage,
  imageLocked = false,
  sharedValuesLocked = false,
}: Props) {
  function addItem() {
    onChange([
      ...value,
      {
        image: "",
        imagePublicId: "",
        procedureType: "",
        graftsLabel: "",
        grafts: "",
        monthsPostOpLabel: "",
        monthsPostOp: "",
        ageLabel: "",
        age: "",
        satisfactionLabel: "",
        satisfaction: "",
      },
    ])
  }

  function removeItem(index: number) {
    onClearStagedCaseImage?.(index)
    onChange(value.filter((_, i) => i !== index))
  }

  function updateItem(index: number, field: keyof BeforeAfterItem, val: BeforeAfterItem[keyof BeforeAfterItem]) {
    onChange(value.map((item, i) => (i === index ? { ...item, [field]: val } : item)))
  }

  function numericField(
    index: number,
    labelField: "monthsPostOpLabel" | "ageLabel" | "satisfactionLabel",
    field: "monthsPostOp" | "age" | "satisfaction",
    defaultLabel: string,
    placeholder: string,
    suffix?: string,
  ) {
    return (
      <div className="grid grid-cols-[120px_1fr] items-center gap-2">
        <input
          type="text"
          value={value[index][labelField]}
          onChange={(e) => updateItem(index, labelField, e.target.value)}
          placeholder={defaultLabel}
          className="w-full bg-muted border border-border rounded-xl px-2.5 py-1.5 text-[11px] text-foreground font-sans placeholder:text-muted-foreground outline-none focus:ring-2 focus:ring-[#2BB673]/30 focus:border-[#2BB673] transition-colors disabled:opacity-60"
          aria-label={`${defaultLabel} label`}
        />
        <div className="relative">
          <input
            type="text"
            value={value[index][field]}
            onChange={(e) => updateItem(index, field, e.target.value)}
            disabled={sharedValuesLocked}
            placeholder={placeholder}
            className="w-full bg-muted border border-border rounded-xl px-3 py-2 text-sm text-foreground font-sans placeholder:text-muted-foreground outline-none focus:ring-2 focus:ring-[#2BB673]/30 focus:border-[#2BB673] transition-colors disabled:opacity-60"
            style={{ paddingRight: suffix ? "2.5rem" : undefined }}
            aria-label={defaultLabel}
          />
          {suffix && (
            <span className="absolute right-2.5 top-1/2 -translate-y-1/2 text-[10px] text-muted-foreground font-sans pointer-events-none">
              {suffix}
            </span>
          )}
        </div>
      </div>
    )
  }

  return (
    <div className="flex flex-col gap-3">
      <div className="flex items-center justify-between">
        <label className="text-xs font-bold text-foreground font-sans uppercase tracking-wider">
          Before &amp; After Results
          <span className="ml-1 normal-case font-normal tracking-normal text-muted-foreground">(optional)</span>
        </label>
        <button
          type="button"
          onClick={addItem}
          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 Case
        </button>
      </div>

      {value.length === 0 ? (
        <div
          className="flex flex-col items-center justify-center gap-2 py-8 rounded-xl border border-dashed"
          style={{ borderColor: "var(--border)" }}
        >
          <p className="text-xs text-muted-foreground font-sans">No before &amp; after cases added yet.</p>
          <button
            type="button"
            onClick={addItem}
            className="text-xs cursor-pointer font-semibold font-sans"
            style={{ color: "var(--brand-green)" }}
          >
            Add your first case
          </button>
        </div>
      ) : (
        <div className="flex flex-col gap-4">
          {value.map((item, index) => (
            <div
              key={index}
              className="rounded-2xl border border-border bg-card overflow-hidden"
            >
              {/* Case header */}
              <div
                className="flex items-center justify-between px-4 py-2.5 border-b border-border"
                style={{ background: "rgba(29,45,104,0.02)" }}
              >
                <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)" }}
                >
                  Case {index + 1}
                </span>
                <button
                  type="button"
                  onClick={() => removeItem(index)}
                  className="p-1.5 cursor-pointer rounded-lg text-muted-foreground hover:text-red-500 hover:bg-red-50 transition-colors"
                  aria-label={`Remove case ${index + 1}`}
                >
                  <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
                </button>
              </div>

              <div className="p-4 grid grid-cols-1 md:grid-cols-2 gap-4">
                {/* Image */}
                <CaseImageUploader
                  value={item.image}
                  imagePublicId={item.imagePublicId}
                  onChange={(url, publicId) => {
                    onChange(
                      value.map((entry, i) =>
                        i === index
                          ? {
                              ...entry,
                              image: url,
                              imagePublicId: publicId,
                            }
                          : entry
                      )
                    )
                  }}
                  index={index}
                  getDoctorName={getDoctorName}
                  onStageCaseImage={onStageCaseImage}
                  onClearStagedCaseImage={onClearStagedCaseImage}
                  disabled={imageLocked}
                />

                {/* Fields */}
                <div className="flex flex-col gap-3">
                  {/* Procedure type */}
                  <div className="flex flex-col gap-1">
                    <label className="text-[10px] font-bold text-muted-foreground font-sans uppercase tracking-wider">
                      Procedure Type
                    </label>
                    <input
                      type="text"
                      value={item.procedureType}
                      onChange={(e) => updateItem(index, "procedureType", e.target.value)}
                      placeholder="e.g. FUE Hair Transplant"
                      className="w-full bg-muted border border-border rounded-xl px-3 py-2 text-sm text-foreground font-sans placeholder:text-muted-foreground outline-none focus:ring-2 focus:ring-[#2BB673]/30 focus:border-[#2BB673] transition-colors"
                    />
                  </div>

                  {/* Grafts */}
                  <div className="flex flex-col gap-2 rounded-xl border border-border bg-muted/40 p-3">
                    <div className="grid grid-cols-[120px_1fr] items-center gap-2">
                      <input
                        type="text"
                        value={item.graftsLabel}
                        onChange={(e) => updateItem(index, "graftsLabel", e.target.value)}
                        placeholder="Grafts"
                        className="w-full bg-muted border border-border rounded-xl px-2.5 py-1.5 text-[11px] text-foreground font-sans placeholder:text-muted-foreground outline-none focus:ring-2 focus:ring-[#2BB673]/30 focus:border-[#2BB673] transition-colors disabled:opacity-60"
                      />
                      <input
                        type="text"
                        value={item.grafts}
                        onChange={(e) => updateItem(index, "grafts", e.target.value)}
                        disabled={sharedValuesLocked}
                        placeholder="e.g. 3,200"
                        className="w-full bg-muted border border-border rounded-xl px-3 py-2 text-sm text-foreground font-sans placeholder:text-muted-foreground outline-none focus:ring-2 focus:ring-[#2BB673]/30 focus:border-[#2BB673] transition-colors disabled:opacity-60"
                      />
                    </div>
                    
                    {numericField(index, "monthsPostOpLabel", "monthsPostOp", "Months Post-Op", "12", "mo")}
                    
                    {numericField(index, "ageLabel", "age", "Age", "35", "yr")}
                    
                    {numericField(index, "satisfactionLabel", "satisfaction", "Satisfaction", "98", "%")}
                    
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}
