"use client"

import { Plus, Trash2, Star, Sparkles } from "lucide-react"

export interface HospitalReviewItem {
  rating: number | ""
  patientName: string
  country: string
  reviewText: string
  treatment: string
  date: string
  isFeatured: boolean
}

export interface HospitalReviewsData {
  eyebrow: string
  title: string
  reviews: HospitalReviewItem[]
}

interface Props {
  value: HospitalReviewsData
  onChange: (value: HospitalReviewsData) => void
  showValidationError?: boolean
}

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 = (invalid: boolean) =>
  `w-full bg-muted border bg-white rounded-xl px-3 py-2 text-sm text-foreground font-sans placeholder:text-muted-foreground outline-none transition-colors resize-none leading-relaxed ${
    invalid ? "border-red-500 focus:ring-2 focus:ring-red-200 focus:border-red-500" : "border-border focus:ring-2 focus:ring-[#2BB673]/30 focus:border-[#2BB673]"
  }`

function FeaturedToggle({
  checked,
  onChange,
  ariaLabel,
}: {
  checked: boolean
  onChange: (next: boolean) => void
  ariaLabel: string
}) {
  return (
    <button
      type="button"
      role="switch"
      aria-checked={checked}
      aria-label={ariaLabel}
      onClick={() => onChange(!checked)}
      className="group inline-flex items-center gap-2 px-2.5 py-1.5 rounded-full border text-xs font-bold font-sans cursor-pointer transition-all hover:brightness-105 active:scale-[0.98]"
      style={
        checked
          ? {
              background: "linear-gradient(135deg, #F59E0B, #FBBF24)",
              color: "#fff",
              borderColor: "transparent",
              boxShadow: "0 4px 12px rgba(245,158,11,0.30)",
            }
          : {
              background: "var(--card)",
              color: "var(--muted-foreground)",
              borderColor: "var(--border)",
            }
      }
    >
      <span
        className="w-4 h-4 rounded-full flex items-center justify-center transition-colors"
        style={{
          background: checked ? "rgba(255,255,255,0.25)" : "var(--muted)",
          color: checked ? "#fff" : "var(--muted-foreground)",
        }}
        aria-hidden="true"
      >
        <Sparkles className="w-2.5 h-2.5" />
      </span>
      <span className="uppercase tracking-wider">
        {checked ? "Featured" : "Mark as Featured"}
      </span>
    </button>
  )
}

function StarRatingPicker({
  value,
  onChange,
  invalid = false,
}: {
  value: number | ""
  onChange: (v: number | "") => void
  invalid?: boolean
}) {
  const intVal =
    value === ""
      ? ""
      : typeof value === "number" && Number.isFinite(value)
        ? Math.round(Math.min(5, Math.max(1, value)))
        : ""

  return (
    <div
      className={`flex items-center gap-1 rounded-lg px-1 py-0.5 ${invalid ? "border border-red-500" : ""}`}
      role="group"
      aria-label="Rating"
    >
      {[1, 2, 3, 4, 5].map((n) => (
        <button
          key={n}
          type="button"
          onClick={() => onChange(intVal === n ? "" : n)}
          aria-label={`${n} star${n !== 1 ? "s" : ""}`}
          aria-pressed={intVal === n}
          className="cursor-pointer transition-transform hover:scale-110"
        >
          <Star
            className="w-5 h-5"
            style={{
              color: intVal !== "" && n <= intVal ? "#F59E0B" : "var(--border)",
              fill: intVal !== "" && n <= intVal ? "#F59E0B" : "transparent",
            }}
            aria-hidden="true"
          />
        </button>
      ))}
      {intVal !== "" && (
        <span className="text-xs font-semibold font-sans ml-1" style={{ color: "#F59E0B" }}>
          {intVal}.0
        </span>
      )}
    </div>
  )
}

