"use client"

import React, { useEffect, useRef, useState } from "react"
import {
  Sparkles,
  Star,
  HelpCircle,
  Megaphone,
  Save,
  Pencil,
  Loader2,
  CheckCircle,
  AlertCircle,
} from "lucide-react"

import { DoctorsHeroSection } from "./DoctorsHeroSection"
import { DoctorsFeaturesSection } from "./DoctorsFeaturesSection"
import { DoctorsFAQSection } from "./DoctorsFAQSection"
import { DoctorsCTASection } from "./DoctorsCTASection"
import { LanguageTabs, type Language } from "../shared/LanguageTabs"
import { DOCTORS_PAGE_LOCALE_CODES } from "@/lib/pages/doctors/locales"
import {
  createEmptyDoctorsPageFormState,
  type DoctorsPageFormStateShape,
} from "@/lib/pages/doctors/form-types"

// ─── Section wrapper ──────────────────────────────────────────────────────────

interface SectionProps {
  id: string
  icon: React.ReactNode
  title: string
  description: string
  accent: "navy" | "green"
  children: React.ReactNode
  footer?: React.ReactNode
}

function Section({ id, icon, title, description, accent, children, footer }: SectionProps) {
  const bg = accent === "navy" ? "rgba(29,45,104,0.02)" : "rgba(43,182,115,0.02)"
  const iconBg = accent === "navy" ? "rgba(29,45,104,0.08)" : "rgba(43,182,115,0.10)"
  const iconColor = accent === "navy" ? "var(--brand-navy)" : "var(--brand-green)"

  return (
    <section
      className="bg-card rounded-2xl border border-border overflow-hidden"
      aria-labelledby={id}
    >
      <div
        className="flex items-center gap-3 px-6 py-4 border-b border-border"
        style={{ background: bg }}
      >
        <div
          className="w-8 h-8 rounded-xl flex items-center justify-center shrink-0"
          style={{ background: iconBg }}
        >
          <span style={{ color: iconColor }} aria-hidden="true">
            {icon}
          </span>
        </div>
        <div>
          <h2 id={id} className="text-sm font-bold text-foreground font-sans">
            {title}
          </h2>
          <p className="text-xs text-muted-foreground font-sans">{description}</p>
        </div>
      </div>
      <div className="p-6">{children}</div>
      {footer ? <div className="px-6 pb-6">{footer}</div> : null}
    </section>
  )
}

// ─── Main form ────────────────────────────────────────────────────────────────

