"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 FeatureSection {
  title: string;
  description: string;
  icon?: string;
}

interface Statistic {
  label: string;
  value: string;
  icon?: string;
}

interface TeamMember {
  name: string;
  role: string;
  bio?: string;
}

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

interface AboutFormState {
  pageTitle: string;
  subtitle: string;
  heroContent: string;
  mainDescription: string;
  mission: string;
  vision: string;
  featureSections: FeatureSection[];
  statistics: Statistic[];
  teamTitle: string;
  teamDescription: string;
  teamMembers: TeamMember[];
  images: string[];
  socialLinks: SocialLink[];
  displayOrder: number;
  published: boolean;
}

const empty: AboutFormState = {
  pageTitle: "About us",
  subtitle: "",
  heroContent: "",
  mainDescription: "",
  mission: "",
  vision: "",
  featureSections: [],
  statistics: [],
  teamTitle: "",
  teamDescription: "",
  teamMembers: [],
  images: [],
  socialLinks: [],
  displayOrder: 0,
  published: true,
};

export function AboutForm({ initial }: { initial: Record<string, unknown> | null }) {
  const router = useRouter();
  const [state, setState] = useState<AboutFormState>(() => {
    if (!initial) return empty;
    const teamSections = (initial.teamSections as {
      title?: string;
      description?: string;
      members?: TeamMember[];
    }) ?? {};
    return {
      pageTitle: (initial.pageTitle as string) ?? empty.pageTitle,
      subtitle: (initial.subtitle as string) ?? "",
      heroContent: (initial.heroContent as string) ?? "",
      mainDescription: (initial.mainDescription as string) ?? "",
      mission: (initial.mission as string) ?? "",
      vision: (initial.vision as string) ?? "",
      featureSections: (initial.featureSections as FeatureSection[]) ?? [],
      statistics: (initial.statistics as Statistic[]) ?? [],
      teamTitle: teamSections.title ?? "",
      teamDescription: teamSections.description ?? "",
      teamMembers: teamSections.members ?? [],
      images: (initial.images as string[]) ?? [],
      socialLinks: (initial.socialLinks as SocialLink[]) ?? [],
      displayOrder: (initial.displayOrder as number) ?? 0,
      published: (initial.published as boolean) ?? true,
    };
  });
  const [pending, setPending] = useState(false);

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

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      setPending(true);
      const payload = {
        pageTitle: state.pageTitle,
        subtitle: state.subtitle,
        heroContent: state.heroContent,
        mainDescription: state.mainDescription,
        mission: state.mission,
        vision: state.vision,
        featureSections: state.featureSections,
        statistics: state.statistics,
        teamSections: {
          title: state.teamTitle,
          description: state.teamDescription,
          members: state.teamMembers,
        },
        images: state.images,
        socialLinks: state.socialLinks,
        displayOrder: state.displayOrder,
        published: state.published,
      };
      await apiPatch("/api/admin/content/about", payload);
      toast("About 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="Subtitle">
          <input
            value={state.subtitle}
            onChange={(e) => update({ subtitle: e.target.value })}
            className="input"
          />
        </Field>
        <Field label="Hero content" full>
          <textarea
            value={state.heroContent}
            onChange={(e) => update({ heroContent: e.target.value })}
            className="input"
            rows={2}
          />
        </Field>
        <Field label="Main description" full>
          <textarea
            value={state.mainDescription}
            onChange={(e) => update({ mainDescription: e.target.value })}
            className="input"
            rows={4}
          />
        </Field>
        <Field label="Mission">
          <textarea
            value={state.mission}
            onChange={(e) => update({ mission: e.target.value })}
            className="input"
            rows={2}
          />
        </Field>
        <Field label="Vision">
          <textarea
            value={state.vision}
            onChange={(e) => update({ vision: e.target.value })}
            className="input"
            rows={2}
          />
        </Field>
      </div>

      <SectionEditor
        title="Feature sections"
        items={state.featureSections as unknown as Array<Record<string, string | undefined>>}
        onChange={(items) =>
          update({
            featureSections: items as unknown as FeatureSection[],
          })
        }
        fields={[
          { key: "title", label: "Title" },
          { key: "description", label: "Description", textarea: true },
          { key: "icon", label: "Icon" },
        ]}
      />

      <SectionEditor
        title="Statistics"
        items={state.statistics as unknown as Array<Record<string, string | undefined>>}
        onChange={(items) =>
          update({
            statistics: items as unknown as Statistic[],
          })
        }
        fields={[
          { key: "label", label: "Label" },
          { key: "value", label: "Value" },
          { key: "icon", label: "Icon" },
        ]}
      />

      <div>
        <p className="mb-2 text-sm font-medium text-foreground">Team</p>
        <div className="grid gap-2 sm:grid-cols-2">
          <Field label="Section title">
            <input
              value={state.teamTitle}
              onChange={(e) => update({ teamTitle: e.target.value })}
              className="input"
            />
          </Field>
          <Field label="Section description">
            <input
              value={state.teamDescription}
              onChange={(e) => update({ teamDescription: e.target.value })}
              className="input"
            />
          </Field>
        </div>
        <div className="mt-3 space-y-2">
          {state.teamMembers.map((m, idx) => (
            <div key={idx} className="rounded-xl border border-border p-3">
              <div className="grid gap-2 sm:grid-cols-2">
                <input
                  value={m.name}
                  placeholder="Name"
                  onChange={(e) =>
                    update({
                      teamMembers: state.teamMembers.map((x, i) =>
                        i === idx ? { ...x, name: e.target.value } : x,
                      ),
                    })
                  }
                  className="input"
                />
                <input
                  value={m.role}
                  placeholder="Role"
                  onChange={(e) =>
                    update({
                      teamMembers: state.teamMembers.map((x, i) =>
                        i === idx ? { ...x, role: e.target.value } : x,
                      ),
                    })
                  }
                  className="input"
                />
              </div>
              <textarea
                value={m.bio ?? ""}
                placeholder="Bio"
                onChange={(e) =>
                  update({
                    teamMembers: state.teamMembers.map((x, i) =>
                      i === idx ? { ...x, bio: e.target.value } : x,
                    ),
                  })
                }
                rows={2}
                className="input mt-2"
              />
              <button
                type="button"
                onClick={() =>
                  update({
                    teamMembers: state.teamMembers.filter((_, i) => i !== idx),
                  })
                }
                className="mt-2 rounded-lg border border-border px-2 py-1 text-xs text-red-600"
              >
                Remove
              </button>
            </div>
          ))}
          <button
            type="button"
            onClick={() =>
              update({
                teamMembers: [
                  ...state.teamMembers,
                  { name: "", role: "", bio: "" },
                ],
              })
            }
            className="rounded-lg border border-border bg-surface px-3 py-1.5 text-xs"
          >
            + Add team member
          </button>
        </div>
      </div>

      <SectionEditor
        title="Social links"
        items={state.socialLinks as unknown as Array<Record<string, string | undefined>>}
        onChange={(items) =>
          update({
            socialLinks: items as unknown as SocialLink[],
          })
        }
        fields={[
          { key: "platform", label: "Platform" },
          { key: "url", label: "URL" },
        ]}
      />

      <div className="flex flex-wrap items-center gap-3">
        <label className="flex items-center gap-2 text-sm">
          <input
            type="checkbox"
            checked={state.published}
            onChange={(e) => update({ published: e.target.checked })}
          />
          Published
        </label>
        <Field label="Display order">
          <input
            type="number"
            value={state.displayOrder}
            onChange={(e) => update({ displayOrder: Number(e.target.value) })}
            className="input w-24"
          />
        </Field>
        <div className="flex-1" />
        <Button type="submit" isLoading={pending}>
          Save about content
        </Button>
      </div>
      <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>
  );
}