export function HospitalReviewsSection({ value, onChange, showValidationError = false }: Props) {
  function set<K extends keyof HospitalReviewsData>(key: K, val: HospitalReviewsData[K]) {
    onChange({ ...value, [key]: val })
  }

  function updateReview(idx: number, field: keyof HospitalReviewItem, val: string | number | "" | boolean) {
    const updated = value.reviews.map((r, i) => (i === idx ? { ...r, [field]: val } : r))
    set("reviews", updated)
  }

  function addReview() {
    set("reviews", [
      ...value.reviews,
      { rating: "", patientName: "", country: "", reviewText: "", treatment: "", date: "", isFeatured: false },
    ])
  }

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

  return (
    <div className="flex flex-col gap-5">
      <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-2 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. Patient Stories" 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. What Our Patients Say" className={inputClass} />
          </div>
        </div>
      </div>

      <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">
            Patient Reviews ({value.reviews.length})
          </label>
          <button
            type="button"
            onClick={addReview}
            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 Review
          </button>
        </div>

        {value.reviews.length === 0 ? (
          <div
            className="flex flex-col items-center justify-center gap-2 py-8 rounded-xl border border-dashed"
            style={{
              borderColor:
                showValidationError ? "#ef4444" : "var(--border)",
            }}
          >
            <p className="text-xs text-muted-foreground font-sans">
              {showValidationError ? "At least one review is required." : "No patient reviews added yet."}
            </p>
            <button
              type="button"
              onClick={addReview}
              className="text-xs cursor-pointer font-semibold font-sans"
              style={{ color: "var(--brand-green)" }}
            >
              Add your first review
            </button>
          </div>
        ) : (
          <div className="flex flex-col gap-4">
            {value.reviews.map((review, idx) => {
              const v = showValidationError
              return (
                <div key={idx} className="rounded-2xl border border-border bg-card overflow-hidden">
                  <div
                    className="flex items-center justify-between gap-3 px-4 py-2.5 border-b border-border flex-wrap"
                    style={{
                      background: review.isFeatured
                        ? "linear-gradient(135deg, rgba(245,158,11,0.10), rgba(43,182,115,0.04))"
                        : "rgba(43,182,115,0.02)",
                    }}
                  >
                    <div className="flex items-center gap-2 flex-wrap">
                      <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)" }}
                      >
                        Review {idx + 1}
                      </span>
                      <StarRatingPicker
                        value={review.rating === "" ? "" : Math.round(Number(review.rating)) || ""}
                        onChange={(stars) =>
                          updateReview(idx, "rating", stars === "" ? "" : stars)
                        }
                        invalid={v && review.rating === ""}
                      />
                    </div>
                    <div className="flex items-center gap-2">
                      <FeaturedToggle
                        checked={review.isFeatured}
                        onChange={(next) => updateReview(idx, "isFeatured", next)}
                        ariaLabel={`Mark review ${idx + 1} as featured`}
                      />
                      <button
                        type="button"
                        onClick={() => removeReview(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 review ${idx + 1}`}
                      >
                        <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
                      </button>
                    </div>
                  </div>

                  <div className="p-4 flex flex-col gap-3">
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                      <div className="flex flex-col gap-1">
                        <label className="text-[10px] font-bold text-muted-foreground font-sans uppercase tracking-wider">Patient Name</label>
                        <input
                          type="text"
                          value={review.patientName}
                          onChange={(e) => updateReview(idx, "patientName", e.target.value)}
                          placeholder="e.g. Ahmed K."
                          className={listFieldClass(v && review.patientName.trim() === "")}
                          aria-label={`Review ${idx + 1} patient name`}
                        />
                      </div>
                      <div className="flex flex-col gap-1">
                        <label className="text-[10px] font-bold text-muted-foreground font-sans uppercase tracking-wider">Country</label>
                        <input
                          type="text"
                          value={review.country}
                          onChange={(e) => updateReview(idx, "country", e.target.value)}
                          placeholder="e.g. Saudi Arabia"
                          className={listFieldClass(v && review.country.trim() === "")}
                          aria-label={`Review ${idx + 1} country`}
                        />
                      </div>
                    </div>
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                      <div className="flex flex-col gap-1">
                        <label className="text-[10px] font-bold text-muted-foreground font-sans uppercase tracking-wider">Treatment</label>
                        <input
                          type="text"
                          value={review.treatment}
                          onChange={(e) => updateReview(idx, "treatment", e.target.value)}
                          placeholder="e.g. Hair Transplant"
                          className={listFieldClass(v && review.treatment.trim() === "")}
                          aria-label={`Review ${idx + 1} treatment`}
                        />
                      </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={review.date}
                          onChange={(e) => updateReview(idx, "date", e.target.value)}
                          className={listFieldClass(v && review.date.trim() === "")}
                          aria-label={`Review ${idx + 1} date`}
                        />
                      </div>
                    </div>
                    <div className="flex flex-col gap-1">
                      <label className="text-[10px] font-bold text-muted-foreground font-sans uppercase tracking-wider">Review Content</label>
                      <textarea
                        value={review.reviewText}
                        onChange={(e) => updateReview(idx, "reviewText", e.target.value)}
                        placeholder="Patient review text..."
                        rows={3}
                        className={`${listFieldClass(v && review.reviewText.trim() === "")} resize-none`}
                        aria-label={`Review ${idx + 1} content`}
                      />
                    </div>
                  </div>
                </div>
              )
            })}
          </div>
        )}
        {showValidationError && (
          <p className="text-xs font-sans text-red-500">
            Please add at least one complete patient review when publishing.
          </p>
        )}
      </div>
    </div>
  )
}
