"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 Certification {
  name: string
  description: string
  status: string
  issuer: string
  year: string
  image: string
}

export interface CertificationsSectionData {
  title: string
  subtitle: string
  certifications: Certification[]
}

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

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

  function addCert() {
    set("certifications", [...value.certifications, { name: "", description: "", status: "VERIFIED", issuer: "", year: "", image: "" }])
  }

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

  function updateCert(i: number, field: keyof Certification, val: string) {
    set("certifications", value.certifications.map((c, idx) => (idx === i ? { ...c, [field]: val } : c)))
  }

  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 Certifications" 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. Internationally accredited" className={fieldClass(showValidation && !value.subtitle.trim())} />
        </div>
      </div>

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

        {value.certifications.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 certifications yet.</p>
            <button type="button" onClick={addCert} className="text-xs cursor-pointer font-semibold font-sans" style={{ color: "var(--brand-green)" }}>
              Add your first certification
            </button>
          </div>
        ) : (
          <div className="flex flex-col gap-3">
            {value.certifications.map((cert, 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)" }}>
                    Certification {i + 1}
                  </span>
                  <div className="flex items-center gap-2">
                    <span
                      className="text-[10px] font-bold font-sans px-2 py-0.5 rounded-full uppercase tracking-wider"
                      style={{ background: "rgba(43,182,115,0.12)", color: "var(--brand-green)" }}
                    >
                      {cert.status || "VERIFIED"}
                    </span>
                    <button type="button" onClick={() => removeCert(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 certification ${i + 1}`}>
                      <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
                    </button>
                  </div>
                </div>

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

                <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={cert.name} onChange={(e) => updateCert(i, "name", e.target.value)} placeholder="Certification name..." className={fieldClass(showValidation && !cert.name.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={cert.description} onChange={(e) => updateCert(i, "description", e.target.value)} placeholder="Brief description..." rows={2} className={`${fieldClass(showValidation && !cert.description.trim())} resize-none leading-relaxed`} />
                </div>
                <div className="grid grid-cols-3 gap-3">
                  <div className="flex flex-col gap-1.5">
                    <label className="text-xs font-semibold text-muted-foreground font-sans">Status</label>
                    <input type="text" value={cert.status} onChange={(e) => updateCert(i, "status", e.target.value)} placeholder="VERIFIED" className={fieldClass(showValidation && !cert.status.trim())} />
                  </div>
                  <div className="flex flex-col gap-1.5">
                    <label className="text-xs font-semibold text-muted-foreground font-sans">Issuer</label>
                    <input type="text" value={cert.issuer} onChange={(e) => updateCert(i, "issuer", e.target.value)} placeholder="e.g. ISO" className={fieldClass(showValidation && !cert.issuer.trim())} />
                  </div>
                  <div className="flex flex-col gap-1.5">
                    <label className="text-xs font-semibold text-muted-foreground font-sans">Year</label>
                    <input type="text" value={cert.year} onChange={(e) => updateCert(i, "year", e.target.value)} placeholder="e.g. 2023" className={fieldClass(showValidation && !cert.year.trim())} />
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}
