"use client"

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

export interface FAQCategory {
  name: string
}

export interface FAQItem {
  category: string
  question: string
  answer: string
}

export interface FAQSectionData {
  title: string
  categories: FAQCategory[]
  faqs: FAQItem[]
}

interface Props {
  value: FAQSectionData
  onChange: (value: FAQSectionData) => void
  showValidation?: 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 FAQSection({ value, onChange, showValidation = false }: Props) {
  function set<K extends keyof FAQSectionData>(key: K, val: FAQSectionData[K]) {
    onChange({ ...value, [key]: val })
  }

  // Categories
  function addCategory() {
    set("categories", [...value.categories, { name: "" }])
  }
  function removeCategory(i: number) {
    set("categories", value.categories.filter((_, idx) => idx !== i))
  }
  function updateCategory(i: number, val: string) {
    set("categories", value.categories.map((c, idx) => (idx === i ? { name: val } : c)))
  }

  // FAQs
  function addFAQ() {
    set("faqs", [...value.faqs, { category: "", question: "", answer: "" }])
  }
  function removeFAQ(i: number) {
    set("faqs", value.faqs.filter((_, idx) => idx !== i))
  }
  function updateFAQ(i: number, field: keyof FAQItem, val: string) {
    set("faqs", value.faqs.map((f, idx) => (idx === i ? { ...f, [field]: val } : f)))
  }

  const categoryOptions = value.categories
    .map((cat) => cat.name.trim())
    .filter((name) => name.length > 0)

  return (
    <div className="flex flex-col gap-6">
      <div className="flex flex-col gap-1.5">
        <Label>Section Title</Label>
        <input type="text" value={value.title} onChange={(e) => set("title", e.target.value)} placeholder="e.g. Frequently Asked Questions" className={fieldClass(showValidation && !value.title.trim())} />
      </div>

      {/* Categories */}
      <div className={`flex flex-col gap-3 rounded-xl ${showValidation && value.categories.length === 0 ? "border border-red-300 p-3 bg-red-50/40" : ""}`}>
        <div className="flex items-center justify-between">
          <Label>Categories</Label>
          <button
            type="button"
            onClick={addCategory}
            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 Category
          </button>
        </div>
        {value.categories.length === 0 ? (
          <div className="flex flex-col items-center justify-center gap-2 py-5 rounded-xl border border-dashed border-border">
            <p className="text-xs text-muted-foreground font-sans">No categories yet.</p>
            <button type="button" onClick={addCategory} className="text-xs cursor-pointer font-semibold font-sans" style={{ color: "var(--brand-green)" }}>
              Add your first category
            </button>
          </div>
        ) : (
          <div className="flex flex-col gap-2">
            {value.categories.map((cat, i) => (
              <div key={i} className="flex items-center gap-2">
                <input type="text" value={cat.name} onChange={(e) => updateCategory(i, e.target.value)} placeholder="Category name..." className={fieldClass(showValidation && !cat.name.trim())} />
                <button type="button" onClick={() => removeCategory(i)} className="p-1.5 cursor-pointer rounded-lg text-muted-foreground hover:text-red-500 hover:bg-red-50 transition-colors shrink-0" aria-label="Remove category">
                  <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
                </button>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* FAQs */}
      <div className={`flex flex-col gap-3 rounded-xl ${showValidation && value.faqs.length === 0 ? "border border-red-300 p-3 bg-red-50/40" : ""}`}>
        <div className="flex items-center justify-between">
          <Label>FAQs</Label>
          <button
            type="button"
            onClick={addFAQ}
            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 FAQ
          </button>
        </div>
        {value.faqs.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 FAQs yet.</p>
            <button type="button" onClick={addFAQ} className="text-xs cursor-pointer font-semibold font-sans" style={{ color: "var(--brand-green)" }}>
              Add your first FAQ
            </button>
          </div>
        ) : (
          <div className="flex flex-col gap-3">
            {value.faqs.map((faq, i) => (
              <div key={i} 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)" }}>
                    FAQ {i + 1}
                  </span>
                  <button type="button" onClick={() => removeFAQ(i)} className="p-1.5 cursor-pointer rounded-lg text-muted-foreground hover:text-red-500 hover:bg-red-50 transition-colors" aria-label={`Remove FAQ ${i + 1}`}>
                    <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
                  </button>
                </div>
                <div className="felx felx-col gap-1.5">
                  <div className="flex flex-col gap-1.5">
                    <label className="text-xs font-semibold text-muted-foreground font-sans">Category</label>
                    <select
                      value={faq.category}
                      onChange={(e) => updateFAQ(i, "category", e.target.value)}
                      className={fieldClass(showValidation && !faq.category.trim())}
                    >
                      <option value="">Select category...</option>
                      {categoryOptions.map((categoryName, categoryIndex) => (
                        <option key={`${categoryName}-${categoryIndex}`} value={categoryName}>
                          {categoryName}
                        </option>
                      ))}
                    </select>
                  </div>
                  
                </div>
                <div className="flex flex-col gap-1.5">
                  <label className="text-xs font-semibold text-muted-foreground font-sans">Question</label>
                  <input type="text" value={faq.question} onChange={(e) => updateFAQ(i, "question", e.target.value)} placeholder="Question text..." className={fieldClass(showValidation && !faq.question.trim())} />
                </div>
                <div className="flex flex-col gap-1.5">
                  <label className="text-xs font-semibold text-muted-foreground font-sans">Answer</label>
                  <textarea value={faq.answer} onChange={(e) => updateFAQ(i, "answer", e.target.value)} placeholder="Answer text..." rows={3} className={`${fieldClass(showValidation && !faq.answer.trim())} resize-none leading-relaxed`} />
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}
