"use client"

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

export interface ContactFormSectionData {
  title: string
  subtitle: string
  fullNameLabel: string
  emailAddressLabel: string
  phoneNumberLabel: string
  yourMessageLabel: string
  subjectOptionsTitle: string
  subjectOptions: string[]
  buttonIcon: string
  buttonText: string
  buttonLink: string
}

interface Props {
  value: ContactFormSectionData
  onChange: (value: ContactFormSectionData) => void
  disabled?: boolean
  validation?: {
    title?: boolean
    subtitle?: boolean
    fullNameLabel?: boolean
    emailAddressLabel?: boolean
    phoneNumberLabel?: boolean
    yourMessageLabel?: boolean
    subjectOptionsTitle?: boolean
    subjectOptions?: boolean
    subjectOptionItems?: boolean[]
    buttonIcon?: boolean
    buttonText?: boolean
    buttonLink?: 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 ContactFormSection({ value, onChange, disabled = false, validation }: Props) {
  function set<K extends keyof ContactFormSectionData>(key: K, val: ContactFormSectionData[K]) {
    onChange({ ...value, [key]: val })
  }

  function addSubjectOption() {
    set("subjectOptions", [...value.subjectOptions, ""])
  }

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

  function updateSubjectOption(index: number, next: string) {
    set(
      "subjectOptions",
      value.subjectOptions.map((item, i) => (i === index ? next : item))
    )
  }

  return (
    <div className="flex flex-col gap-5">
      <div className="flex flex-col gap-1.5">
        <Label>Title</Label>
        <input
          type="text"
          value={value.title}
          disabled={disabled}
          onChange={(e) => set("title", e.target.value)}
          placeholder="e.g. Send Us a Message"
          className={fieldClass(!!validation?.title)}
        />
      </div>

      <div className="flex flex-col gap-1.5">
        <Label>Subtitle</Label>
        <input
          type="text"
          value={value.subtitle}
          disabled={disabled}
          onChange={(e) => set("subtitle", e.target.value)}
          placeholder="e.g. Fill in the form below and we will get back to you."
          className={fieldClass(!!validation?.subtitle)}
        />
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
        <div className="flex flex-col gap-1.5">
          <Label>Full Name Label</Label>
          <input
            type="text"
            value={value.fullNameLabel}
            disabled={disabled}
            onChange={(e) => set("fullNameLabel", e.target.value)}
            placeholder="e.g. Full Name"
            className={fieldClass(!!validation?.fullNameLabel)}
          />
        </div>
        <div className="flex flex-col gap-1.5">
          <Label>Email Address Label</Label>
          <input
            type="text"
            value={value.emailAddressLabel}
            disabled={disabled}
            onChange={(e) => set("emailAddressLabel", e.target.value)}
            placeholder="e.g. Email Address"
            className={fieldClass(!!validation?.emailAddressLabel)}
          />
        </div>
        <div className="flex flex-col gap-1.5">
          <Label>Phone Number Label</Label>
          <input
            type="text"
            value={value.phoneNumberLabel}
            disabled={disabled}
            onChange={(e) => set("phoneNumberLabel", e.target.value)}
            placeholder="e.g. Phone Number"
            className={fieldClass(!!validation?.phoneNumberLabel)}
          />
        </div>
        <div className="flex flex-col gap-1.5">
          <Label>Your Message Label</Label>
          <input
            type="text"
            value={value.yourMessageLabel}
            disabled={disabled}
            onChange={(e) => set("yourMessageLabel", e.target.value)}
            placeholder="e.g. Your Message"
            className={fieldClass(!!validation?.yourMessageLabel)}
          />
        </div>
      </div>

      <div className={`flex flex-col gap-3 rounded-xl ${validation?.subjectOptions ? "border border-red-300 p-3 bg-red-50/40" : ""}`}>
        <div className="flex flex-col gap-1.5">
          <Label>Subject Options Title</Label>
          <input
            type="text"
            value={value.subjectOptionsTitle}
            disabled={disabled}
            onChange={(e) => set("subjectOptionsTitle", e.target.value)}
            placeholder="e.g. Subject"
            className={fieldClass(!!validation?.subjectOptionsTitle)}
          />
        </div>
        <div className="flex items-center justify-between">
          <Label>Subject Options (Array)</Label>
          <button
            type="button"
            disabled={disabled}
            onClick={addSubjectOption}
            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-60 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 Subject
          </button>
        </div>
        {value.subjectOptions.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 subjects yet.</p>
            <button
              type="button"
              disabled={disabled}
              onClick={addSubjectOption}
              className="text-xs cursor-pointer font-semibold font-sans disabled:opacity-60 disabled:cursor-not-allowed"
              style={{ color: "var(--brand-green)" }}
            >
              Add your first subject
            </button>
          </div>
        ) : (
          <div className="flex flex-col gap-2">
            {value.subjectOptions.map((subject, index) => (
              <div key={index} className="flex items-center gap-2">
                <input
                  type="text"
                  value={subject}
                  disabled={disabled}
                  onChange={(e) => updateSubjectOption(index, e.target.value)}
                  placeholder="Subject option..."
                  className={fieldClass(!!validation?.subjectOptionItems?.[index])}
                />
                <button
                  type="button"
                  disabled={disabled}
                  onClick={() => removeSubjectOption(index)}
                  className="p-1.5 cursor-pointer rounded-lg text-muted-foreground hover:text-red-500 hover:bg-red-50 transition-colors shrink-0 disabled:opacity-60 disabled:cursor-not-allowed"
                  aria-label={`Remove subject ${index + 1}`}
                >
                  <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
                </button>
              </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">
          Button (Icon + Text + Link)
        </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">Button Icon</label>
            <IconPicker
              value={value.buttonIcon}
              onChange={(key) => set("buttonIcon", key)}
              invalid={!!validation?.buttonIcon}
            />
          </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.buttonText}
              disabled={disabled}
              onChange={(e) => set("buttonText", e.target.value)}
              placeholder="e.g. Send Message"
              className={fieldClass(!!validation?.buttonText)}
            />
          </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.buttonLink}
              disabled={disabled}
              onChange={(e) => set("buttonLink", e.target.value)}
              placeholder="e.g. /contact"
              className={fieldClass(!!validation?.buttonLink)}
            />
          </div>
        </div>
      </div>
    </div>
  )
}
