"use client"

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

export interface CTABadge {
  label: string
  icon: string
}

export interface FinalCTASectionData {
  eyebrow: string
  title: string
  description: string
  primaryButtonText: string
  primaryButtonLink: string
  secondaryButtonIcon: string
  secondaryButtonText: string
  secondaryButtonLink: string
  badges: CTABadge[]
}

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

  function addBadge() {
    set("badges", [...value.badges, { label: "", icon: "" }])
  }

  function removeBadge(i: number) {
    set("badges", value.badges.filter((_, idx) => idx !== i))
  }

  function updateBadge(i: number, field: keyof CTABadge, val: string) {
    set("badges", value.badges.map((b, idx) => (idx === i ? { ...b, [field]: val } : b)))
  }

  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. Start Your Journey" className={fieldClass(showValidation && !value.eyebrow.trim())} />
      </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. Ready to Transform Your Life?" className={fieldClass(showValidation && !value.title.trim())} />
      </div>

      <div className="flex flex-col gap-1.5">
        <Label>Description</Label>
        <textarea value={value.description} onChange={(e) => set("description", e.target.value)} placeholder="A compelling call-to-action description..." rows={3} className={`${fieldClass(showValidation && !value.description.trim())} resize-none leading-relaxed`} />
      </div>

      <div
        className="rounded-xl p-4 border border-border flex flex-col gap-4"
        style={{ background: "rgba(43,182,115,0.03)" }}
      >
        <p className="text-xs font-bold font-sans uppercase tracking-wider text-muted-foreground">Primary Button</p>
        <div className="grid grid-cols-2 gap-4">
          <div className="flex flex-col gap-1.5">
            <label className="text-xs font-semibold text-muted-foreground font-sans">Button Text</label>
            <input type="text" value={value.primaryButtonText} onChange={(e) => set("primaryButtonText", e.target.value)} placeholder="e.g. Book Free Consultation" className={fieldClass(showValidation && !value.primaryButtonText.trim())} />
          </div>
          <div className="flex flex-col gap-1.5">
            <label className="text-xs font-semibold text-muted-foreground font-sans">Button Link</label>
            <input type="text" value={value.primaryButtonLink} onChange={(e) => set("primaryButtonLink", e.target.value)} placeholder="e.g. /contact" className={fieldClass(showValidation && !value.primaryButtonLink.trim())} />
          </div>
        </div>
      </div>

      <div
        className="rounded-xl p-4 border border-border flex flex-col gap-4"
        style={{ background: "rgba(29,45,104,0.03)" }}
      >
        <p className="text-xs font-bold font-sans uppercase tracking-wider text-muted-foreground">Secondary Button</p>
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <div className="flex flex-col gap-1.5 sm:col-span-2">
            <label className="text-xs font-semibold text-muted-foreground font-sans">Icon</label>
            <IconPicker
              value={value.secondaryButtonIcon}
              onChange={(key) => set("secondaryButtonIcon", key)}
              invalid={showValidation && !value.secondaryButtonIcon.trim()}
            />
          </div>
          <div className="flex flex-col gap-1.5">
            <label className="text-xs font-semibold text-muted-foreground font-sans">Button Text</label>
            <input type="text" value={value.secondaryButtonText} onChange={(e) => set("secondaryButtonText", e.target.value)} placeholder="e.g. View Our Work" className={fieldClass(showValidation && !value.secondaryButtonText.trim())} />
          </div>
          <div className="flex flex-col gap-1.5">
            <label className="text-xs font-semibold text-muted-foreground font-sans">Button Link</label>
            <input type="text" value={value.secondaryButtonLink} onChange={(e) => set("secondaryButtonLink", e.target.value)} placeholder="e.g. /gallery" className={fieldClass(showValidation && !value.secondaryButtonLink.trim())} />
          </div>
        </div>
      </div>

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

        {value.badges.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 badges yet.</p>
            <button type="button" onClick={addBadge} className="text-xs cursor-pointer font-semibold font-sans" style={{ color: "var(--brand-green)" }}>
              Add your first badge
            </button>
          </div>
        ) : (
          <div className="flex flex-col gap-3">
            {value.badges.map((badge, 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)" }}>
                    Badge {i + 1}
                  </span>
                  <button type="button" onClick={() => removeBadge(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 badge ${i + 1}`}>
                    <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
                  </button>
                </div>
                <input type="text" value={badge.label} onChange={(e) => updateBadge(i, "label", e.target.value)} placeholder="Badge label..." className={fieldClass(showValidation && !badge.label.trim())} />
                <div className="flex flex-col gap-1.5">
                  <label className="text-xs font-semibold text-muted-foreground font-sans">Icon</label>
                  <IconPicker value={badge.icon} onChange={(key) => updateBadge(i, "icon", key)} invalid={showValidation && !badge.icon.trim()} />
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}
