"use client";

import { useState } from "react";

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

import { FormPageHeader, 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 { cn } from "@/lib/utils";

import {
  GATEWAY_MODE_OPTIONS,
  GATEWAY_STATUS_OPTIONS,
  SORT_ORDER_OPTIONS,
} from "./constants";
import type { GatewayConfig } from "./configs";
import { createGatewaySchema } from "./schema";
import type { z } from "zod";

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

type Props = {
  config: GatewayConfig;
};

function selectOptionsFor(key: NonNullable<GatewayConfig["fields"][number]["optionsKey"]>) {
  if (key === "status") return GATEWAY_STATUS_OPTIONS;
  if (key === "mode") return GATEWAY_MODE_OPTIONS;
  return SORT_ORDER_OPTIONS;
}

export function GatewaySettingsForm({ config }: Props) {
  const [isSaving, setIsSaving] = useState(false);
  const schema = createGatewaySchema(config);
  type FormValues = z.infer<typeof schema>;

  const form = useForm<FormValues>({
    resolver: zodResolver(schema),
    defaultValues: config.defaults as FormValues,
  });

  const onSubmit = form.handleSubmit(async (values) => {
    setIsSaving(true);
    await new Promise((resolve) => setTimeout(resolve, 600));
    setIsSaving(false);
    toast.success(`${config.title} settings saved`);
    form.reset(values);
  });

  return (
    <form onSubmit={onSubmit} className="pb-4">
      <FormPageHeader
        backHref={LIST_HREF}
        breadcrumb={[
          { label: "Plans & Orders" },
          { label: "Payment gateways", href: LIST_HREF },
          { label: config.title },
        ]}
        titleIcon={<ArrowLeftRight className="size-5 text-primary" />}
        title={config.title}
        description={config.description}
      />

      <FormPanel title="Gateway settings">
        <div className="grid gap-5 sm:grid-cols-2">
          {config.fields.map((field) => {
            const spanClass = field.span === "full" ? "sm:col-span-2" : "";
            const error = form.formState.errors[field.name] as { message?: string } | undefined;

            if (field.type === "select" && field.optionsKey) {
              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={field.required}
                        description={field.description}
                        error={error}
                      >
                        <FormSelect
                          id={field.name}
                          value={controllerField.value ?? ""}
                          onChange={controllerField.onChange}
                          placeholder={`Select ${field.label.toLowerCase()}`}
                          options={selectOptionsFor(field.optionsKey!)}
                        />
                      </FormField>
                    )}
                  />
                </div>
              );
            }

            if (field.type === "textarea") {
              return (
                <div key={field.name} className={cn("sm:col-span-2", spanClass)}>
                  <Controller
                    name={field.name}
                    control={form.control}
                    render={({ field: controllerField }) => (
                      <FormField
                        label={field.label}
                        htmlFor={field.name}
                        required={field.required}
                        description={field.description}
                        error={error}
                      >
                        <Textarea
                          id={field.name}
                          rows={5}
                          placeholder={field.placeholder}
                          className="resize-y min-h-[120px]"
                          {...controllerField}
                        />
                      </FormField>
                    )}
                  />
                </div>
              );
            }

            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={field.required}
                      description={field.description}
                      error={error}
                    >
                      <Input
                        id={field.name}
                        type={field.type === "password" ? "password" : field.type === "email" ? "email" : "text"}
                        placeholder={field.placeholder}
                        autoComplete={field.type === "password" ? "off" : undefined}
                        {...controllerField}
                      />
                    </FormField>
                  )}
                />
              </div>
            );
          })}
        </div>
      </FormPanel>

      <FormSaveBar
        cancelHref={LIST_HREF}
        isSaving={isSaving}
        onReset={() => form.reset(config.defaults)}
      />
    </form>
  );
}
