"use client"

import { ImagePlus, X, Star, MapPin, Tag } 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 HospitalBasicInfoData {
  name: string
  slug: string
  /** Localized hospital kind label (per locale form tab) */
  type: string
  image: string
  imagePublicId: string
  rating: number | ""
  reviewCount: number | ""
  badge: string
  /** Calendar year (e.g. 1998); empty string if unknown */
  foundedYear: number | ""
  bedsCount: number | ""
  departmentsCount: number | ""
  doctorsCount: number | ""
  patientsPerYear: number | ""
  location: string
  isFeatured: boolean
}

/** Persisted on `Hospital` — English-only fields edited on the EN tab */
export type HospitalBasicInfoStoredFields = Omit<HospitalBasicInfoData, "name" | "location" | "type">

interface Props {
  value: HospitalBasicInfoData
  onChange: (value: HospitalBasicInfoData) => void
  onSlugBlur?: (slug: string) => void
  sharedFieldsLocked?: boolean
  checkingSlug?: boolean
  slugError?: string | null
  slugAvailable?: boolean | null
  invalidFields?: {
    name?: boolean
    slug?: boolean
    image?: boolean
    rating?: boolean
    reviewCount?: boolean
    location?: boolean
  }
  getHospitalSlug?: () => string
  onStageMainPhoto?: (staged: StagedImage) => void
  onClearStagedMainPhoto?: () => void
}

