"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { toast } from "@/components/admin/Toast";
import { apiPatch, FetchError } from "@/lib/client-api";

interface SocialLink {
  platform: string;
  url: string;
}

interface ContactFormState {
  pageTitle: string;
  description: string;
  supportEmail: string;
  phone: string;
  address: string;
  businessHours: string;
  mapLocation: string;
  socialLinks: SocialLink[];
  formEnabled: boolean;
  published: boolean;
}

const empty: ContactFormState = {
  pageTitle: "Contact us",
  description: "",
  supportEmail: "support@example.com",
  phone: "",
  address: "",
  businessHours: "",
  mapLocation: "",
  socialLinks: [],
  formEnabled: true,
  published: true,
};

export function ContactForm({ initial }: { initial: Record<string, unknown> | null }) {
  const router = useRouter();
  const [state, setState] = useState<ContactFormState>(() => {
    if (!initial) return empty;
    return {
      pageTitle: (initial.pageTitle as string) ?? empty.pageTitle,
      description: (initial.description as string) ?? "",
      supportEmail: (initial.supportEmail as string) ?? empty.supportEmail,
      phone: (initial.phone as string) ?? "",
      address: (initial.address as string) ?? "",
      businessHours: (initial.businessHours as string) ?? "",
      mapLocation: (initial.mapLocation as string) ?? "",
      socialLinks: (initial.socialLinks as SocialLink[]) ?? [],
      formEnabled: (initial.formEnabled as boolean) ?? true,
      published: (initial.published as boolean) ?? true,
    };
  });
  const [pending, setPending] = useState(false);

  const update = (patch: Partial<ContactFormState>) =>
    setState((s) => ({ ...s, ...patch }));

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      setPending(true);
      await apiPatch("/api/admin/content/contact", state);
      toast("Contact content saved.", "success");
      router.refresh();
    } catch (err) {
      toast(err instanceof FetchError ? err.message : "Save failed.", "error");
    } finally {
      setPending(false);
    }
  };

  return (
    <form onSubmit={submit} className="rounded-2xl border border-border bg-surface p-5 shadow-sm space-y-4">
      <div className="grid gap-3 sm:grid-cols-2">
        <Field label="Page title">
          <input
            value={state.pageTitle}
            onChange={(e) => update({ pageTitle: e.target.value })}
            className="input"
          />
        </Field>
        <Field label="Support email">
          <input
            type="email"
            required
            value={state.supportEmail}
            onChange={(e) => update({ supportEmail: e.target.value })}
            className="input"
          />
        </Field>
        <Field label="Phone">
          <input
            value={state.phone}
            onChange={(e) => update({ phone: e.target.value })}
            className="input"
          />
        </Field>
        <Field label="Business hours">
          <input
            value={state.businessHours}
            onChange={(e) => update({ businessHours: e.target.value })}
            className="input"
          />
        </Field>
        <Field label="Address" full>
          <textarea
            value={state.address}
            onChange={(e) => update({ address: e.target.value })}
            className="input"
            rows={2}
          />
        </Field>
        <Field label="Description" full>
          <textarea
            value={state.description}
            onChange={(e) => update({ description: e.target.value })}
            className="input"
            rows={3}
          />
        </Field>
        <Field label="Map embed (iframe or coordinates)" full>
          <textarea
            value={state.mapLocation}
            onChange={(e) => update({ mapLocation: e.target.value })}
            className="input"
            rows={3}
            placeholder='<iframe src="…" /> or coordinates'
          />
        </Field>
      </div>
      <div>
        <p className="mb-2 text-sm font-medium text-foreground">Social links</p>
        <div className="space-y-2">
          {state.socialLinks.map((s, idx) => (
            <div key={idx} className="flex gap-2">
              <input
                value={s.platform}
                placeholder="Platform"
                onChange={(e) =>
                  update({
                    socialLinks: state.socialLinks.map((x, i) =>
                      i === idx ? { ...x, platform: e.target.value } : x,
                    ),
                  })
                }
                className="input"
              />
              <input
                value={s.url}
                placeholder="https://…"
                onChange={(e) =>
                  update({
                    socialLinks: state.socialLinks.map((x, i) =>
                      i === idx ? { ...x, url: e.target.value } : x,
                    ),
                  })
                }
                className="input"
              />
              <button
                type="button"
                onClick={() =>
                  update({
                    socialLinks: state.socialLinks.filter((_, i) => i !== idx),
                  })
                }
                className="rounded-lg border border-border px-2 text-red-600"
              >
                ✕
              </button>
            </div>
          ))}
          <button
            type="button"
            onClick={() =>
              update({
                socialLinks: [...state.socialLinks, { platform: "", url: "" }],
              })
            }
            className="rounded-lg border border-border bg-surface px-3 py-1.5 text-xs"
          >
            + Add social link
          </button>
        </div>
      </div>
      <div className="flex items-center gap-3 text-sm">
        <label className="flex items-center gap-2">
          <input
            type="checkbox"
            checked={state.formEnabled}
            onChange={(e) => update({ formEnabled: e.target.checked })}
          />
          Show contact form
        </label>
        <label className="flex items-center gap-2">
          <input
            type="checkbox"
            checked={state.published}
            onChange={(e) => update({ published: e.target.checked })}
          />
          Published
        </label>
      </div>
      <Button type="submit" isLoading={pending}>
        Save contact content
      </Button>
      <style jsx>{`
        :global(.input) {
          width: 100%;
          border-radius: 0.5rem;
          border: 1px solid var(--border);
          background: var(--surface);
          padding: 0.5rem 0.75rem;
          font-size: 0.875rem;
        }
        :global(.input:focus) {
          outline: none;
          border-color: var(--primary);
        }
      `}</style>
    </form>
  );
}

function Field({
  label,
  full,
  children,
}: {
  label: string;
  full?: boolean;
  children: React.ReactNode;
}) {
  return (
    <div className={full ? "sm:col-span-2" : ""}>
      <label className="mb-1 block text-xs font-medium text-muted">{label}</label>
      {children}
    </div>
  );
}