"use client"

import { ImagePlus, Plus, Trash2, 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 AccreditationItem {
  name: string
  date: string
  description: string
  logo: string
  certificateImage: string
  issuer: string
}

export interface HospitalAccreditationData {
  eyebrow: string
  title: string
  subtitle: string
  accreditations: AccreditationItem[]
}

interface Props {
  value: HospitalAccreditationData
  onChange: (value: HospitalAccreditationData) => void
  getHospitalSlug?: () => string
  onStageAccreditationLogo?: (index: number, staged: StagedImage) => void
  onClearStagedAccreditationLogo?: (index: number) => void
  onStageAccreditationCertificate?: (index: number, staged: StagedImage) => void
  onClearStagedAccreditationCertificate?: (index: number) => void
}

const inputClass =
  "w-full bg-card border border-border rounded-xl px-4 py-2.5 text-sm text-foreground font-sans placeholder:text-muted-foreground outline-none focus:ring-2 focus:ring-[#2BB673]/30 focus:border-[#2BB673] transition-colors"

const listFieldClass = inputClass

function AccreditationImageUploader({
  value,
  onChange,
  label,
  width = "w-40",
  height = "h-28",
  getHospitalSlug,
  fileBaseName,
  fileIndex = 0,
  onStageImage,
  onClearStagedImage,
}: {
  value: string
  onChange: (url: string) => void
  label: string
  width?: string
  height?: string
  getHospitalSlug?: () => string
  fileBaseName?: string
  fileIndex?: number
  onStageImage?: (staged: StagedImage) => void
  onClearStagedImage?: () => void
}) {
  const inputRef = useRef<HTMLInputElement>(null)
  const [dragOver, setDragOver] = useState(false)
  const [error, setError] = useState<string | null>(null)

  function handleFile(file: File) {
    setError(null)
    if (!file.type.startsWith("image/")) {
      setError("Please upload a valid image file.")
      return
    }
    if (file.size > 5 * 1024 * 1024) {
      setError("Image size must be 5 MB or less.")
      return
    }
    const hospitalSlug = getHospitalSlug?.().trim() ?? ""
    if (!hospitalSlug) {
      setError("Please enter the hospital slug before selecting an image.")
      return
    }
    try {
      const staged = stageImage(file, {
        maxBytes: 5 * 1024 * 1024,
        fileBaseName,
        fileIndex,
      })
      onStageImage?.(staged)
      onChange(staged.previewUrl)
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to prepare image.")
    }
  }

  return (
    <div className="flex flex-col gap-1.5">
      <label className="text-[10px] font-bold text-muted-foreground font-sans uppercase tracking-wider">
        {label}
      </label>
      {value ? (
        <div className={`relative ${width} ${height} rounded-2xl overflow-hidden border border-border bg-card`}>
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img src={value} alt={label} className="w-full h-full object-cover" />
          <button
            type="button"
            onClick={() => {
              onClearStagedImage?.()
              onChange("")
            }}
            className="absolute top-1.5 right-1.5 w-7 h-7 rounded-lg bg-black/60 flex items-center justify-center text-white hover:bg-black/80 transition-colors cursor-pointer"
            aria-label={`Remove ${label.toLowerCase()}`}
          >
            <X className="w-3.5 h-3.5" aria-hidden="true" />
          </button>
        </div>
      ) : (
        <div
          role="button"
          tabIndex={0}
          onClick={() => inputRef.current?.click()}
          onKeyDown={(e) => e.key === "Enter" && 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-2 ${width} ${height} rounded-2xl 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(--card)",
          }}
          aria-label={`Upload ${label.toLowerCase()}`}
        >
          <>
            <div
              className="w-10 h-10 rounded-xl flex items-center justify-center"
              style={{ background: "rgba(43,182,115,0.10)" }}
            >
              <ImagePlus className="w-5 h-5" style={{ color: "var(--brand-green)" }} aria-hidden="true" />
            </div>
            <p className="text-[10px] text-muted-foreground font-sans text-center leading-tight">
              Click or drag
              <br />
              to upload
            </p>
          </>
        </div>
      )}
      {error && (
        <p className="text-xs font-sans text-red-500" role="alert">
          {error}
        </p>
      )}
      <input
        ref={inputRef}
        type="file"
        accept="image/*"
        className="sr-only"
        aria-hidden="true"
        onChange={(e) => {
          const file = e.target.files?.[0]
          if (file) handleFile(file)
          e.target.value = ""
        }}
      />
    </div>
  )
}