function HospitalImageUploader({
  value,
  getHospitalSlug,
  onStageMainPhoto,
  onClearStagedMainPhoto,
  onChange,
  invalid = false,
  disabled = false,
}: {
  value: string
  imagePublicId: string
  getHospitalSlug?: () => string
  onStageMainPhoto?: (staged: StagedImage) => void
  onClearStagedMainPhoto?: () => void
  onChange: (url: string, publicId: string) => void
  invalid?: boolean
  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 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: MEDIA_FILE_BASE.mainPhoto })
      onStageMainPhoto?.(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-xs font-bold text-foreground font-sans uppercase tracking-wider">
        Hospital Main Image
      </label>
      {value ? (
        <div className={`relative w-40 h-28 rounded-2xl overflow-hidden border bg-card ${invalid ? "border-red-500" : "border-border"}`}>
          <img src={value} alt="Hospital preview" className="w-full h-full object-cover" />
          <button
            type="button"
            disabled={disabled}
            onClick={() => {
              onClearStagedMainPhoto?.()
              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 disabled:opacity-40 disabled:cursor-not-allowed"
            aria-label="Remove image"
          >
            <X className="w-3.5 h-3.5" aria-hidden="true" />
          </button>
        </div>
      ) : (
        <div
          role={disabled ? undefined : "button"}
          tabIndex={disabled ? undefined : 0}
          onClick={() => !disabled && inputRef.current?.click()}
          onKeyDown={(e) => !disabled && e.key === "Enter" && inputRef.current?.click()}
          onDragOver={(e) => {
            if (disabled) return
            e.preventDefault()
            setDragOver(true)
          }}
          onDragLeave={() => setDragOver(false)}
          onDrop={(e) => {
            e.preventDefault()
            setDragOver(false)
            if (disabled) return
            const file = e.dataTransfer.files[0]
            if (file) handleFile(file)
          }}
          className={`flex flex-col items-center justify-center gap-2 w-40 h-28 rounded-2xl border-2 border-dashed transition-all ${disabled ? "opacity-50 cursor-not-allowed" : "cursor-pointer"}`}
          style={{
            borderColor: invalid ? "#ef4444" : dragOver ? "var(--brand-green)" : "var(--border)",
            background: dragOver ? "rgba(43,182,115,0.04)" : "var(--card)",
          }}
          aria-label="Upload hospital image"
        >
          <>
              <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>}
      {invalid && !value && <p className="text-xs font-sans text-red-500">Hospital image is required.</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>
  )
}

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 inputClassInvalid =
  "w-full bg-card border border-red-500 rounded-xl px-4 py-2.5 text-sm text-foreground font-sans placeholder:text-muted-foreground outline-none focus:ring-2 focus:ring-red-200 focus:border-red-500 transition-colors"

export function HospitalBasicInfo({
  value,
  onChange,
  onSlugBlur,
  invalidFields,
  sharedFieldsLocked = false,
  checkingSlug = false,
  slugError = null,
  slugAvailable = null,
  getHospitalSlug,
  onStageMainPhoto,
  onClearStagedMainPhoto,
}: Props) {
  function set<K extends keyof HospitalBasicInfoData>(key: K, val: HospitalBasicInfoData[K]) {
    onChange({ ...value, [key]: val })
  }

  return (
    <div className="flex flex-col gap-5">
      
      {/* Slug + Type */}
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
        <div className="flex flex-col gap-1.5">
          <label htmlFor="hospital-slug" className="text-xs font-bold text-foreground font-sans uppercase tracking-wider flex items-center gap-1">
            <Tag className="w-3 h-3" style={{ color: "var(--brand-navy)" }} aria-hidden="true" />
            Slug <span className="text-red-500">*</span>
          </label>
          <input
            id="hospital-slug"
            type="text"
            value={value.slug}
            onChange={(e) => set("slug", e.target.value.trim().toLowerCase().replace(/\s+/g, "-"))}
            onBlur={(e) => onSlugBlur?.(e.currentTarget.value)}
            disabled={sharedFieldsLocked}
            placeholder="e.g. istanbul-medical-center"
            className={invalidFields?.slug ? inputClassInvalid : inputClass}
          />
          {invalidFields?.slug && <p className="text-xs font-sans text-red-500">Slug is required.</p>}
          {!invalidFields?.slug && slugError && <p className="text-xs font-sans text-red-500">{slugError}</p>}
          {!invalidFields?.slug && !slugError && slugAvailable && <p className="text-xs font-sans text-green-600">Slug is available</p>}
          {!invalidFields?.slug && checkingSlug && <p className="text-xs font-sans text-muted-foreground">Checking slug availability...</p>}
          <p className="text-[11px] text-muted-foreground font-sans">
            Used in the URL. Auto-formatted to lowercase with dashes.
            {sharedFieldsLocked ? " Editable on English only." : ""}
          </p>
        </div>

        <div className="flex flex-col gap-1.5">
          <label htmlFor="hospital-type" className="text-xs font-bold text-foreground font-sans uppercase tracking-wider">
            Type
          </label>
          <input
            id="hospital-type"
            type="text"
            value={value.type}
            onChange={(e) => set("type", e.target.value)}
            placeholder="e.g. Private Hospital, Clinic, Medical Center"
            className={inputClass}
          />
        </div>
      </div>

      {/* Founded year + facility metrics */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
        <div className="flex flex-col gap-1.5">
          <label htmlFor="hospital-founded-year" className="text-xs font-bold text-foreground font-sans uppercase tracking-wider">
            Founded year
          </label>
          <input
            id="hospital-founded-year"
            type="number"
            min={1800}
            max={new Date().getFullYear() + 1}
            step={1}
            value={value.foundedYear === "" ? "" : value.foundedYear}
            onChange={(e) => {
              const v = e.target.value
              if (v === "") {
                set("foundedYear", "")
                return
              }
              const n = Number(v)
              if (!Number.isNaN(n)) set("foundedYear", Math.trunc(n))
            }}
            placeholder="e.g. 1998"
            disabled={sharedFieldsLocked}
            className={inputClass}
          />
        </div>
        <div className="flex flex-col gap-1.5">
          <label htmlFor="hospital-beds" className="text-xs font-bold text-foreground font-sans uppercase tracking-wider">
            Beds count
          </label>
          <input
            id="hospital-beds"
            type="number"
            min={0}
            value={value.bedsCount === "" ? "" : value.bedsCount}
            onChange={(e) => {
              const v = e.target.value
              if (v === "") {
                set("bedsCount", "")
                return
              }
              const n = Number(v)
              if (!Number.isNaN(n)) set("bedsCount", Math.max(0, Math.trunc(n)))
            }}
            placeholder="e.g. 120"
            disabled={sharedFieldsLocked}
            className={inputClass}
          />
        </div>
        <div className="flex flex-col gap-1.5">
          <label htmlFor="hospital-depts-count" className="text-xs font-bold text-foreground font-sans uppercase tracking-wider">
            Departments count
          </label>
          <input
            id="hospital-depts-count"
            type="number"
            min={0}
            value={value.departmentsCount === "" ? "" : value.departmentsCount}
            onChange={(e) => {
              const v = e.target.value
              if (v === "") {
                set("departmentsCount", "")
                return
              }
              const n = Number(v)
              if (!Number.isNaN(n)) set("departmentsCount", Math.max(0, Math.trunc(n)))
            }}
            placeholder="e.g. 24"
            disabled={sharedFieldsLocked}
            className={inputClass}
          />
        </div>
        <div className="flex flex-col gap-1.5">
          <label htmlFor="hospital-doctors-count" className="text-xs font-bold text-foreground font-sans uppercase tracking-wider">
            Doctors count
          </label>
          <input
            id="hospital-doctors-count"
            type="number"
            min={0}
            value={value.doctorsCount === "" ? "" : value.doctorsCount}
            onChange={(e) => {
              const v = e.target.value
              if (v === "") {
                set("doctorsCount", "")
                return
              }
              const n = Number(v)
              if (!Number.isNaN(n)) set("doctorsCount", Math.max(0, Math.trunc(n)))
            }}
            placeholder="e.g. 85"
            disabled={sharedFieldsLocked}
            className={inputClass}
          />
        </div>
        <div className="flex flex-col gap-1.5">
          <label htmlFor="hospital-patients-yr" className="text-xs font-bold text-foreground font-sans uppercase tracking-wider">
            Patients / yr count
          </label>
          <input
            id="hospital-patients-yr"
            type="number"
            min={0}
            value={value.patientsPerYear === "" ? "" : value.patientsPerYear}
            onChange={(e) => {
              const v = e.target.value
              if (v === "") {
                set("patientsPerYear", "")
                return
              }
              const n = Number(v)
              if (!Number.isNaN(n)) set("patientsPerYear", Math.max(0, Math.trunc(n)))
            }}
            placeholder="e.g. 12000"
            disabled={sharedFieldsLocked}
            className={inputClass}
          />
        </div>
      </div>

      {/* Image + Name row */}
      <div className="flex flex-col sm:flex-row gap-5 items-start">
        <HospitalImageUploader
          value={value.image}
          imagePublicId={value.imagePublicId}
          getHospitalSlug={getHospitalSlug ?? (() => value.slug)}
          onStageMainPhoto={onStageMainPhoto}
          onClearStagedMainPhoto={onClearStagedMainPhoto}
          invalid={invalidFields?.image}
          disabled={sharedFieldsLocked}
          onChange={(url, publicId) => onChange({ ...value, image: url, imagePublicId: publicId })}
        />

        <div className="flex-1 flex flex-col gap-4 w-full">
          {/* Name */}
          <div className="flex flex-col gap-1.5">
            <label htmlFor="hospital-name" className="text-xs font-bold text-foreground font-sans uppercase tracking-wider">
              Hospital Name
            </label>
            <input
              id="hospital-name"
              type="text"
              value={value.name}
              onChange={(e) => set("name", e.target.value)}
              placeholder="e.g. Istanbul Medical Center"
              className={invalidFields?.name ? inputClassInvalid : inputClass}
            />
            {invalidFields?.name && <p className="text-xs font-sans text-red-500">Hospital name is required.</p>}
          </div>

          {/* Rating + Review Count */}
          <div className="grid grid-cols-2 gap-3">
            <div className="flex flex-col gap-1.5">
              <label htmlFor="hospital-rating" className="text-xs font-bold text-foreground font-sans uppercase tracking-wider flex items-center gap-1">
                <Star className="w-3 h-3" style={{ color: "var(--brand-green)" }} aria-hidden="true" />
                Rating
              </label>
              <input
                id="hospital-rating"
                type="number"
                min={0}
                max={5}
                step={0.1}
                value={value.rating === "" ? "" : value.rating}
                onChange={(e) => {
                  const v = e.target.value
                  if (v === "") { set("rating", ""); return }
                  const n = Number(v)
                  if (!Number.isNaN(n)) set("rating", Math.min(5, Math.max(0, n)))
                }}
                placeholder="e.g. 4.8"
                disabled={sharedFieldsLocked}
                className={invalidFields?.rating ? inputClassInvalid : inputClass}
              />
              {invalidFields?.rating && <p className="text-xs font-sans text-red-500">Rating is required.</p>}
            </div>
            <div className="flex flex-col gap-1.5">
              <label htmlFor="hospital-review-count" className="text-xs font-bold text-foreground font-sans uppercase tracking-wider">
                Review Count
              </label>
              <input
                id="hospital-review-count"
                type="number"
                min={0}
                value={value.reviewCount === "" ? "" : value.reviewCount}
                onChange={(e) => {
                  const v = e.target.value
                  if (v === "") { set("reviewCount", ""); return }
                  const n = Number(v)
                  if (!Number.isNaN(n)) set("reviewCount", n)
                }}
                placeholder="e.g. 240"
                disabled={sharedFieldsLocked}
                className={invalidFields?.reviewCount ? inputClassInvalid : inputClass}
              />
              {invalidFields?.reviewCount && <p className="text-xs font-sans text-red-500">Review count is required.</p>}
            </div>
          </div>
        </div>
      </div>


      {/* Badge + Location */}
      <div className="grid  gap-4">
        
        <div className="flex flex-col gap-1.5">
          <label htmlFor="hospital-location" className="text-xs font-bold text-foreground font-sans uppercase tracking-wider flex items-center gap-1">
            <MapPin className="w-3 h-3" style={{ color: "var(--brand-navy)" }} aria-hidden="true" />
            Location
          </label>
          <input
            id="hospital-location"
            type="text"
            value={value.location}
            onChange={(e) => set("location", e.target.value)}
            placeholder="e.g. Istanbul, Turkey"
            className={invalidFields?.location ? inputClassInvalid : inputClass}
          />
          {invalidFields?.location && <p className="text-xs font-sans text-red-500">Location is required.</p>}
        </div>
      </div>

      {/* Featured toggle */}
      <div
        className={`flex items-center justify-between gap-4 px-4 py-3 rounded-xl border border-border bg-card ${sharedFieldsLocked ? "opacity-70" : ""}`}
      >
        <div className="flex items-center gap-2.5">
          <Star className="w-4 h-4" style={{ color: "var(--brand-navy)" }} aria-hidden="true" />
          <div>
            <p className="text-sm font-semibold text-foreground font-sans">Featured Hospital</p>
            <p className="text-xs text-muted-foreground font-sans">Pin this hospital to appear in featured sections</p>
            {sharedFieldsLocked ? (
              <p className="text-[10px] text-muted-foreground font-sans mt-1">Editable on English only</p>
            ) : null}
          </div>
        </div>
        <button
          type="button"
          role="switch"
          aria-checked={value.isFeatured}
          disabled={sharedFieldsLocked}
          onClick={() => !sharedFieldsLocked && set("isFeatured", !value.isFeatured)}
          className="relative w-11 h-6 rounded-full transition-colors duration-200 shrink-0 focus:outline-none focus:ring-2 focus:ring-[#2BB673]/40 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
          style={{ background: value.isFeatured ? "var(--brand-green)" : "var(--border)" }}
        >
          <span
            className="absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full shadow-sm transition-transform duration-200"
            style={{ transform: value.isFeatured ? "translateX(20px)" : "translateX(0px)" }}
          />
          <span className="sr-only">{value.isFeatured ? "Featured" : "Not featured"}</span>
        </button>
      </div>
    </div>
  )
}
