"use client";

import { toastApiError } from "@/lib/toast-api-error";
import * as React from "react";

import { zodResolver } from "@hookform/resolvers/zod";
import { Mail } from "lucide-react";
import { useForm } from "react-hook-form";
import { toast } from "sonner";

import { FormPageHeader, FormSaveBar } from "@/app/dashboard/_components/form";
import { useDashboardFormSubmit } from "@/app/dashboard/_components/use-dashboard-form-submit";
import { FormField } from "@/components/form/form-field";
import { ErrorBanner } from "@/components/shared/error-banner";
import { Input } from "@/components/ui/input";
import { FRONTEND_ROUTES } from "@/config/frontend-routes";
import { submitDashboardForm } from "@/lib/dashboard-mutations.client";
import { Button } from "@/components/ui/button";

import {
  customerCredentialsDefaults,
  customerCredentialsSchema,
  type CustomerCredentialsValues,
} from "./schema";

const LIST_HREF = "/dashboard/customers";

function credentialsListHref(parentCustomerId?: number) {
  return parentCustomerId
    ? `/dashboard/customers?parentCustomer=${parentCustomerId}`
    : LIST_HREF;
}

type CustomerCredentialsFormProps = {
  customerId: number;
  customerName?: string | null;
  initial?: CustomerCredentialsValues;
  initialErrorMessage?: string | null;
  parentCustomerId?: number;
  variant?: "page" | "modal";
  onSuccess?: () => void;
};

export function CustomerCredentialsForm({
  customerId,
  customerName = null,
  initial,
  initialErrorMessage = null,
  parentCustomerId,
  variant = "page",
  onSuccess,
}: CustomerCredentialsFormProps) {
  const listHref = credentialsListHref(parentCustomerId);

  const form = useForm<CustomerCredentialsValues>({
    resolver: zodResolver(customerCredentialsSchema),
    defaultValues: initial ?? customerCredentialsDefaults,
  });

  React.useEffect(() => {
    if (initial) {
      form.reset(initial);
    }
  }, [form, initial]);

  const { isSaving, submit } = useDashboardFormSubmit<CustomerCredentialsValues>({
    mode: "update",
    id: customerId,
    createUrl: FRONTEND_ROUTES.customers.credentialsSubmit,
    updateUrl: FRONTEND_ROUTES.customers.credentialsSubmit,
    listHref,
    saveFailMessage: "Customer credentials could not be sent.",
    messages: {
      createFail: "Customer credentials could not be sent.",
      updateFail: "Customer credentials could not be sent.",
      createSuccess: "Customer credentials sent.",
      updateSuccess: "Customer credentials sent.",
    },
  });

  const onSubmit = form.handleSubmit(async (values) => {
    if (variant === "modal") {
      try {
        const message = await submitDashboardForm({
          mode: "update",
          id: customerId,
          values,
          createUrl: FRONTEND_ROUTES.customers.credentialsSubmit,
          updateUrl: FRONTEND_ROUTES.customers.credentialsSubmit,
          messages: {
            createFail: "Customer credentials could not be sent.",
            updateFail: "Customer credentials could not be sent.",
            createSuccess: "Customer credentials sent.",
            updateSuccess: "Customer credentials sent.",
          },
        });
        toast.success(message);
        onSuccess?.();
      } catch (error) {
        toastApiError(error, "Customer credentials could not be sent.");
      }
      return;
    }

    await submit(values);
  });

  const errors = form.formState.errors;

  return (
    <form onSubmit={onSubmit} className="flex flex-col">
      <ErrorBanner message={initialErrorMessage} className="mb-4" />

      {variant === "page" ? (
        <FormPageHeader
          backHref={listHref}
          parentLabel="Customers"
          currentLabel="Send Customer Credential"
          titleIcon={<Mail className="size-4 text-primary" />}
          title="Send Customer Credential"
          description={
            customerName
              ? `Update login credentials for ${customerName} and send them by email.`
              : "Update login credentials and send them by email."
          }
        />
      ) : null}

      <div className="grid gap-4 md:grid-cols-2">
        <FormField label="E-mail address" required error={errors.email}>
          <Input
            type="email"
            autoComplete="email"
            className="h-9"
            {...form.register("email")}
          />
        </FormField>

        <FormField label="Confirm Email" required error={errors.confirm_email}>
          <Input
            type="email"
            autoComplete="email"
            className="h-9"
            {...form.register("confirm_email")}
          />
        </FormField>

        <FormField label="Enter Password" required error={errors.password}>
          <Input
            type="password"
            autoComplete="new-password"
            className="h-9"
            {...form.register("password")}
          />
        </FormField>

        <FormField label="Confirm Password" required error={errors.con_password}>
          <Input
            type="password"
            autoComplete="new-password"
            className="h-9"
            {...form.register("con_password")}
          />
        </FormField>
      </div>

      {variant === "page" ? (
        <FormSaveBar
          cancelHref={listHref}
          saveLabel="Send Email Credential"
          isSaving={isSaving}
        />
      ) : (
        <div className="mt-4 flex items-center justify-end gap-2">
          <Button type="button" variant="outline" onClick={() => onSuccess?.()} disabled={isSaving}>
            Cancel
          </Button>
          <Button type="submit" disabled={isSaving}>
            Send Email Credential
          </Button>
        </div>
      )}
    </form>
  );
}
