"use client"

import { Plus, Trash2 } from "lucide-react"
import type {
  ProceduresFiltersSectionData,
  ProceduresFilter,
  ProceduresFilterOption,
} from "@/lib/pages/procedures-page/form-types"

interface Props {
  value: ProceduresFiltersSectionData
  onChange: (value: ProceduresFiltersSectionData) => void
  disabled?: boolean
  validation?: {
    filters?: boolean
    filterItems?: Array<{ label?: boolean; options?: boolean; optionItems?: Array<{ label?: boolean }> }>
    mainFilterOptionsTitle?: boolean
    mainFilterOptions?: boolean
    mainFilterOptionItems?: Array<{ label?: 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 ProceduresFiltersSection({ value, onChange, disabled = false, validation }: Props) {
  // ── Filters ──────────────────────────────────────────────────────────────

  function addFilter() {
    if (disabled) return
    onChange({ ...value, filters: [...value.filters, { label: "", options: [] }] })
  }

  function removeFilter(filterIndex: number) {
    onChange({ ...value, filters: value.filters.filter((_, i) => i !== filterIndex) })
  }

  function updateFilterLabel(filterIndex: number, label: string) {
    onChange({
      ...value,
      filters: value.filters.map((f, i) => (i === filterIndex ? { ...f, label } : f)),
    })
  }

  function addFilterOption(filterIndex: number) {
    if (disabled) return
    onChange({
      ...value,
      filters: value.filters.map((f, i) =>
        i === filterIndex ? { ...f, options: [...f.options, { label: "" }] } : f
      ),
    })
  }

  function removeFilterOption(filterIndex: number, optionIndex: number) {
    onChange({
      ...value,
      filters: value.filters.map((f, i) =>
        i === filterIndex
          ? { ...f, options: f.options.filter((_, j) => j !== optionIndex) }
          : f
      ),
    })
  }

  function updateFilterOption(filterIndex: number, optionIndex: number, label: string) {
    onChange({
      ...value,
      filters: value.filters.map((f, i) =>
        i === filterIndex
          ? {
              ...f,
              options: f.options.map((o, j) => (j === optionIndex ? { label } : o)),
            }
          : f
      ),
    })
  }

  // ── Main Filter ───────────────────────────────────────────────────────────

  function addMainOption() {
    if (disabled) return
    onChange({ ...value, mainFilterOptions: [...value.mainFilterOptions, { label: "" }] })
  }

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

  function updateMainOption(index: number, label: string) {
    onChange({
      ...value,
      mainFilterOptions: value.mainFilterOptions.map((o, i) => (i === index ? { label } : o)),
    })
  }

  function updateMainFilterOptionsTitle(title: string) {
    onChange({ ...value, mainFilterOptionsTitle: title })
  }

  return (
    <div className="flex flex-col gap-8">
      {/* Filters */}
      <div className={`flex flex-col gap-4 rounded-xl ${validation?.filters && value.filters.length === 0 ? "border border-red-300 p-3 bg-red-50/40" : ""}`}>
        <div className="flex items-center justify-between gap-2">
          <div className="flex flex-col gap-0.5">
            <Label>Filters</Label>
            <span className="text-xs text-muted-foreground font-sans">Each filter has a label and a list of options</span>
          </div>
          <button
            type="button"
            onClick={addFilter}
            disabled={disabled}
            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] disabled:opacity-50 disabled:cursor-not-allowed"
            style={{ background: "rgba(43,182,115,0.10)", color: "var(--brand-green)" }}
          >
            <Plus className="w-3.5 h-3.5" aria-hidden="true" />
            Add Filter
          </button>
        </div>

        {value.filters.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 filters yet.</p>
            <button
              type="button"
              onClick={addFilter}
              disabled={disabled}
              className="text-xs font-semibold font-sans disabled:opacity-50"
              style={{ color: "var(--brand-green)" }}
            >
              Add your first filter
            </button>
          </div>
        ) : (
          <div className="flex flex-col gap-4">
            {value.filters.map((filter, filterIndex) => (
              <div
                key={filterIndex}
                className="flex flex-col gap-3 p-4 rounded-xl border border-border bg-muted/40"
              >
                {/* Filter header */}
                <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)" }}
                  >
                    Filter {filterIndex + 1}
                  </span>
                  <button
                    type="button"
                    onClick={() => removeFilter(filterIndex)}
                    disabled={disabled}
                    className="p-1.5 cursor-pointer rounded-lg text-muted-foreground hover:text-red-500 hover:bg-red-50 transition-colors"
                    aria-label={`Remove filter ${filterIndex + 1}`}
                  >
                    <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
                  </button>
                </div>

                {/* Filter label */}
                <div className="flex flex-col gap-1.5">
                  <label className="text-xs font-semibold text-muted-foreground font-sans">Label</label>
                  <input
                    type="text"
                    value={filter.label}
                    disabled={disabled}
                    onChange={(e) => updateFilterLabel(filterIndex, e.target.value)}
                    placeholder="e.g. Body Area"
                    className={fieldClass(!!validation?.filterItems?.[filterIndex]?.label)}
                  />
                </div>

                {/* Filter options */}
                <div className={`flex flex-col gap-2 rounded-xl ${validation?.filterItems?.[filterIndex]?.options && filter.options.length === 0 ? "border border-red-300 p-2 bg-red-50/40" : ""}`}>
                  <div className="flex items-center justify-between">
                    <label className="text-xs font-semibold text-muted-foreground font-sans">
                      Options
                    </label>
                    <button
                      type="button"
                      onClick={() => addFilterOption(filterIndex)}
                      disabled={disabled}
                      className="flex cursor-pointer items-center gap-1 px-2.5 py-1 rounded-lg text-xs font-semibold font-sans transition-all hover:brightness-105 disabled:opacity-50 disabled:cursor-not-allowed"
                      style={{ background: "rgba(29,45,104,0.07)", color: "var(--brand-navy)" }}
                    >
                      <Plus className="w-3 h-3" aria-hidden="true" />
                      Add Option
                    </button>
                  </div>

                  {filter.options.length === 0 ? (
                    <p className="text-xs text-muted-foreground font-sans italic py-2">No options yet.</p>
                  ) : (
                    <div className="flex flex-col gap-2">
                      {filter.options.map((option, optionIndex) => (
                        <div key={optionIndex} className="flex items-center gap-2">
                          <input
                            type="text"
                            value={option.label}
                            disabled={disabled}
                            onChange={(e) => updateFilterOption(filterIndex, optionIndex, e.target.value)}
                            placeholder={`Option ${optionIndex + 1} label`}
                            className={fieldClass(!!validation?.filterItems?.[filterIndex]?.optionItems?.[optionIndex]?.label)}
                          />
                          <button
                            type="button"
                            onClick={() => removeFilterOption(filterIndex, optionIndex)}
                            disabled={disabled}
                            className="p-1.5 cursor-pointer shrink-0 rounded-lg text-muted-foreground hover:text-red-500 hover:bg-red-50 transition-colors"
                            aria-label={`Remove option ${optionIndex + 1}`}
                          >
                            <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
                          </button>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Separator */}
      <div className="border-t border-border" />

      {/* Main Filter Name Options */}
      <div className={`flex flex-col gap-4 rounded-xl ${validation?.mainFilterOptions && value.mainFilterOptions.length === 0 ? "border border-red-300 p-3 bg-red-50/40" : ""}`}>
        <div className="flex flex-col gap-1.5">
          <Label>Main Filter Options Title</Label>
          <input
            type="text"
            value={value.mainFilterOptionsTitle ?? ""}
            disabled={disabled}
            onChange={(e) => updateMainFilterOptionsTitle(e.target.value)}
            placeholder="e.g. Main Filter Options"
            className={fieldClass(!!validation?.mainFilterOptionsTitle)}
          />
        </div>

        <div className="flex items-center justify-between gap-2">
          <div className="flex flex-col gap-0.5">
            <Label>Main Filter Options</Label>
            <span className="text-xs text-muted-foreground font-sans">Options for the primary filter (e.g. All, Popular, New)</span>
          </div>
          <button
            type="button"
            onClick={addMainOption}
            disabled={disabled}
            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] disabled:opacity-50 disabled:cursor-not-allowed"
            style={{ background: "rgba(43,182,115,0.10)", color: "var(--brand-green)" }}
          >
            <Plus className="w-3.5 h-3.5" aria-hidden="true" />
            Add Option
          </button>
        </div>

        {value.mainFilterOptions.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 main filter options yet.</p>
            <button
              type="button"
              onClick={addMainOption}
              disabled={disabled}
              className="text-xs font-semibold font-sans disabled:opacity-50"
              style={{ color: "var(--brand-green)" }}
            >
              Add your first option
            </button>
          </div>
        ) : (
          <div className="flex flex-col gap-2">
            {value.mainFilterOptions.map((option, index) => (
              <div key={index} className="flex items-center gap-2">
                <input
                  type="text"
                  value={option.label}
                  disabled={disabled}
                  onChange={(e) => updateMainOption(index, e.target.value)}
                  placeholder={`e.g. All Procedures`}
                  className={fieldClass(!!validation?.mainFilterOptionItems?.[index]?.label)}
                />
                <button
                  type="button"
                  onClick={() => removeMainOption(index)}
                  disabled={disabled}
                  className="p-1.5 cursor-pointer shrink-0 rounded-lg text-muted-foreground hover:text-red-500 hover:bg-red-50 transition-colors"
                  aria-label={`Remove option ${index + 1}`}
                >
                  <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
                </button>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}
