"use client"

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

export interface TimelineItem {
  sinceText: string
  title: string
  description: string
}

export interface HistorySectionData {
  eyebrow: string
  title: string
  subtitle: string
  timeline: TimelineItem[]
}

interface Props {
  value: HistorySectionData
  onChange: (value: HistorySectionData) => void
  validation?: {
    eyebrow?: boolean
    title?: boolean
    subtitle?: boolean
    timeline?: boolean
    timelineItems?: Array<{ sinceText?: boolean; title?: boolean; description?: 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 HistorySection({ value, onChange, validation }: Props) {
  function set<K extends keyof HistorySectionData>(key: K, val: HistorySectionData[K]) {
    onChange({ ...value, [key]: val })
  }

  function addItem() {
    set("timeline", [...value.timeline, { sinceText: "", title: "", description: "" }])
  }

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

  function updateItem(index: number, field: keyof TimelineItem, val: string) {
    set("timeline", value.timeline.map((item, i) => (i === index ? { ...item, [field]: val } : item)))
  }

  return (
    <div className="flex flex-col gap-5">
      <div className="flex flex-col gap-1.5">
        <Label>Eyebrow Text</Label>
        <input
          type="text"
          value={value.eyebrow}
          onChange={(e) => set("eyebrow", e.target.value)}
          placeholder="e.g. Our Journey"
          className={fieldClass(!!validation?.eyebrow)}
        />
      </div>

      <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. A History of Excellence"
          className={fieldClass(!!validation?.title)}
        />
      </div>

      <div className="flex flex-col gap-1.5">
        <Label>Subtitle</Label>
        <textarea
          value={value.subtitle}
          onChange={(e) => set("subtitle", e.target.value)}
          placeholder="Brief subtitle for the history section..."
          rows={2}
          className={`${fieldClass(!!validation?.subtitle)} resize-none leading-relaxed`}
        />
      </div>

      {/* Timeline */}
      <div
        className={`flex flex-col gap-3 rounded-xl ${
          validation?.timeline && value.timeline.length === 0 ? "border border-red-300 p-3 bg-red-50/40" : ""
        }`}
      >
        <div className="flex items-center justify-between">
          <Label>Timeline Items</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 Item
          </button>
        </div>

        {value.timeline.length === 0 ? (
          <div className="flex flex-col items-center justify-center gap-2 py-6 rounded-xl border border-dashed border-border">
            <p className="text-xs text-muted-foreground font-sans">No timeline items yet.</p>
            <button
              type="button"
              onClick={addItem}
              className="text-xs cursor-pointer font-semibold font-sans"
              style={{ color: "var(--brand-green)" }}
            >
              Add your first milestone
            </button>
          </div>
        ) : (
          <div className="flex flex-col gap-3">
            {value.timeline.map((item, index) => (
              <div
                key={index}
                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)" }}
                  >
                    {item.sinceText || `Milestone ${index + 1}`}
                  </span>
                  <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 timeline item ${index + 1}`}
                  >
                    <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
                  </button>
                </div>
                <div className="grid grid-cols-2 gap-3">
                  <div className="flex flex-col gap-1.5">
                    <label className="text-xs font-semibold text-muted-foreground font-sans">Since / Year</label>
                    <input
                      type="text"
                      value={item.sinceText}
                      onChange={(e) => updateItem(index, "sinceText", e.target.value)}
                      placeholder="e.g. Since 2010"
                      className={fieldClass(!!validation?.timelineItems?.[index]?.sinceText)}
                    />
                  </div>
                  <div className="flex flex-col gap-1.5">
                    <label className="text-xs font-semibold text-muted-foreground font-sans">Title</label>
                    <input
                      type="text"
                      value={item.title}
                      onChange={(e) => updateItem(index, "title", e.target.value)}
                      placeholder="e.g. Clinic Founded"
                      className={fieldClass(!!validation?.timelineItems?.[index]?.title)}
                    />
                  </div>
                </div>
                <textarea
                  value={item.description}
                  onChange={(e) => updateItem(index, "description", e.target.value)}
                  placeholder="Describe this milestone..."
                  rows={2}
                  className={`${fieldClass(!!validation?.timelineItems?.[index]?.description)} resize-none leading-relaxed`}
                />
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}