function SectionEditor({
  title,
  items,
  onChange,
  fields,
}: {
  title: string;
  items: Array<Record<string, string | undefined>>;
  onChange: (items: Array<Record<string, string | undefined>>) => void;
  fields: { key: string; label: string; textarea?: boolean }[];
}) {
  return (
    <div>
      <p className="mb-2 text-sm font-medium text-foreground">{title}</p>
      <div className="space-y-2">
        {items.map((item, idx) => (
          <div key={idx} className="rounded-xl border border-border p-3">
            <div className="grid gap-2 sm:grid-cols-2">
              {fields.map((f) => (
                <div key={f.key} className={f.textarea ? "sm:col-span-2" : ""}>
                  <label className="mb-1 block text-xs font-medium text-muted">
                    {f.label}
                  </label>
                  {f.textarea ? (
                    <textarea
                      value={item[f.key] ?? ""}
                      onChange={(e) =>
                        onChange(
                          items.map((x, i) =>
                            i === idx
                              ? { ...x, [f.key]: e.target.value }
                              : x,
                          ),
                        )
                      }
                      rows={2}
                      className="input"
                    />
                  ) : (
                    <input
                      value={item[f.key] ?? ""}
                      onChange={(e) =>
                        onChange(
                          items.map((x, i) =>
                            i === idx
                              ? { ...x, [f.key]: e.target.value }
                              : x,
                          ),
                        )
                      }
                      className="input"
                    />
                  )}
                </div>
              ))}
            </div>
            <button
              type="button"
              onClick={() => onChange(items.filter((_, i) => i !== idx))}
              className="mt-2 rounded-lg border border-border px-2 py-1 text-xs text-red-600"
            >
              Remove
            </button>
          </div>
        ))}
        <button
          type="button"
          onClick={() =>
            onChange([
              ...items,
              Object.fromEntries(fields.map((f) => [f.key, ""])),
            ])
          }
          className="rounded-lg border border-border bg-surface px-3 py-1.5 text-xs"
        >
          + Add {title.toLowerCase().replace(/s$/, "")}
        </button>
      </div>
    </div>
  );
}