"use client";

import { FormSkeleton } from "@/components/ui/form-skeleton";
import { SERVICE_UPSERT_FORM_ID } from "@/components/dashboard/services/service-upsert-constants";
import { ServiceUpsertFormView } from "@/components/dashboard/services/service-upsert-form-view";
import type { ServiceUpsertFormValues } from "@/components/dashboard/services/services-types";
import { createService, useService, updateService } from "@/components/dashboard/services/services-api";
import { Button } from "@/components/ui/button";
import { Link } from "@/i18n/routing";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { useEffect } from "react";

interface ServiceUpsertFormProps {
  mode: "create" | "edit";
  serviceId?: number;
}

const EMPTY_DEFAULTS: ServiceUpsertFormValues = {
  title: "",
  short_description: "",
  description: "",
  icon: "",
  image: null,
  is_active: false,
  order: 0,
};

export function ServiceUpsertForm({ mode, serviceId }: ServiceUpsertFormProps) {
  const t = useTranslations("dashboard.services");
  const router = useRouter();

  const isEdit = mode === "edit" && serviceId !== undefined && Number.isFinite(serviceId) && serviceId > 0;
  const { service, isLoading, error, refetch } = useService(isEdit ? serviceId : undefined);

  const form = useForm<ServiceUpsertFormValues>({
    defaultValues: EMPTY_DEFAULTS,
    mode: "onBlur",
  });

  useEffect(() => {
    if (service) {
      form.reset({
        title: service.title,
        short_description: service.short_description,
        description: service.description,
        icon: service.icon,
        image: null,
        is_active: service.is_active,
        order: service.order,
      });
    }
  }, [service, form]);

  const onSubmit = async (values: ServiceUpsertFormValues) => {
    try {
      if (isEdit && serviceId !== undefined) {
        await updateService(serviceId, values);
      } else {
        await createService(values);
      }
      router.push("/dashboard/services");
    } catch {
      // Form stays open on failure; user input is preserved
    }
  };

  // Not-found state for invalid edit id
  if (mode === "edit" && (!serviceId || !Number.isFinite(serviceId) || serviceId <= 0)) {
    return (
      <section className="rounded-3xl border border-border bg-background p-8 text-center shadow-sm">
        <h1 className="text-2xl font-semibold text-foreground">
          {t("titles.notFound")}
        </h1>
        <p className="mx-auto mt-3 max-w-xl text-sm text-muted-foreground">
          {t("form.notFoundDescription")}
        </p>
        <Button asChild className="mt-6 h-12 rounded-xl px-6">
          <Link href="/dashboard/services">{t("actions.backToServices")}</Link>
        </Button>
      </section>
    );
  }

  if (isEdit && isLoading) {
    return (
      <section className="rounded-3xl border border-border bg-background p-8 shadow-sm">
        <FormSkeleton rows={5} />
      </section>
    );
  }

  // Error state
  if (isEdit && error && !service) {
    return (
      <section className="rounded-3xl border border-border bg-background p-8 text-center shadow-sm" 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>
    );
  }

  // Not-found state (valid id but no service returned)
  if (isEdit && !isLoading && !service) {
    return (
      <section className="rounded-3xl border border-border bg-background p-8 text-center shadow-sm">
        <h1 className="text-2xl font-semibold text-foreground">
          {t("titles.notFound")}
        </h1>
        <p className="mx-auto mt-3 max-w-xl text-sm text-muted-foreground">
          {t("form.notFoundDescription")}
        </p>
        <Button asChild className="mt-6 h-12 rounded-xl px-6">
          <Link href="/dashboard/services">{t("actions.backToServices")}</Link>
        </Button>
      </section>
    );
  }

  return (
    <ServiceUpsertFormView
      form={form}
      formId={SERVICE_UPSERT_FORM_ID}
      mode={mode}
      currentImagePath={isEdit && service ? service.image : undefined}
      onSubmit={onSubmit}
      isSubmitting={form.formState.isSubmitting}
    />
  );
}
