"use client";
import { useEffect } from "react";
import { useForm, Controller } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import { createMetal, editMetal } from "@/Services/Metals/ApiMetal";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import CustomInput from "@/components/ui/FormInput/CustomInput";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

const schema = yup.object({
  metal_name: yup.string().required("Metal name is required"),
  unit: yup.string().required("Unit is required"),
  purity: yup.string(),
  status: yup.boolean().default(true),
});

export default function AddMetalForm({
  type = "add",
  editData = null,
  onClose,
}) {
  const queryClient = useQueryClient();

  const {
    control,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
    defaultValues: {
      metal_name: "",
      unit: "gram",
      purity: "",
      status: true,
    },
  });

  useEffect(() => {
    if (editData) {
      console.log(editData.unit);
      reset({
        metal_name: editData.metal_name,
        unit: editData.unit,
        purity: editData.purity || "",
        status: editData.status === 1,
      });
    } else {
      reset({
        metal_name: "",
        unit: "gram",
        purity: "",
        status: true,
      });
    }
  }, [editData, reset]);

  const addMutation = useMutation({
    mutationFn: createMetal,
    onSuccess: () => {
      queryClient.invalidateQueries(["metals", "metal-rates"]);
      reset();
      onClose();
    },
  });

  const editMutation = useMutation({
    mutationFn: editMetal,
    onSuccess: () => {
      queryClient.invalidateQueries(["metals", "metal-rates"]);
      reset();
      onClose();
    },
  });

  const onSubmit = (data) => {
    const formData = new FormData();
    formData.append("metal_name", data.metal_name);
    formData.append("unit", data.unit);
    formData.append("purity", data.purity || "");
    formData.append("status", data.status ? "1" : "0");

    if (editData?.id) {
      formData.append("id", editData.id);
      editMutation.mutate(formData);
    } else {
      addMutation.mutate(formData);
    }
  };

  return (
    <div className="bg-white pt-0 w-full border border-gray-200 rounded-md">
      <div className="flex justify-between items-center border-b p-4 bg-brand-dark/5">
        <h2 className="text-xl font-semibold text-brand-dark">
          {type === "add" ? "Add" : "Edit"} Metal
        </h2>

        <Controller
          control={control}
          name="status"
          render={({ field }) => (
            <div className="flex items-center space-x-2">
              <label className="text-sm">Active</label>
              <Switch checked={field.value} onCheckedChange={field.onChange} />
            </div>
          )}
        />
      </div>
      <form onSubmit={handleSubmit(onSubmit)} className="p-6 space-y-6 ">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <Controller
            name="metal_name"
            control={control}
            render={({ field }) => (
              <CustomInput
                {...field}
                label="Metal Name"
                placeholder="e.g., Gold"
                errors={errors}
                required
              />
            )}
          />

          <Controller
            name="unit"
            control={control}
            render={({ field }) => (
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Unit <span className="text-red-500">*</span>
                </label>

                <Select
                  key={field.value}
                  value={field.value}
                  onValueChange={field.onChange}
                >
                  <SelectTrigger className="w-full">
                    <SelectValue placeholder="Select unit" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="gram">Gram</SelectItem>
                    <SelectItem value="carat">Carat</SelectItem>
                  </SelectContent>
                </Select>

                {errors.unit && (
                  <p className="text-red-500 text-sm mt-1">
                    {errors.unit.message}
                  </p>
                )}
              </div>
            )}
          />

          <Controller
            name="purity"
            control={control}
            render={({ field }) => (
              <CustomInput
                {...field}
                label="Purity/Carat (Optional)"
                placeholder="e.g., 22K"
                errors={errors}
              />
            )}
          />

        </div>
          <div className="flex justify-end">
            <Button variant="dark" type="submit">
              {editData ? "Update" : "Add"} Metal
            </Button>
          </div>
      </form>
    </div>
  );
}
