"use client"

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

export interface Hospital {
  location: string
  name: string
  description: string
  image: string
  features: string[]
  buttonText: string
  buttonLink: string
}

export interface HospitalsSectionData {
  title: string
  subtitle: string
  hospitals: Hospital[]
}

interface Props {
  value: HospitalsSectionData
  onChange: (value: HospitalsSectionData) => void
  showValidation?: boolean
  defaultSharedData?: HospitalsSectionData
  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 HospitalsSection({
  value,
  onChange,
  showValidation = false,
  defaultSharedData,
  isDefaultLanguage = false,
}: Props) {
  const { registerStaged, clearStaged } = useCmsPagePending()

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

  function addHospital() {
    set("hospitals", [...value.hospitals, { location: "", name: "", description: "", image: "", features: [], buttonText: "", buttonLink: "" }])
  }

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

  function updateHospital<K extends keyof Hospital>(i: number, field: K, val: Hospital[K]) {
    set("hospitals", value.hospitals.map((h, idx) => (idx === i ? { ...h, [field]: val } : h)))
  }

  function addFeature(hi: number) {
    const h = value.hospitals[hi]
    updateHospital(hi, "features", [...h.features, ""])
  }

  function removeFeature(hi: number, fi: number) {
    const h = value.hospitals[hi]
    updateHospital(hi, "features", h.features.filter((_, idx) => idx !== fi))
  }

  function updateFeature(hi: number, fi: number, val: string) {
    const h = value.hospitals[hi]
    updateHospital(hi, "features", h.features.map((f, idx) => (idx === fi ? val : f)))
  }

  return (
    <div className="flex flex-col gap-5">
      <div className="grid grid-cols-2 gap-4">
        <div className="flex flex-col gap-1.5">
          <Label>Title</Label>
          <input type="text" value={value.title} onChange={(e) => set("title", e.target.value)} placeholder="e.g. Our Partner Hospitals" className={fieldClass(showValidation && !value.title.trim())} />
        </div>
        <div className="flex flex-col gap-1.5">
          <Label>Subtitle</Label>
          <input type="text" value={value.subtitle} onChange={(e) => set("subtitle", e.target.value)} placeholder="e.g. State-of-the-art facilities" className={fieldClass(showValidation && !value.subtitle.trim())} />
        </div>
      </div>

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

        {value.hospitals.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 hospitals yet.</p>
            <button type="button" onClick={addHospital} className="text-xs cursor-pointer font-semibold font-sans" style={{ color: "var(--brand-green)" }}>
              Add your first hospital
            </button>
          </div>
        ) : (
          <div className="flex flex-col gap-4">
            {value.hospitals.map((h, hi) => (
              <div key={hi} className="flex flex-col gap-4 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)" }}>
                    Hospital {hi + 1}
                  </span>
                  <button type="button" onClick={() => removeHospital(hi)} className="p-1.5 cursor-pointer rounded-lg text-muted-foreground hover:text-red-500 hover:bg-red-50 transition-colors" aria-label={`Remove hospital ${hi + 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">Name</label>
                    <input type="text" value={h.name} onChange={(e) => updateHospital(hi, "name", e.target.value)} placeholder="Hospital name..." className={fieldClass(showValidation && !h.name.trim())} />
                  </div>
                  <div className="flex flex-col gap-1.5">
                    <label className="text-xs font-semibold text-muted-foreground font-sans">Location</label>
                    <input type="text" value={h.location} onChange={(e) => updateHospital(hi, "location", e.target.value)} placeholder="e.g. Istanbul, Turkey" className={fieldClass(showValidation && !h.location.trim())} />
                  </div>
                </div>

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

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

                {/* Features */}
                <div className={`flex flex-col gap-2 rounded-xl ${showValidation && h.features.length === 0 ? "border border-red-300 p-2 bg-red-50/40" : ""}`}>
                  <div className="flex items-center justify-between">
                    <label className="text-xs font-semibold text-muted-foreground font-sans uppercase tracking-wider">Features</label>
                    <button type="button" onClick={() => addFeature(hi)} className="flex cursor-pointer items-center gap-1 px-2.5 py-1 rounded-lg text-xs font-semibold font-sans" style={{ background: "rgba(43,182,115,0.10)", color: "var(--brand-green)" }}>
                      <Plus className="w-3 h-3" aria-hidden="true" />
                      Add
                    </button>
                  </div>
                  {h.features.map((feat, fi) => (
                    <div key={fi} className="flex items-center gap-2">
                      <input type="text" value={feat} onChange={(e) => updateFeature(hi, fi, e.target.value)} placeholder="Feature text..." className={fieldClass(showValidation && !feat.trim())} />
                      <button type="button" onClick={() => removeFeature(hi, fi)} className="p-1.5 cursor-pointer rounded-lg text-muted-foreground hover:text-red-500 hover:bg-red-50 transition-colors shrink-0" aria-label="Remove feature">
                        <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
                      </button>
                    </div>
                  ))}
                </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">Button Text</label>
                    <input type="text" value={h.buttonText} onChange={(e) => updateHospital(hi, "buttonText", e.target.value)} placeholder="e.g. Learn More" className={fieldClass(showValidation && !h.buttonText.trim())} />
                  </div>
                  <div className="flex flex-col gap-1.5">
                    <label className="text-xs font-semibold text-muted-foreground font-sans">Button Link</label>
                    <input type="text" value={h.buttonLink} onChange={(e) => updateHospital(hi, "buttonLink", e.target.value)} placeholder="e.g. /hospitals/istanbul" className={fieldClass(showValidation && !h.buttonLink.trim())} />
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}
