import { useEffect } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { Button } from "@/shared/common/ui/button";
import {
  Form,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
  FormControl,
} from "@/shared/common/ui/form";
import { Input } from "@/shared/common/ui/input";

import {
  CreateRecordTagPayload,
  UpdateRecordTagPayload,
} from "@/user-management/dto/recordTags/recordTags.type";
import { useRecordTags } from "@/user-management/hooks/useRecordTags";

const recordTagSchema = z.object({
  nameAm: z.string().min(1, "Amharic name is required"),
  nameEn: z.string().min(1, "English name is required"),
  key: z.string().min(1, "Key is required"),
  unitId: z.string().min(1, "Unit is required"),
});

export type RecordTagFormValues = z.infer<typeof recordTagSchema>;

interface RecordTagFormProps {
  defaultValues?: Partial<RecordTagFormValues>;
  unitId: string;
  mode: "create" | "edit";
  id?: string; // required if edit
  onSuccess?: () => void;
}

export function RecordTagForm({
  defaultValues,
  unitId,
  mode,
  id,
  onSuccess,
}: RecordTagFormProps) {
  const form = useForm<RecordTagFormValues>({
    resolver: zodResolver(recordTagSchema),
    defaultValues: {
      nameAm: defaultValues?.nameAm ?? "",
      nameEn: defaultValues?.nameEn ?? "",
      key: defaultValues?.key ?? "",
      unitId: defaultValues?.unitId ?? unitId,
    },
  });

  const {
    createRecordTag,
    updateRecordTag,
    isCreatingRecordTag,
    isUpdatingRecordTag,
  } = useRecordTags({ unitId });

  const handleSubmit = (values: RecordTagFormValues) => {
    if (mode === "create") {
      const payload: CreateRecordTagPayload = {
        name: { am: values.nameAm, en: values.nameEn },
        key: values.key,
        unitId: values.unitId,
      };
      createRecordTag(payload, {
        onSuccess: () => {
          form.reset();
          onSuccess?.();
        },
      });
    } else if (mode === "edit" && id) {
      const payload: UpdateRecordTagPayload = {
        name: { am: values.nameAm, en: values.nameEn },
        key: values.key,
        unitId: values.unitId,
      };
      updateRecordTag(
        { id, payload },
        {
          onSuccess: () => {
            onSuccess?.();
          },
        }
      );
    }
  };

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-4">
        <FormField
          control={form.control}
          name="nameAm"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Amharic Name</FormLabel>
              <FormControl>
                <Input placeholder="Enter Amharic name" {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="nameEn"
          render={({ field }) => (
            <FormItem>
              <FormLabel>English Name</FormLabel>
              <FormControl>
                <Input placeholder="Enter English name" {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="key"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Key</FormLabel>
              <FormControl>
                <Input placeholder="Unique key" {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <Button
          type="submit"
          disabled={isCreatingRecordTag || isUpdatingRecordTag}
        >
          {mode === "create"
            ? isCreatingRecordTag
              ? "Creating..."
              : "Create"
            : isUpdatingRecordTag
            ? "Updating..."
            : "Update"}
        </Button>
      </form>
    </Form>
  );
}