export function HospitalAccreditationSection({
  value,
  onChange,
  getHospitalSlug,
  onStageAccreditationLogo,
  onClearStagedAccreditationLogo,
  onStageAccreditationCertificate,
  onClearStagedAccreditationCertificate,
}: Props) {
  function set<K extends keyof HospitalAccreditationData>(key: K, val: HospitalAccreditationData[K]) {
    onChange({ ...value, [key]: val })
  }

  function updateItem(idx: number, field: keyof AccreditationItem, val: string) {
    const updated = value.accreditations.map((a, i) => (i === idx ? { ...a, [field]: val } : a))
    set("accreditations", updated)
  }

  function addItem() {
    set("accreditations", [
      ...value.accreditations,
      { name: "", date: "", description: "", logo: "", certificateImage: "", issuer: "" },
    ])
  }

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

  return (
    <div className="flex flex-col gap-5">
      {/* Section headings */}
      <div className="flex flex-col gap-3 rounded-xl border border-border bg-muted/30 p-4">
        <div className="flex items-center gap-2 pb-2 border-b border-border">
          <span className="w-1 h-4 rounded-full shrink-0" style={{ background: "var(--brand-green)" }} aria-hidden="true" />
          <p className="text-[11px] font-bold uppercase tracking-wider text-muted-foreground font-sans">Section Headings</p>
        </div>
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
          <div className="flex flex-col gap-1.5">
            <label className="text-xs font-semibold text-foreground font-sans">Eyebrow</label>
            <input type="text" value={value.eyebrow} onChange={(e) => set("eyebrow", e.target.value)} placeholder="e.g. Certifications" className={inputClass} />
          </div>
          <div className="flex flex-col gap-1.5">
            <label className="text-xs font-semibold text-foreground font-sans">Title</label>
            <input type="text" value={value.title} onChange={(e) => set("title", e.target.value)} placeholder="e.g. Internationally Accredited" className={inputClass} />
          </div>
          <div className="flex flex-col gap-1.5">
            <label className="text-xs font-semibold text-foreground font-sans">Subtitle</label>
            <input type="text" value={value.subtitle} onChange={(e) => set("subtitle", e.target.value)} placeholder="e.g. Recognized by global health organizations" className={inputClass} />
          </div>
        </div>
      </div>

      {/* Accreditations list */}
      <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">
            Accreditations ({value.accreditations.length})
          </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 Accreditation
          </button>
        </div>
        {value.accreditations.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 accreditations 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 accreditation
            </button>
          </div>
        ) : (
          <div className="flex flex-col gap-4">
            {value.accreditations.map((item, idx) => (
              <div key={idx} className="rounded-2xl border border-border bg-card overflow-hidden">
                <div
                  className="flex items-center justify-between px-4 py-2.5 border-b border-border"
                  style={{ background: "rgba(43,182,115,0.02)" }}
                >
                  <span
                    className="text-xs font-bold font-sans px-2 py-0.5 rounded-md"
                    style={{ background: "rgba(43,182,115,0.10)", color: "var(--brand-green)" }}
                  >
                    Accreditation {idx + 1}
                  </span>
                  <button
                    type="button"
                    onClick={() => removeItem(idx)}
                    className="p-1.5 cursor-pointer rounded-lg text-muted-foreground hover:text-red-500 hover:bg-red-50 transition-colors"
                    aria-label="Remove accreditation"
                  >
                    <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
                  </button>
                </div>
                <div className="p-4 flex flex-col gap-3">
                  <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                    <div className="flex flex-col gap-1">
                      <label className="text-[10px] font-bold text-muted-foreground font-sans uppercase tracking-wider">Name</label>
                      <input type="text" value={item.name} onChange={(e) => updateItem(idx, "name", e.target.value)} placeholder="e.g. JCI Accreditation" className={listFieldClass} />
                    </div>
                    <div className="flex flex-col gap-1">
                      <label className="text-[10px] font-bold text-muted-foreground font-sans uppercase tracking-wider">Issuer</label>
                      <input type="text" value={item.issuer} onChange={(e) => updateItem(idx, "issuer", e.target.value)} placeholder="e.g. Joint Commission International" className={listFieldClass} />
                    </div>
                    <div className="flex flex-col gap-1">
                      <label className="text-[10px] font-bold text-muted-foreground font-sans uppercase tracking-wider">Date</label>
                      <input type="date" value={item.date} onChange={(e) => updateItem(idx, "date", e.target.value)} className={listFieldClass} />
                    </div>
                  </div>
                  <div className="flex flex-col gap-1">
                    <label className="text-[10px] font-bold text-muted-foreground font-sans uppercase tracking-wider">Description</label>
                    <textarea
                      value={item.description}
                      onChange={(e) => updateItem(idx, "description", e.target.value)}
                      placeholder="Brief description of this accreditation..."
                      rows={2}
                      className={`${listFieldClass} resize-none leading-relaxed`}
                    />
                  </div>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <AccreditationImageUploader
                      label="Logo"
                      value={item.logo}
                      onChange={(url) => updateItem(idx, "logo", url)}
                      getHospitalSlug={getHospitalSlug}
                      fileBaseName={MEDIA_FILE_BASE.accreditationLogo}
                      fileIndex={idx}
                      onStageImage={(staged) => onStageAccreditationLogo?.(idx, staged)}
                      onClearStagedImage={() => onClearStagedAccreditationLogo?.(idx)}
                      width="w-full"
                      height="h-40"
                    />
                    <AccreditationImageUploader
                      label="Certificate Image"
                      value={item.certificateImage}
                      onChange={(url) => updateItem(idx, "certificateImage", url)}
                      getHospitalSlug={getHospitalSlug}
                      fileBaseName={MEDIA_FILE_BASE.accreditationCertificate}
                      fileIndex={idx}
                      onStageImage={(staged) => onStageAccreditationCertificate?.(idx, staged)}
                      onClearStagedImage={() => onClearStagedAccreditationCertificate?.(idx)}
                      width="w-full"
                      height="h-40"
                    />
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}
