"use client";

import { useAppForm, useFormFields } from "@/components/ui/tanstack-form";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  createTrainingMatrixMutation,
  updateTrainingMatrixMutation,
} from "../api/mutations";
import type { TrainingMatrix } from "../api/types";
import { useMutation, useSuspenseQuery } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import * as z from "zod";
import { trainingMatrixOptionsQueryOptions } from "../api/queries";
import {
  trainingMatrixSchema,
  type TrainingMatrixFormValues,
} from "../schemas/training-matrix";

export default function TrainingMatrixForm({
  initialData,
  pageTitle,
}: {
  initialData: TrainingMatrix | null;
  pageTitle: string;
}) {
  const router = useRouter();
  const isEdit = !!initialData;
  const { data: options } = useSuspenseQuery(
    trainingMatrixOptionsQueryOptions(),
  );

  const createMutation = useMutation({
    ...createTrainingMatrixMutation,
    onSuccess: () => {
      toast.success("Training matrix created successfully");
      router.push("/dashboard/training-matrix");
    },
    onError: () => {
      toast.error("Failed to create training matrix");
    },
  });

  const updateMutation = useMutation({
    ...updateTrainingMatrixMutation,
    onSuccess: () => {
      toast.success("Training matrix updated successfully");
      router.push("/dashboard/training-matrix");
    },
    onError: () => {
      toast.error("Failed to update training matrix");
    },
  });

  const form = useAppForm({
    defaultValues: {
      departmentId: initialData?.department_id
        ? String(initialData.department_id)
        : "",
      positionId: initialData?.position_id
        ? String(initialData.position_id)
        : "",
      courseId: initialData ? String(initialData.course_id) : "",
      isRequired: initialData?.is_required ?? true,
      renewalPeriodMonths: initialData?.renewal_period_months ?? undefined,
      note: initialData?.note ?? "",
    } as TrainingMatrixFormValues,
    validators: {
      onSubmit: trainingMatrixSchema,
    },
    onSubmit: async ({ value }) => {
      const payload = {
        departmentId: value.departmentId ? Number(value.departmentId) : null,
        positionId: value.positionId ? Number(value.positionId) : null,
        courseId: Number(value.courseId),
        isRequired: value.isRequired,
        renewalPeriodMonths: value.renewalPeriodMonths,
        note: value.note,
      };

      if (isEdit) {
        updateMutation.mutate({ id: initialData.id, values: payload });
      } else {
        createMutation.mutate(payload);
      }
    },
  });

  const { FormSelectField, FormSwitchField, FormTextField, FormTextareaField } =
    useFormFields<TrainingMatrixFormValues>();

  return (
    <Card className="mx-auto w-full">
      <CardHeader>
        <CardTitle className="text-left text-2xl font-bold">
          {pageTitle}
        </CardTitle>
      </CardHeader>
      <CardContent>
        <form.AppForm>
          <form.Form className="space-y-8">
            <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
              <FormSelectField
                name="departmentId"
                label="ฝ่ายงาน"
                options={options.departments}
                placeholder="Select department"
              />

              <FormSelectField
                name="positionId"
                label="ตำแหน่ง"
                options={options.positions}
                placeholder="Select position"
              />

              <FormSelectField
                name="courseId"
                label="หลักสูตร"
                required
                options={options.courses}
                placeholder="Select course"
                validators={{
                  onBlur: z.string().min(1, "Please select a course"),
                }}
              />

              <FormTextField
                name="renewalPeriodMonths"
                label="Renewal Period (Months)"
                type="number"
                min={0}
                step={1}
                placeholder="Leave empty to use course validity"
                validators={{
                  onBlur: z.number().int().min(0).optional(),
                }}
              />
            </div>

            <FormSwitchField
              name="isRequired"
              label="Required Rule"
              description="When enabled, the selected course becomes mandatory for the target group."
            />

            <FormTextareaField
              name="note"
              label="Note"
              placeholder="Add internal note for this matrix rule"
              maxLength={500}
              rows={4}
            />

            <div className="flex justify-end gap-2">
              <Button
                type="button"
                variant="outline"
                onClick={() => router.back()}
              >
                Back
              </Button>
              <form.SubmitButton>
                {isEdit ? "แก้ไขแผนการอบรม" : "สร้างแผนการอบรม"}
              </form.SubmitButton>
            </div>
          </form.Form>
        </form.AppForm>
      </CardContent>
    </Card>
  );
}
