"use client";

import React, { useEffect, useState } from "react";
import { useForm, Controller } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import { Card } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { errorAutoClose, loading, successAutoClose } from "@/lib/swal";
import { close } from "@/config/swal";
import { getUserLevelDetail, updateUserLevel } from "@/service/tenant";

const tenantSchema = z.object({
  aliasName: z.string().trim().min(1, { message: "Alias Name wajib diisi" }),
  levelNumber: z
    .number({
      invalid_type_error: "Level Number harus berupa angka",
    })
    .min(1, { message: "Level Number minimal 1" }),
  name: z.string().trim().min(1, { message: "Name wajib diisi" }),
});

type TenantSchema = z.infer<typeof tenantSchema>;

interface TenantUpdateFormProps {
  id: number;
  /** ✅ Tambahkan properti ini */
  initialData?: {
    name: string;
    aliasName: string;
    levelNumber: number;
    parentLevelId?: number;
    provinceId?: number;
    group: string;
    isApprovalActive: boolean;
    isActive: boolean;
  };
  onSuccess?: () => void;
  onCancel?: () => void;
}

export default function TenantUpdateForm({
  id,
  onSuccess,
  onCancel,
}: TenantUpdateFormProps) {
  const MySwal = withReactContent(Swal);
  const [loadingData, setLoadingData] = useState(false);

  const {
    control,
    handleSubmit,
    setValue,
    formState: { errors },
  } = useForm<TenantSchema>({
    resolver: zodResolver(tenantSchema),
    defaultValues: {
      aliasName: "",
      levelNumber: 1,
      name: "",
    },
  });

  useEffect(() => {
    async function getDetail() {
      setLoadingData(true);
      try {
        const response = await getUserLevelDetail(id);

        if (!response.error && response.data) {
          const detail = response.data;

          setValue("aliasName", detail.aliasName ?? "");
          setValue("levelNumber", detail.levelNumber ?? 1);
          setValue("name", detail.name ?? "");
        } else {
          console.error("Gagal mengambil detail:", response.message);
        }
      } catch (err) {
        console.error("Error fetching detail:", err);
      } finally {
        setLoadingData(false);
      }
    }

    if (id) getDetail();
  }, [id, setValue]);

  const onSubmit = async (data: TenantSchema) => {
    try {
      loading();

      const payload = {
        aliasName: data.aliasName,
        levelNumber: data.levelNumber,
        name: data.name,
      };

      console.log("Payload dikirim ke API:", payload);

      const response = await updateUserLevel(Number(id), payload);

      close();

      if (response?.error) {
        errorAutoClose(response.message || "Gagal memperbarui data.");
        return;
      }

      successAutoClose("Data berhasil diperbarui.");

      setTimeout(() => {
        if (onSuccess) onSuccess();
      }, 3000);
    } catch (err) {
      close();
      errorAutoClose("Terjadi kesalahan saat menyimpan data.");
      console.error("Update user level error:", err);
    }
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Card className="p-6 w-full lg:w-2/3">
        <h2 className="text-lg font-semibold mb-4">
          Update Tenant (User Level)
        </h2>

        <div className="space-y-4">
          {/* Alias Name */}
          <div>
            <Label>Alias Name</Label>
            <Controller
              control={control}
              name="aliasName"
              render={({ field }) => (
                <Input {...field} placeholder="Masukkan alias name" />
              )}
            />
            {errors.aliasName && (
              <p className="text-red-500 text-sm">{errors.aliasName.message}</p>
            )}
          </div>

          {/* Level Number */}
          <div>
            <Label>Level Number</Label>
            <Controller
              control={control}
              name="levelNumber"
              render={({ field }) => (
                <Input
                  type="number"
                  {...field}
                  onChange={(e) => field.onChange(Number(e.target.value) || 1)}
                  placeholder="Masukkan level number"
                />
              )}
            />
            {errors.levelNumber && (
              <p className="text-red-500 text-sm">
                {errors.levelNumber.message}
              </p>
            )}
          </div>

          {/* Name */}
          <div>
            <Label>Nama</Label>
            <Controller
              control={control}
              name="name"
              render={({ field }) => (
                <Input {...field} placeholder="Masukkan nama" />
              )}
            />
            {errors.name && (
              <p className="text-red-500 text-sm">{errors.name.message}</p>
            )}
          </div>
        </div>

        {/* Action Buttons */}
        <div className="mt-6 flex justify-end gap-3">
          <Button type="submit">Update</Button>
          <Button type="button" variant="outline" onClick={() => onCancel?.()}>
            Cancel
          </Button>
        </div>
      </Card>
    </form>
  );
}
