"use client";

import { FormSkeleton } from "@/components/ui/form-skeleton";
import {
  type WidgetUpsertFormValues,
} from "@/components/dashboard/appearance/appearance-types";
import { AppearanceSubnavCard } from "@/components/dashboard/appearance/appearance-subnav-card";
import { WIDGET_FORM_ID } from "@/components/dashboard/appearance/widget-form-constants";
import { WidgetUpsertFormView } from "@/components/dashboard/appearance/widget-upsert-form-view";
import { createWidgetUpsertSchema } from "@/components/dashboard/appearance/widget-upsert-schema";
import { SettingsPageLayout } from "@/components/dashboard/settings/settings-page-layout";
import { Button } from "@/components/ui/button";
import { Link } from "@/i18n/routing";
import { createWidget, updateWidget, useWidget } from "@/lib/api/dashboard/widgets-api";
import { zodResolver } from "@hookform/resolvers/zod";
import { useLocale, useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";

interface WidgetFormControllerProps {
  mode: "create" | "edit";
  widgetId?: number;
}

export function WidgetFormController({ mode, widgetId }: WidgetFormControllerProps) {
  const t = useTranslations("dashboard.appearance.widgets");
  const tActions = useTranslations("dashboard.appearance.actions");
  const locale = useLocale();
  const router = useRouter();
  const isEdit = mode === "edit" && Number.isFinite(widgetId ?? NaN) && (widgetId ?? 0) > 0;
  const { widget, isLoading, error, refetch } = useWidget(isEdit ? widgetId : null);

  const [formReady, setFormReady] = useState(mode === "create");

  const form = useForm<WidgetUpsertFormValues>({
    defaultValues: {
      title: "",
      language: locale === "ar" ? "ar" : "en",
      position: "sidebar",
      content_type: "html",
      content: "",
      order: 0,
      is_active: true,
    },
    resolver: zodResolver(
      createWidgetUpsertSchema({ required: t("form.validation.required") }),
    ),
    mode: "onBlur",
  });

  useEffect(() => {
    if (widget) {
      form.reset({
        title: widget.title,
        language: widget.language,
        position: widget.position,
        content_type: widget.content_type,
        content: widget.content,
        order: widget.order,
        is_active: widget.is_active,
      });
      // eslint-disable-next-line react-hooks/set-state-in-effect -- intentional: re-render after form.reset() so Radix Select mounts with the correct initial value
      setFormReady(true);
    }
  }, [form, widget]);

  const onSubmit = async (values: WidgetUpsertFormValues) => {
    try {
      if (isEdit && widgetId !== undefined) {
        await updateWidget(widgetId, values);
      } else {
        await createWidget(values);
      }
      router.push("/dashboard/appearance/widgets");
    } catch {
      // Keep the form open on failure; the interceptor toast explains the issue.
    }
  };

  if (mode === "edit" && (!widgetId || !Number.isFinite(widgetId) || widgetId <= 0)) {
    return (
      <SettingsPageLayout sideContent={<AppearanceSubnavCard activeId="widgets" />}>
        <section className="rounded-2xl border border-border bg-card p-8 text-center">
          <h1 className="text-xl font-semibold text-foreground">{t("form.notFound")}</h1>
          <Button asChild className="mt-6 h-12 rounded-xl px-6">
            <Link href="/dashboard/appearance/widgets">{tActions("back")}</Link>
          </Button>
        </section>
      </SettingsPageLayout>
    );
  }

  if (isEdit && (isLoading || !formReady)) {
    return (
      <SettingsPageLayout sideContent={<AppearanceSubnavCard activeId="widgets" />}>
        <section className="rounded-2xl border border-border bg-card p-8">
          <FormSkeleton rows={4} />
        </section>
      </SettingsPageLayout>
    );
  }

  if (isEdit && error && !widget) {
    return (
      <SettingsPageLayout sideContent={<AppearanceSubnavCard activeId="widgets" />}>
        <section className="rounded-2xl border border-border bg-card p-8 text-center" role="alert">
          <p className="text-sm text-muted-foreground">{t("error")}</p>
          <button type="button" className="mt-3 text-primary underline" onClick={() => refetch()}>
            {t("retry")}
          </button>
        </section>
      </SettingsPageLayout>
    );
  }

  if (isEdit && !isLoading && !widget) {
    return (
      <SettingsPageLayout sideContent={<AppearanceSubnavCard activeId="widgets" />}>
        <section className="rounded-2xl border border-border bg-card p-8 text-center">
          <h1 className="text-xl font-semibold text-foreground">{t("form.notFound")}</h1>
          <Button asChild className="mt-6 h-12 rounded-xl px-6">
            <Link href="/dashboard/appearance/widgets">{tActions("back")}</Link>
          </Button>
        </section>
      </SettingsPageLayout>
    );
  }

  return (
    <SettingsPageLayout sideContent={<AppearanceSubnavCard activeId="widgets" />}>
      <WidgetUpsertFormView
        form={form}
        formId={WIDGET_FORM_ID}
        onSubmit={onSubmit}
        isSubmitting={form.formState.isSubmitting}
      />
    </SettingsPageLayout>
  );
}
