"use client";

import { FormSkeleton } from "@/components/ui/form-skeleton";
import { Button } from "@/components/ui/button";
import { Link } from "@/i18n/routing";
import { PREVIOUS_WORK_FORM_ID } from "@/components/dashboard/previous-work/previous-work-form-constants";
import { createWork, updateWork, useWork } from "@/lib/api/dashboard/works-api";
import { getAssetUrl } from "@/lib/api-enabled";
import { useServices } from "@/components/dashboard/services/services-api";
import { createPreviousWorkUpsertSchema } from "@/components/dashboard/previous-work/previous-work-upsert-schema";
import type { PreviousWorkUpsertFormValues } from "@/components/dashboard/previous-work/previous-work-types";
import { PreviousWorkFormView } from "@/components/dashboard/previous-work/previous-work-form-view";
import { zodResolver } from "@hookform/resolvers/zod";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { useEffect, useMemo, useState } from "react";
import { useForm } from "react-hook-form";

interface PreviousWorkFormControllerProps {
  mode: "create" | "edit";
  workId?: number;
}

const EMPTY_DEFAULTS: PreviousWorkUpsertFormValues = {
  service_id: 0,
  title: "",
  short_description: "",
  description: "",
  client_name: "",
  image: null,
  gallery: [],
  is_featured: false,
  is_active: true,
  order: 0,
};

export function PreviousWorkFormController({ mode, workId }: PreviousWorkFormControllerProps) {
  const t = useTranslations("dashboard.previousWork");
  const router = useRouter();
  const isEdit = mode === "edit" && Number.isFinite(workId ?? NaN) && (workId ?? 0) > 0;
  const { work, isLoading, error, refetch } = useWork(isEdit ? workId : null);
  const { services } = useServices();

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

  const form = useForm<PreviousWorkUpsertFormValues>({
    defaultValues: EMPTY_DEFAULTS,
    resolver: zodResolver(
      createPreviousWorkUpsertSchema({
        required: t("form.validation.required"),
        image: t("form.validation.image"),
        imageSize: t("form.validation.imageSize"),
        galleryImage: t("form.validation.image"),
      }),
    ),
    mode: "onBlur",
  });

  useEffect(() => {
    if (work) {
      form.reset({
        service_id: work.service_id,
        title: work.title,
        short_description: work.short_description,
        description: work.description,
        client_name: work.client_name,
        image: null,
        gallery: [],
        is_featured: work.is_featured,
        is_active: work.is_active,
        order: work.order,
      });
      // 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, work]);

  const serviceOptions = useMemo(() => {
    const mapped = (services || []).map((service) => ({
      id: service.id,
      label: service.title || String(service.id),
      is_active: service.is_active,
    }));

    if (!work) {
      return mapped.filter((service) => service.is_active);
    }

    const selectedService = work.service_id;
    const selectedExists = mapped.some((service) => service.id === selectedService);

    if (!selectedExists) {
      const selectedLabel =
        typeof work.service === "object" && work.service
          ? work.service.title || work.service.name || String(selectedService)
          : String(selectedService);

      return [{ id: selectedService, label: selectedLabel }, ...mapped];
    }

    return mapped;
  }, [services, work]);

  const onSubmit = async (values: PreviousWorkUpsertFormValues) => {
    try {
      if (isEdit && workId !== undefined) {
        await updateWork(workId, values);
      } else {
        await createWork(values);
      }
      router.push("/dashboard/previous-work");
    } catch {
      // Keep the form open on failure; the toast already explains the issue.
    }
  };

  if (mode === "edit" && (!workId || !Number.isFinite(workId) || workId <= 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/previous-work">{t("actions.backToList")}</Link>
        </Button>
      </section>
    );
  }

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

  if (isEdit && error && !work) {
    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>
    );
  }

  if (isEdit && !isLoading && !work) {
    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/previous-work">{t("actions.backToList")}</Link>
        </Button>
      </section>
    );
  }

  return (
    <PreviousWorkFormView
      form={form}
      formId={PREVIOUS_WORK_FORM_ID}
      mode={mode}
      serviceOptions={serviceOptions}
      currentImagePath={isEdit && work?.image ? getAssetUrl(work.image) : undefined}
      onSubmit={onSubmit}
      isSubmitting={form.formState.isSubmitting}
    />
  );
}
