"use client"

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

export interface ReviewItem {
  patientName: string
  country: string
  content: string
  rating: number | ""
  treatment: string
  date: string
}

interface Props {
  value: ReviewItem[]
  onChange: (value: ReviewItem[]) => void
  showValidationError?: boolean
  sharedValuesLocked?: boolean
}

function StarRatingPicker({
  value,
  onChange,
  invalid = false,
  disabled = false,
}: {
  value: number | ""
  onChange: (v: number | "") => void
  invalid?: boolean
  disabled?: boolean
}) {
  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"
          disabled={disabled}
          onClick={() => onChange(value === n ? "" : n)}
          aria-label={`${n} star${n !== 1 ? "s" : ""}`}
          aria-pressed={value === n}
          className="cursor-pointer transition-transform hover:scale-110 disabled:opacity-60 disabled:cursor-not-allowed"
        >
          <Star
            className="w-5 h-5"
            style={{
              color: value !== "" && n <= value ? "#F59E0B" : "var(--border)",
              fill: value !== "" && n <= value ? "#F59E0B" : "transparent",
            }}
            aria-hidden="true"
          />
        </button>
      ))}
      {value !== "" && (
        <span className="text-xs font-semibold font-sans ml-1" style={{ color: "#F59E0B" }}>
          {value}.0
        </span>
      )}
    </div>
  )
}

export function DoctorReviews({ value, onChange, showValidationError = false, sharedValuesLocked = false }: Props) {
  function addItem() {
    onChange([
      ...value,
      { patientName: "", country: "", content: "", rating: "", treatment: "", date: "" },
    ])
  }

  function removeItem(index: number) {
    onChange(value.filter((_, i) => i !== index))
  }

  function updateItem(index: number, field: keyof ReviewItem, val: ReviewItem[keyof ReviewItem]) {
    onChange(value.map((item, i) => (i === index ? { ...item, [field]: val } : item)))
  }

  return (
    <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
        </label>
        <button
          type="button"
          onClick={addItem}
          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.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">No patient reviews added yet.</p>
          <button
            type="button"
            onClick={addItem}
            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.map((item, index) => (
            <div
              key={index}
              className="rounded-2xl border border-border bg-card overflow-hidden"
            >
              {/* Review header */}
              <div
                className="flex items-center justify-between px-4 py-2.5 border-b border-border"
                style={{ background: "rgba(43,182,115,0.02)" }}
              >
                <div className="flex items-center gap-2">
                  <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 {index + 1}
                  </span>
                  <StarRatingPicker
                    value={item.rating}
                    onChange={(v) => updateItem(index, "rating", v)}
                    invalid={showValidationError && item.rating === ""}
                    disabled={sharedValuesLocked}
                  />
                </div>
                <button
                  type="button"
                  onClick={() => removeItem(index)}
                  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 ${index + 1}`}
                >
                  <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
                </button>
              </div>

              <div className="p-4 flex flex-col gap-3">
                {/* Name + Country row */}
                <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={item.patientName}
                      onChange={(e) => updateItem(index, "patientName", e.target.value)}
                      placeholder="e.g. Ahmed K."
                      className={`w-full bg-muted border rounded-xl px-3 py-2 text-sm text-foreground font-sans placeholder:text-muted-foreground outline-none transition-colors ${
                        showValidationError && item.patientName.trim() === ""
                          ? "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]"
                      }`}
                      aria-label={`Review ${index + 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={item.country}
                      onChange={(e) => updateItem(index, "country", e.target.value)}
                      placeholder="e.g. Saudi Arabia"
                      className={`w-full bg-muted border rounded-xl px-3 py-2 text-sm text-foreground font-sans placeholder:text-muted-foreground outline-none transition-colors ${
                        showValidationError && item.country.trim() === ""
                          ? "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]"
                      }`}
                      aria-label={`Review ${index + 1} country`}
                    />
                  </div>
                </div>

                {/* Treatment + Date row */}
                <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={item.treatment}
                      onChange={(e) => updateItem(index, "treatment", e.target.value)}
                      placeholder="e.g. FUE Hair Transplant"
                      className={`w-full bg-muted border rounded-xl px-3 py-2 text-sm text-foreground font-sans placeholder:text-muted-foreground outline-none transition-colors ${
                        showValidationError && item.treatment.trim() === ""
                          ? "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]"
                      }`}
                      aria-label={`Review ${index + 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={item.date}
                      onChange={(e) => updateItem(index, "date", e.target.value)}
                      disabled={sharedValuesLocked}
                      className={`w-full bg-muted border rounded-xl px-3 py-2 text-sm text-foreground font-sans outline-none transition-colors ${
                        showValidationError && item.date.trim() === ""
                          ? "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]"
                      } disabled:opacity-60`}
                      aria-label={`Review ${index + 1} date`}
                    />
                  </div>
                </div>

                {/* Review content */}
                <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={item.content}
                    onChange={(e) => updateItem(index, "content", e.target.value)}
                    placeholder="The patient's review text..."
                    rows={3}
                    className={`w-full bg-muted border rounded-xl px-3 py-2 text-sm text-foreground font-sans placeholder:text-muted-foreground outline-none transition-colors resize-none leading-relaxed ${
                      showValidationError && item.content.trim() === ""
                        ? "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]"
                    }`}
                    aria-label={`Review ${index + 1} content`}
                  />
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
      {showValidationError && (
        <p className="text-xs font-sans text-red-500">
          Please add at least one complete patient review (name, country, treatment, date, rating, and content).
        </p>
      )}
    </div>
  )
}