export function DoctorsPageForm() {
  const [activeLanguage, setActiveLanguage] = useState<Language>("en")
  const [formByLanguage, setFormByLanguage] = useState<Record<Language, DoctorsPageFormStateShape>>({
    en: createEmptyDoctorsPageFormState(),
    tr: createEmptyDoctorsPageFormState(),
    ar: createEmptyDoctorsPageFormState(),
  })
  const [loading, setLoading] = useState(true)
  const [loadError, setLoadError] = useState<string | null>(null)
  const [saving, setSaving] = useState(false)
  const [savingSectionKey, setSavingSectionKey] = useState<keyof DoctorsPageFormStateShape | null>(null)
  const [sectionFeedback, setSectionFeedback] = useState<
    Partial<Record<keyof DoctorsPageFormStateShape, { type: "success" | "error"; message: string }>>
  >({})
  const sectionFeedbackTimersRef = useRef<Partial<Record<keyof DoctorsPageFormStateShape, ReturnType<typeof setTimeout>>>>({})
  const [isLockedForEditing, setIsLockedForEditing] = useState(false)
  const [saveSuccess, setSaveSuccess] = useState<string | null>(null)
  const [saveError, setSaveError] = useState<string | null>(null)
  const isFormLocked = loading || saving || savingSectionKey !== null || isLockedForEditing

  function getEnglishValidationErrors() {
    const en = formByLanguage.en
    const heroQuickStatsItems = en.hero.quickStats.map((item) => ({
      label: !item.label.trim(),
      value: !item.value.trim(),
    }))
    const heroHasQuickStatsItemError = heroQuickStatsItems.some((item) => item.label || item.value)
    const imageEyebrowItems = en.hero.imageEyebrow.map((item) => ({
      label: !item.label.trim(),
      value: !item.value.trim(),
      icon: !item.icon.trim(),
    }))
    const imageEyebrowHasItemError = imageEyebrowItems.some((item) => item.label || item.value || item.icon)
    const featureItems = en.features.features.map((item) => ({
      title: !item.title.trim(),
      description: !item.description.trim(),
      icon: !item.icon.trim(),
    }))
    const featureHasItemError = featureItems.some((item) => item.title || item.description || item.icon)
    const faqItems = en.faq.faqs.map((item) => ({
      question: !item.question.trim(),
      answer: !item.answer.trim(),
    }))
    const faqHasItemError = faqItems.some((item) => item.question || item.answer)

    return {
      hero: {
        eyebrow: !en.hero.eyebrow.trim(),
        title: !en.hero.title.trim(),
        description: !en.hero.description.trim(),
        quickStats: en.hero.quickStats.length === 0 || heroHasQuickStatsItemError,
        imageEyebrow: en.hero.imageEyebrow.length === 0 || imageEyebrowHasItemError,
      },
      features: {
        title: !en.features.title.trim(),
        subtitle: !en.features.subtitle.trim(),
        features: en.features.features.length === 0 || featureHasItemError,
      },
      faq: {
        title: !en.faq.title.trim(),
        faqs: en.faq.faqs.length === 0 || faqHasItemError,
      },
      cta: {
        eyebrow: !en.cta.eyebrow.trim(),
        title: !en.cta.title.trim(),
        description: !en.cta.description.trim(),
        primaryButtonText: !en.cta.primaryButtonText.trim(),
        primaryButtonLink: !en.cta.primaryButtonLink.trim(),
        secondaryButtonIcon: !en.cta.secondaryButtonIcon.trim(),
        secondaryButtonText: !en.cta.secondaryButtonText.trim(),
        secondaryButtonLink: !en.cta.secondaryButtonLink.trim(),
      },
    }
  }

  useEffect(() => {
    let cancelled = false

    async function load() {
      setLoading(true)
      setLoadError(null)
      try {
        const res = await fetch("/api/admin/doctors-page", { credentials: "include" })
        const data: {
          success?: boolean
          error?: string
          locales?: Partial<Record<Language, DoctorsPageFormStateShape>>
        } = await res.json()

        if (cancelled) return
        if (!res.ok || !data.success) {
          setLoadError(data.error ?? "Failed to load doctors page.")
          return
        }

        setFormByLanguage((prev) => {
          const next = { ...prev }
          for (const code of DOCTORS_PAGE_LOCALE_CODES) {
            const chunk = data.locales?.[code]
            if (chunk?.hero) next[code] = chunk
          }
          return next
        })
      } catch {
        if (!cancelled) setLoadError("Failed to load doctors page. Please try again.")
      } finally {
        if (!cancelled) setLoading(false)
      }
    }

    void load()
    return () => {
      cancelled = true
    }
  }, [])

  useEffect(() => {
    return () => {
      for (const timer of Object.values(sectionFeedbackTimersRef.current)) {
        if (timer) clearTimeout(timer)
      }
    }
  }, [])

  function showSectionFeedback(
    sectionKey: keyof DoctorsPageFormStateShape,
    type: "success" | "error",
    message: string
  ) {
    const existingTimer = sectionFeedbackTimersRef.current[sectionKey]
    if (existingTimer) clearTimeout(existingTimer)
    setSectionFeedback((prev) => ({
      ...prev,
      [sectionKey]: { type, message },
    }))
    sectionFeedbackTimersRef.current[sectionKey] = setTimeout(() => {
      setSectionFeedback((prev) => {
        const next = { ...prev }
        delete next[sectionKey]
        return next
      })
      delete sectionFeedbackTimersRef.current[sectionKey]
    }, 3500)
  }

  function updateSection<K extends keyof DoctorsPageFormStateShape>(
    key: K,
    value: DoctorsPageFormStateShape[K]
  ) {
    if (isFormLocked) return
    setFormByLanguage((prev) => ({
      ...prev,
      [activeLanguage]: { ...prev[activeLanguage], [key]: value },
    }))
    setSaveSuccess(null)
    setSaveError(null)
  }

  async function handleSave() {
    setSaving(true)
    setSaveSuccess(null)
    setSaveError(null)

    try {
      const payloadLocales: Record<Language, DoctorsPageFormStateShape> = {
        en: { ...formByLanguage.en },
        tr: { ...formByLanguage.tr },
        ar: { ...formByLanguage.ar },
      }
      const res = await fetch("/api/admin/doctors-page", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({ locales: payloadLocales }),
      })
      const data: { success?: boolean; error?: string } = await res.json()
      if (!res.ok || !data.success) {
        throw new Error(data.error ?? "Failed to save")
      }

      const refreshRes = await fetch("/api/admin/doctors-page", { credentials: "include" })
      const refreshData: {
        success?: boolean
        error?: string
        locales?: Partial<Record<Language, DoctorsPageFormStateShape>>
      } = await refreshRes.json()
      if (!refreshRes.ok || !refreshData.success) {
        throw new Error(refreshData.error ?? "Page saved, but failed to refresh latest data.")
      }
      setFormByLanguage((prev) => {
        const next = { ...prev }
        for (const code of DOCTORS_PAGE_LOCALE_CODES) {
          const chunk = refreshData.locales?.[code]
          if (chunk?.hero) next[code] = chunk
        }
        return next
      })

      setSaveSuccess("Doctors page saved successfully.")
      setIsLockedForEditing(true)
    } catch (error) {
      setActiveLanguage("en")
      setSaveError(
        error instanceof Error
          ? error.message
          : "Something went wrong. Please try again."
      )
    } finally {
      setSaving(false)
    }
  }

  async function handleSaveSection(sectionKey: keyof DoctorsPageFormStateShape) {
    setSavingSectionKey(sectionKey)
    setSaveSuccess(null)
    setSaveError(null)

    try {
      const payloadLocales: Record<Language, DoctorsPageFormStateShape> = {
        en: { ...formByLanguage.en },
        tr: { ...formByLanguage.tr },
        ar: { ...formByLanguage.ar },
      }
      const res = await fetch("/api/admin/doctors-page", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({ locales: payloadLocales, sectionKey }),
      })
      const data: { success?: boolean; error?: string } = await res.json()
      if (!res.ok || !data.success) throw new Error(data.error ?? "Failed to save section")

      const refreshRes = await fetch("/api/admin/doctors-page", { credentials: "include" })
      const refreshData: {
        success?: boolean
        error?: string
        locales?: Partial<Record<Language, DoctorsPageFormStateShape>>
      } = await refreshRes.json()
      if (!refreshRes.ok || !refreshData.success) {
        throw new Error(refreshData.error ?? "Section saved, but failed to refresh latest data.")
      }
      setFormByLanguage((prev) => {
        const next = { ...prev }
        for (const code of DOCTORS_PAGE_LOCALE_CODES) {
          const chunk = refreshData.locales?.[code]
          if (chunk?.hero) next[code] = chunk
        }
        return next
      })
      setSaveSuccess(`${String(sectionKey)} section saved successfully.`)
      showSectionFeedback(sectionKey, "success", "Section saved successfully.")
    } catch (error) {
      const errorMessage =
        error instanceof Error ? error.message : "Something went wrong. Please try again."
      setActiveLanguage("en")
      setSaveError(errorMessage)
      showSectionFeedback(sectionKey, "error", errorMessage)
    } finally {
      setSavingSectionKey(null)
    }
  }

  function renderSectionSaveButton(sectionKey: keyof DoctorsPageFormStateShape) {
    const isSavingThisSection = savingSectionKey === sectionKey
    const feedback = sectionFeedback[sectionKey]
    return (
      <div className="flex flex-col items-end gap-2">
        <button
          type="button"
          onClick={() => void handleSaveSection(sectionKey)}
          disabled={isFormLocked}
          className="flex items-center gap-2 px-4 py-2 rounded-xl text-xs font-bold font-sans text-white transition-all hover:brightness-105 active:scale-[0.98] disabled:opacity-60 disabled:cursor-not-allowed cursor-pointer"
          style={{ background: "var(--brand-navy)" }}
        >
          {isSavingThisSection ? (
            <>
              <Loader2 className="w-3.5 h-3.5 animate-spin" aria-hidden="true" />
              Saving section...
            </>
          ) : (
            <>
              <Save className="w-3.5 h-3.5" aria-hidden="true" />
              Save Section
            </>
          )}
        </button>
        {feedback ? (
          <div
            className="text-xs font-sans px-3 py-1.5 rounded-lg border max-w-[420px]"
            style={
              feedback.type === "success"
                ? { background: "rgba(43,182,115,0.08)", borderColor: "rgba(43,182,115,0.30)", color: "var(--brand-green)" }
                : { background: "rgba(239,68,68,0.08)", borderColor: "rgba(239,68,68,0.30)", color: "#dc2626" }
            }
            role="alert"
          >
            {feedback.message}
          </div>
        ) : null}
      </div>
    )
  }

  const form = formByLanguage[activeLanguage]

  return (
    <div className="flex flex-col gap-6">
      {loadError && (
        <div
          className="flex items-center gap-3 px-4 py-3 rounded-xl border text-sm font-sans"
          style={{
            background: "rgba(239,68,68,0.06)",
            borderColor: "rgba(239,68,68,0.30)",
            color: "#dc2626",
          }}
          role="alert"
        >
          <AlertCircle className="w-4 h-4 shrink-0" aria-hidden="true" />
          {loadError}
        </div>
      )}

      {/* Language Tabs */}
      <div
        className="bg-card rounded-2xl border border-border overflow-hidden"
        role="tabpanel"
        id={`language-panel-${activeLanguage}`}
        aria-labelledby={`language-tab-${activeLanguage}`}
      >
        <div
          className="flex items-center gap-2 px-6 py-3 border-b border-border"
          style={{ background: "rgba(29,45,104,0.02)" }}
        >
          <div
            className="w-7 h-7 rounded-lg flex items-center justify-center shrink-0 text-sm"
            style={{ background: "rgba(29,45,104,0.08)" }}
            aria-hidden="true"
          >
            🌐
          </div>
          <div>
            <p className="text-sm font-bold font-sans" style={{ color: "var(--brand-navy)" }}>
              Page Language
            </p>
            <p className="text-xs text-muted-foreground font-sans leading-none mt-0.5">
              English is required to save. Turkish and Arabic are optional.
            </p>
          </div>
        </div>
        <div className="px-6 py-4">
          <LanguageTabs
            activeLanguage={activeLanguage}
            onChange={(language) => {
              if (isFormLocked) return
              setActiveLanguage(language)
            }}
            disabled={isFormLocked}
          />
        </div>
      </div>

      {/* Section 1 — Hero */}
      <Section
        id="section-doctors-hero"
        icon={<Sparkles className="w-4 h-4" />}
        title="Hero Section"
        description="Eyebrow, title, description, and quick stats"
        accent="navy"
        footer={renderSectionSaveButton("hero")}
      >
        {loading ? (
          <p className="text-sm text-muted-foreground font-sans">Loading...</p>
        ) : (
          <fieldset disabled={isFormLocked} className="min-w-0">
            <DoctorsHeroSection
              value={form.hero}
              onChange={(v) => updateSection("hero", v)}
              validation={
                activeLanguage === "en"
                  ? {
                      ...getEnglishValidationErrors().hero,
                      imageEyebrowItems: formByLanguage.en.hero.imageEyebrow.map((item) => ({
                        label: !item.label.trim(),
                        value: !item.value.trim(),
                        icon: !item.icon.trim(),
                      })),
                      quickStatsItems: formByLanguage.en.hero.quickStats.map((item) => ({
                        label: !item.label.trim(),
                        value: !item.value.trim(),
                      })),
                    }
                  : undefined
              }
            />
          </fieldset>
        )}
      </Section>

      {/* Section 2 — Features */}
      <Section
        id="section-doctors-features"
        icon={<Star className="w-4 h-4" />}
        title="Features Section"
        description="Section title, subtitle, and a list of features with icons"
        accent="green"
        footer={renderSectionSaveButton("features")}
      >
        {loading ? (
          <p className="text-sm text-muted-foreground font-sans">Loading...</p>
        ) : (
          <fieldset disabled={isFormLocked} className="min-w-0">
            <DoctorsFeaturesSection
              value={form.features}
              onChange={(v) => updateSection("features", v)}
              validation={
                activeLanguage === "en"
                  ? {
                      ...getEnglishValidationErrors().features,
                      featureItems: formByLanguage.en.features.features.map((item) => ({
                        title: !item.title.trim(),
                        description: !item.description.trim(),
                        icon: !item.icon.trim(),
                      })),
                    }
                  : undefined
              }
            />
          </fieldset>
        )}
      </Section>

      {/* Section 3 — FAQ */}
      <Section
        id="section-doctors-faq"
        icon={<HelpCircle className="w-4 h-4" />}
        title="FAQ Section"
        description="Section title and a list of frequently asked questions"
        accent="navy"
        footer={renderSectionSaveButton("faq")}
      >
        {loading ? (
          <p className="text-sm text-muted-foreground font-sans">Loading...</p>
        ) : (
          <fieldset disabled={isFormLocked} className="min-w-0">
            <DoctorsFAQSection
              value={form.faq}
              onChange={(v) => updateSection("faq", v)}
              validation={
                activeLanguage === "en"
                  ? {
                      ...getEnglishValidationErrors().faq,
                      faqItems: formByLanguage.en.faq.faqs.map((item) => ({
                        question: !item.question.trim(),
                        answer: !item.answer.trim(),
                      })),
                    }
                  : undefined
              }
            />
          </fieldset>
        )}
      </Section>

      {/* Section 4 — CTA */}
      <Section
        id="section-doctors-cta"
        icon={<Megaphone className="w-4 h-4" />}
        title="CTA Section"
        description="Final conversion section with eyebrow, title, description, and two buttons"
        accent="green"
        footer={renderSectionSaveButton("cta")}
      >
        {loading ? (
          <p className="text-sm text-muted-foreground font-sans">Loading...</p>
        ) : (
          <fieldset disabled={isFormLocked} className="min-w-0">
            <DoctorsCTASection
              value={form.cta}
              onChange={(v) => updateSection("cta", v)}
              validation={
                activeLanguage === "en"
                  ? getEnglishValidationErrors().cta
                  : undefined
              }
            />
          </fieldset>
        )}
      </Section>

      {/* Feedback messages */}
      {saveSuccess && (
        <div
          className="flex items-center gap-3 px-4 py-3 rounded-xl border text-sm font-sans"
          style={{
            background: "rgba(43,182,115,0.08)",
            borderColor: "rgba(43,182,115,0.30)",
            color: "var(--brand-green)",
          }}
          role="alert"
        >
          <CheckCircle className="w-4 h-4 shrink-0" aria-hidden="true" />
          {saveSuccess}
        </div>
      )}

      {saveError && (
        <div
          className="flex items-center gap-3 px-4 py-3 rounded-xl border text-sm font-sans"
          style={{
            background: "rgba(239,68,68,0.06)",
            borderColor: "rgba(239,68,68,0.30)",
            color: "#dc2626",
          }}
          role="alert"
        >
          <AlertCircle className="w-4 h-4 shrink-0" aria-hidden="true" />
          {saveError}
        </div>
      )}

      {/* Save button */}
      <div className="flex items-center justify-end gap-3 pb-2">
        {isLockedForEditing && (
          <button
            type="button"
            onClick={() => {
              setIsLockedForEditing(false)
              setSaveSuccess(null)
              setSaveError(null)
            }}
            disabled={saving || loading}
            className="flex items-center gap-2 px-6 py-3 rounded-xl text-sm font-bold font-sans border border-border text-foreground bg-card transition-all hover:brightness-105 active:scale-[0.98] disabled:opacity-60 disabled:cursor-not-allowed cursor-pointer"
          >
            <Pencil className="w-4 h-4" aria-hidden="true" />
            Edit Page
          </button>
        )}
        <button
          type="button"
          onClick={() => void handleSave()}
          disabled={isFormLocked}
          className="flex items-center gap-2 px-6 py-3 rounded-xl text-sm font-bold font-sans text-white transition-all hover:brightness-105 active:scale-[0.98] disabled:opacity-60 disabled:cursor-not-allowed cursor-pointer"
          style={{ background: "var(--brand-navy)" }}
        >
          {saving ? (
            <>
              <Loader2 className="w-4 h-4 animate-spin" aria-hidden="true" />
              Saving...
            </>
          ) : (
            <>
              <Save className="w-4 h-4" aria-hidden="true" />
              Save Changes
            </>
          )}
        </button>
      </div>

    </div>
  )
}
