"use client"

import { Plus, Trash2 } from "lucide-react"
import { IconPicker } from "@/components/dashboard/shared/IconPicker"

export interface MissionStat {
  label: string
  value: string
}

export interface MissionFeature {
  title: string
  description: string
  icon: string
}

export interface MissionSectionData {
  eyebrow: string
  title: string
  description: string
  stats: MissionStat[]
  features: MissionFeature[]
}

interface Props {
  value: MissionSectionData
  onChange: (value: MissionSectionData) => void
  validation?: {
    eyebrow?: boolean
    title?: boolean
    description?: boolean
    stats?: boolean
    statsItems?: Array<{ label?: boolean; value?: boolean }>
    features?: boolean
    featureItems?: Array<{ title?: boolean; description?: boolean; icon?: 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 MissionSection({ value, onChange, validation }: Props) {
  function set<K extends keyof MissionSectionData>(key: K, val: MissionSectionData[K]) {
    onChange({ ...value, [key]: val })
  }

  // Stats
  function addStat() {
    set("stats", [...value.stats, { label: "", value: "" }])
  }
  function removeStat(index: number) {
    set("stats", value.stats.filter((_, i) => i !== index))
  }
  function updateStat(index: number, field: keyof MissionStat, val: string) {
    set("stats", value.stats.map((s, i) => (i === index ? { ...s, [field]: val } : s)))
  }

  // Features
  function addFeature() {
    set("features", [...value.features, { title: "", description: "", icon: "" }])
  }
  function removeFeature(index: number) {
    set("features", value.features.filter((_, i) => i !== index))
  }
  function updateFeature(index: number, field: keyof MissionFeature, val: string) {
    set("features", value.features.map((f, i) => (i === index ? { ...f, [field]: val } : f)))
  }

  return (
    <div className="flex flex-col gap-6">
      {/* Main fields */}
      <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 Mission"
          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. Dedicated to Your Health & Confidence"
          className={fieldClass(!!validation?.title)}
        />
      </div>

      <div className="flex flex-col gap-1.5">
        <Label>Description</Label>
        <textarea
          value={value.description}
          onChange={(e) => set("description", e.target.value)}
          placeholder="Describe your mission..."
          rows={4}
          className={`${fieldClass(!!validation?.description)} resize-none leading-relaxed`}
        />
      </div>

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

        {value.stats.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 stats yet.</p>
            <button type="button" onClick={addStat} className="text-xs cursor-pointer font-semibold font-sans" style={{ color: "var(--brand-green)" }}>
              Add your first stat
            </button>
          </div>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
            {value.stats.map((stat, index) => (
              <div key={index} className="flex flex-col gap-2 p-3 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)" }}>
                    Stat {index + 1}
                  </span>
                  <button type="button" onClick={() => removeStat(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 stat ${index + 1}`}>
                    <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
                  </button>
                </div>
                <input type="text" value={stat.value} onChange={(e) => updateStat(index, "value", e.target.value)} placeholder="e.g. 98%" className={fieldClass(!!validation?.statsItems?.[index]?.value)} />
                <input type="text" value={stat.label} onChange={(e) => updateStat(index, "label", e.target.value)} placeholder="e.g. Success Rate" className={fieldClass(!!validation?.statsItems?.[index]?.label)} />
              </div>
            ))}
          </div>
        )}
      </div>

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

        {value.features.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 features yet.</p>
            <button type="button" onClick={addFeature} className="text-xs cursor-pointer font-semibold font-sans" style={{ color: "var(--brand-green)" }}>
              Add your first feature
            </button>
          </div>
        ) : (
          <div className="flex flex-col gap-3">
            {value.features.map((feature, 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(43,182,115,0.10)", color: "var(--brand-green)" }}>
                    Feature {index + 1}
                  </span>
                  <button type="button" onClick={() => removeFeature(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 feature ${index + 1}`}>
                    <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
                  </button>
                </div>
                <input type="text" value={feature.title} onChange={(e) => updateFeature(index, "title", e.target.value)} placeholder="Feature title..." className={fieldClass(!!validation?.featureItems?.[index]?.title)} />
                <textarea value={feature.description} onChange={(e) => updateFeature(index, "description", e.target.value)} placeholder="Feature description..." rows={2} className={`${fieldClass(!!validation?.featureItems?.[index]?.description)} resize-none leading-relaxed`} />
                <IconPicker
                  value={feature.icon}
                  onChange={(key) => updateFeature(index, "icon", key)}
                  invalid={!!validation?.featureItems?.[index]?.icon}
                />
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}
