"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import type { StorefrontAccountSession } from "@/types/storefront";

type AuthFormField = {
  id: string;
  label: string;
  type?: string;
  required?: boolean;
  fullWidth?: boolean;
};

function AuthField({
  field,
  value,
  onChange,
}: {
  field: AuthFormField;
  value: string;
  onChange: (value: string) => void;
}) {
  return (
    <label className={field.fullWidth ? "space-y-3 md:col-span-2" : "space-y-3"}>
      <span className="block text-[14px] font-bold leading-[1.3] tracking-[-0.02em] text-primary">
        {field.label}
        {field.required !== false ? <span className="text-accent"> *</span> : null}
      </span>
      <input
        type={field.type ?? "text"}
        value={value}
        onChange={(event) => onChange(event.target.value)}
        className="h-[52px] w-full appearance-none rounded-[6px] border border-black/10 bg-white px-5 text-[16px] font-medium leading-[1.5] tracking-[-0.02em] text-primary outline-none transition-colors placeholder:text-primary/35 focus:border-accent"
      />
    </label>
  );
}

function buildSessionFromValues({
  mode,
  values,
}: {
  mode: "login" | "register-person" | "register-company";
  values: Record<string, string>;
}): Partial<StorefrontAccountSession> {
  if (mode === "login") {
    const email = values.email.trim();
    const localPart = email.split("@")[0] || "Korisnik";
    const firstName = localPart.charAt(0).toUpperCase() + localPart.slice(1);

    return {
      email,
      firstName,
      lastName: "Kupac",
      accountType: "person",
    };
  }

  if (mode === "register-company") {
    return {
      email: values.email.trim(),
      firstName: values.firstName.trim(),
      lastName: values.lastName.trim(),
      phone: values.phone.trim(),
      address1: values.address1.trim(),
      postcode: values.postcode.trim(),
      city: values.city.trim(),
      companyName: values.companyName.trim(),
      companyAddress: values.companyAddress.trim(),
      oib: values.oib.trim(),
      accountType: "company",
    };
  }

  return {
    email: values.email.trim(),
    firstName: values.firstName.trim(),
    lastName: values.lastName.trim(),
    phone: values.phone.trim(),
    address1: values.address1.trim(),
    postcode: values.postcode.trim(),
    city: values.city.trim(),
    accountType: "person",
  };
}

export function AuthFormShell({
  mode,
  title,
  fields,
  submitLabel,
  secondaryHref,
  secondaryLabel,
  helperLabel,
  helperHref,
  helperText,
}: {
  mode: "login" | "register-person" | "register-company";
  title: string;
  fields: AuthFormField[];
  submitLabel: string;
  secondaryHref: string;
  secondaryLabel: string;
  helperLabel?: string;
  helperHref?: string;
  helperText?: string;
}) {
  const router = useRouter();
  const [values, setValues] = useState<Record<string, string>>(
    Object.fromEntries(fields.map((field) => [field.id, ""])),
  );
  const [issues, setIssues] = useState<string[]>([]);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [message, setMessage] = useState<string | null>(null);

  function setFieldValue(id: string, value: string) {
    setValues((current) => ({
      ...current,
      [id]: value,
    }));
  }

  function validate() {
    const nextIssues: string[] = [];

    fields.forEach((field) => {
      if (field.required === false) {
        return;
      }

      if (!values[field.id]?.trim()) {
        nextIssues.push(`Unesite polje: ${field.label}.`);
      }
    });

    return nextIssues;
  }

  async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const nextIssues = validate();

    if (nextIssues.length > 0) {
      setIssues(nextIssues);
      setMessage(null);
      return;
    }

    setIssues([]);
    setMessage(null);
    setIsSubmitting(true);

    try {
      const response = await fetch("/api/account/session", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(buildSessionFromValues({ mode, values })),
      });

      const payload = (await response.json()) as {
        message?: string;
      };

      if (!response.ok) {
        throw new Error(payload.message || "Spremanje korisničkog računa nije uspjelo.");
      }

      router.push("/my-account");
      router.refresh();
    } catch (error) {
      setMessage(
        error instanceof Error ? error.message : "Spremanje korisničkog računa nije uspjelo.",
      );
    } finally {
      setIsSubmitting(false);
    }
  }

  return (
    <section className="pb-20 pt-[80px]">
      <div className="mx-auto w-full max-w-[610px] space-y-[42px]">
        <div className="flex justify-center">
          <h1 className="text-center text-[28px] font-bold leading-[1.2] tracking-[-0.03em] text-primary">
            {title}
          </h1>
        </div>

        <form className="space-y-6" onSubmit={handleSubmit}>
          {issues.length > 0 ? (
            <div className="rounded-[6px] border border-accent/20 bg-accent/5 px-5 py-4">
              <ul className="space-y-1">
                {issues.map((issue) => (
                  <li
                    key={issue}
                    className="text-[14px] font-medium leading-[1.5] tracking-[-0.02em] text-accent"
                  >
                    {issue}
                  </li>
                ))}
              </ul>
            </div>
          ) : null}

          <div className="grid gap-x-6 gap-y-6 md:grid-cols-2">
            {fields.map((field) => (
              <AuthField
                key={field.id}
                field={field}
                value={values[field.id] ?? ""}
                onChange={(value) => setFieldValue(field.id, value)}
              />
            ))}
          </div>

          {helperLabel && helperHref ? (
            <div className="-mt-2">
              <Link
                href={helperHref}
                className="text-[14px] font-medium leading-[1.2] tracking-[-0.02em] text-primary/60 underline"
              >
                {helperLabel}
              </Link>
            </div>
          ) : null}

          {message ? (
            <p className="text-[14px] font-medium leading-[1.5] tracking-[-0.02em] text-accent">
              {message}
            </p>
          ) : null}

          <Button
            type="submit"
            className="w-full cursor-pointer rounded-[6px]"
            disabled={isSubmitting}
          >
            {submitLabel}
          </Button>

          <p className="text-center text-[14px] font-medium leading-[1.2] tracking-[-0.02em] text-primary/60">
            {helperText ? <span>{helperText} </span> : null}
            <Link href={secondaryHref} className="text-accent underline">
              {secondaryLabel}
            </Link>
          </p>
        </form>
      </div>
    </section>
  );
}
