"use client";

import { useMemo, useState } from "react";

import { zodResolver } from "@hookform/resolvers/zod";
import { Controller, useForm, useWatch, type FieldValues } from "react-hook-form";
import { toast } from "sonner";
import { useRouter } from "next/navigation";

import { FormPanel, FormSaveBar, FormSelect } from "@/app/dashboard/_components/form";
import { FormField } from "@/components/form/form-field";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { FRONTEND_ROUTES } from "@/config/frontend-routes";
import { isApiSuccess } from "@/lib/api-messages";
import { requestDashboardApi } from "@/lib/dashboard-api-client";
import { toastApiError } from "@/lib/toast-api-error";

import type { GatewayCredential, GatewayField } from "../schema";
import { CredentialsEditor } from "./credentials-editor";
import { createGatewaySchema } from "./schema";

const LIST_HREF = "/dashboard/plans-orders/payment-gateways";

export type GatewayFormProps = {
  mode: "create" | "update";
  /** Template key (create) — sent so the backend knows what to register. */
  provider: string;
  /** Full method id, e.g. "payment-gateway-stripe" (update). */
  gatewayId?: string;
  fields: GatewayField[];
  initialValues: Record<string, string>;
  initialCredentials?: GatewayCredential[];
  /** Custom integrations: method type, mode and free-form credentials. */
  isCustom: boolean;
  panelTitle?: string;
};

/** Settings form shared by "register a payment method" and the per-method settings page. */
export function GatewayForm({
  mode,
  provider,
  gatewayId,
  fields,
  initialValues,
  initialCredentials = [],
  isCustom,
  panelTitle = "Settings",
}: GatewayFormProps) {
  const router = useRouter();
  const [isSaving, setIsSaving] = useState(false);

  const schema = useMemo(() => createGatewaySchema(fields, { isCustom }), [fields, isCustom]);
  const defaultValues = useMemo<FieldValues>(() => {
    const values: FieldValues = {};
    for (const field of fields) values[field.name] = initialValues[field.name] ?? "";
    values.credentials = initialCredentials;
    return values;
  }, [fields, initialValues, initialCredentials]);

  const form = useForm<FieldValues>({ resolver: zodResolver(schema), defaultValues });
  const methodType = useWatch({ control: form.control, name: "method_type" });
  const slug = useWatch({ control: form.control, name: "slug" });
  const offline = isCustom && methodType === "offline";
  const showCredentials = isCustom && !offline;

  const onSubmit = form.handleSubmit(async (values) => {
    setIsSaving(true);

    try {
      const payload: Record<string, unknown> = {};
      for (const field of fields) {
        if (offline && field.name === "mode") continue;
        payload[field.name] = values[field.name] ?? "";
      }
      if (mode === "create") payload.provider = provider;
      if (mode === "update") payload.id = gatewayId;
      if (showCredentials) {
        payload.credentials = (values.credentials as GatewayCredential[]).map((row) => ({
          key: row.key,
          label: row.label,
          value: row.value,
          secret: row.secret,
        }));
      }

      const data = await requestDashboardApi<{ status?: string; message?: string }>({
        url:
          mode === "create"
            ? FRONTEND_ROUTES.plansOrders.paymentGateways.createSubmit
            : FRONTEND_ROUTES.plansOrders.paymentGateways.updateSubmit,
        method: "POST",
        body: payload,
        fallbackError:
          mode === "create"
            ? "Payment method could not be registered."
            : "Payment method could not be saved.",
        validate: (response) => isApiSuccess(response),
      });

      toast.success(
        data.message?.trim() ||
          (mode === "create" ? "Payment method registered." : "Payment method saved."),
      );
      router.push(LIST_HREF);
      router.refresh();
    } catch (error) {
      toastApiError(error, "Payment method could not be saved.");
    } finally {
      setIsSaving(false);
    }
  });

  return (
    <form onSubmit={onSubmit} className="space-y-6">
      <FormPanel title={panelTitle}>
        <div className="grid gap-5 sm:grid-cols-2">
          {fields
            .filter((field) => !(offline && field.name === "mode"))
            .map((field) => {
              const error = form.formState.errors[field.name] as { message?: string } | undefined;
              const spanClass = field.span === "full" || field.type === "textarea" ? "sm:col-span-2" : "";
              const required = field.required || (isCustom && offline && field.name === "description");
              const placeholder =
                field.secret && field.hasValue
                  ? "•••••••• saved — leave blank to keep"
                  : field.placeholder;

              return (
                <div key={field.name} className={spanClass}>
                  <Controller
                    name={field.name}
                    control={form.control}
                    render={({ field: controllerField }) => (
                      <FormField
                        label={field.label}
                        htmlFor={field.name}
                        required={required && !(field.secret && field.hasValue)}
                        description={field.description}
                        error={error}
                      >
                        {field.type === "select" ? (
                          <FormSelect
                            id={field.name}
                            value={controllerField.value ?? ""}
                            onChange={controllerField.onChange}
                            placeholder={`Select ${field.label.toLowerCase()}`}
                            options={field.options ?? []}
                          />
                        ) : field.type === "textarea" ? (
                          <Textarea
                            id={field.name}
                            rows={4}
                            placeholder={placeholder}
                            className="min-h-[96px] resize-y"
                            {...controllerField}
                          />
                        ) : (
                          <Input
                            id={field.name}
                            type={
                              field.type === "password"
                                ? "password"
                                : field.type === "email"
                                  ? "email"
                                  : field.type === "number"
                                    ? "number"
                                    : "text"
                            }
                            min={field.min}
                            max={field.max}
                            placeholder={placeholder}
                            autoComplete={field.type === "password" ? "new-password" : undefined}
                            className="h-9"
                            {...controllerField}
                          />
                        )}
                      </FormField>
                    )}
                  />
                </div>
              );
            })}
        </div>
      </FormPanel>

      {showCredentials ? (
        <FormPanel title="Integration">
          <CredentialsEditor
            control={form.control}
            slugHint={mode === "update" ? gatewayId?.replace(/^payment-gateway-/, "") : slug}
            errors={form.formState.errors.credentials}
          />
        </FormPanel>
      ) : null}

      <FormSaveBar
        cancelHref={LIST_HREF}
        isSaving={isSaving}
        saveLabel={mode === "create" ? "Register" : "Save"}
        onReset={() => form.reset(defaultValues)}
      />
    </form>
  );
}
