import React from "react";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import CustomSelect2 from "Components/CustomSelect2";

const schema = yup.object().shape({
  name: yup.string().required("Name is required"),
  code: yup.string().required("Code is required"),
  discountType: yup.string().required("Discount type is required"),
  discountAmount: yup
    .number()
    .required("Discount amount is required")
    .min(0, "Amount must be positive")
    .test(
      "discount-range",
      "Percentage must be between 1 and 100",
      function (value) {
        return (
          this.parent.discountType !== "percentage" ||
          (value <= 100 && value >= 1)
        );
      }
    ),
  durationInMonths: yup
    .number()
    .required("Duration is required")
    .min(1, "Duration must be at least 1 month"),
  maxRedemptions: yup
    .number()
    .required("Max redemptions is required")
    .min(1, "Must allow at least 1 redemption"),
  minimumAmount: yup
    .number()
    .required("Minimum amount is required")
    .min(0, "Amount must be positive"),
  expiresAt: yup.date().required("Expiration date is required"),
  applyToSubscriptions: yup.boolean(),
  applyToInvoices: yup.boolean(),
  restrictedToPlans: yup.array().of(yup.number()),
});

const CouponForm = ({
  onSubmit,
  initialData = null,
  plans = [],
  isSubmitting = false,
}) => {
  const {
    register,
    handleSubmit,
    formState: { errors },
    watch,
    setValue,
  } = useForm({
    resolver: yupResolver(schema),
    defaultValues: {
      name: initialData?.name || "",
      code: initialData?.code || "",
      discountType: initialData?.discountType || "percentage",
      discountAmount: initialData?.discountAmount || "",
      durationInMonths: initialData?.durationInMonths || 1,
      maxRedemptions: initialData?.maxRedemptions || 1,
      minimumAmount: initialData?.minimumAmount || 0,
      expiresAt: initialData?.expiresAt
        ? new Date(initialData.expiresAt).toISOString().split("T")[0]
        : "",
      applyToSubscriptions: initialData?.applyToSubscriptions ?? true,
      applyToInvoices: initialData?.applyToInvoices ?? false,
      restrictedToPlans: initialData?.restrictedToPlans || [],
    },
  });

  const discountType = watch("discountType");

  const handleFormSubmit = (data) => {
    console.log("Form submitted with data:", data);
    try {
      onSubmit(data);
    } catch (error) {
      console.error("Error in form submission:", error);
    }
  };

  const onError = (errors) => {
    console.log("Form validation errors:", errors);
  };

  return (
    <form
      onSubmit={handleSubmit(handleFormSubmit, onError)}
      className="space-y-6"
    >
      <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
        {/* Name */}
        <div>
          <label className="mb-2.5 block font-medium text-white">Name</label>
          <input
            type="text"
            {...register("name")}
            className="w-full rounded border-[1.5px] border-stroke bg-form-input px-5 py-3 text-white"
            placeholder="Summer Sale"
          />
          {errors.name && (
            <p className="mt-1 text-sm text-danger">{errors.name.message}</p>
          )}
        </div>

        {/* Code */}
        <div>
          <label className="mb-2.5 block font-medium text-white">Code</label>
          <input
            type="text"
            {...register("code")}
            className="w-full rounded border-[1.5px] border-stroke bg-form-input px-5 py-3 text-white"
            placeholder="SUMMER2024"
          />
          {errors.code && (
            <p className="mt-1 text-sm text-danger">{errors.code.message}</p>
          )}
        </div>

        {/* Discount Type */}
        <div>
          <label className="mb-2.5 block font-medium text-white">
            Discount Type
          </label>
          <CustomSelect2
            value={discountType}
            onChange={(value) => setValue("discountType", value)}
            options={[
              { value: "percentage", label: "Percentage" },
              { value: "fixed_amount", label: "Fixed Amount" },
            ]}
          />
          {errors.discountType && (
            <p className="mt-1 text-sm text-danger">
              {errors.discountType.message}
            </p>
          )}
        </div>

        {/* Discount Amount */}
        <div>
          <label className="mb-2.5 block font-medium text-white">
            Discount Amount
          </label>
          <div className="relative">
            <input
              type="number"
              {...register("discountAmount")}
              className="w-full rounded border-[1.5px] border-stroke bg-form-input px-5 py-3 text-white"
              placeholder={discountType === "percentage" ? "10" : "100"}
            />
            <span className="absolute right-4 top-1/2 text-white -translate-y-1/2">
              {discountType === "percentage" ? "%" : "$"}
            </span>
          </div>
          {errors.discountAmount && (
            <p className="mt-1 text-sm text-danger">
              {errors.discountAmount.message}
            </p>
          )}
        </div>

        {/* Duration */}
        <div>
          <label className="mb-2.5 block font-medium text-white">
            Duration (Months)
          </label>
          <input
            type="number"
            {...register("durationInMonths")}
            className="w-full rounded border-[1.5px] border-stroke bg-form-input px-5 py-3 text-white"
            min="1"
          />
          {errors.durationInMonths && (
            <p className="mt-1 text-sm text-danger">
              {errors.durationInMonths.message}
            </p>
          )}
        </div>

        {/* Max Redemptions */}
        <div>
          <label className="mb-2.5 block font-medium text-white">
            Max Redemptions
          </label>
          <input
            type="number"
            {...register("maxRedemptions")}
            className="w-full rounded border-[1.5px] border-stroke bg-form-input px-5 py-3 text-white"
            min="1"
          />
          {errors.maxRedemptions && (
            <p className="mt-1 text-sm text-danger">
              {errors.maxRedemptions.message}
            </p>
          )}
        </div>

        {/* Minimum Amount */}
        <div>
          <label className="mb-2.5 block font-medium text-white">
            Minimum Amount ($)
          </label>
          <input
            type="number"
            {...register("minimumAmount")}
            className="w-full rounded border-[1.5px] border-stroke bg-form-input px-5 py-3 text-white"
            min="0"
          />
          {errors.minimumAmount && (
            <p className="mt-1 text-sm text-danger">
              {errors.minimumAmount.message}
            </p>
          )}
        </div>

        {/* Expiration Date */}
        <div>
          <label className="mb-2.5 block font-medium text-white">
            Expiration Date
          </label>
          <input
            type="date"
            {...register("expiresAt")}
            className="w-full rounded border-[1.5px] border-stroke bg-form-input px-5 py-3 text-white"
          />
          {errors.expiresAt && (
            <p className="mt-1 text-sm text-danger">
              {errors.expiresAt.message}
            </p>
          )}
        </div>
      </div>

      {/* Checkboxes */}
      <div className="space-y-4">
        <div className="flex gap-2 items-center">
          <input
            type="checkbox"
            {...register("applyToSubscriptions")}
            className="form-checkbox"
          />
          <label className="text-white">Apply to Subscriptions</label>
        </div>

        <div className="flex gap-2 items-center">
          <input
            type="checkbox"
            {...register("applyToInvoices")}
            className="form-checkbox"
          />
          <label className="text-white">Apply to Invoices</label>
        </div>
      </div>

      {/* Restricted Plans */}
      {plans.length > 0 && (
        <div>
          <label className="mb-2.5 block font-medium text-white">
            Restricted to Plans
          </label>
          <div className="grid grid-cols-2 gap-4 mt-2">
            {plans.map((plan) => (
              <div key={plan.id} className="flex gap-2 items-center">
                <input
                  type="checkbox"
                  id={`plan-${plan.id}`}
                  value={plan.id}
                  {...register("restrictedToPlans")}
                  className="form-checkbox"
                />
                <label htmlFor={`plan-${plan.id}`} className="text-white">
                  {plan.name}
                </label>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Submit Button */}
      <div className="flex justify-end">
        <button
          type="submit"
          disabled={isSubmitting}
          onClick={(e) => {
            e.preventDefault();
            handleSubmit(handleFormSubmit, onError)(e);
          }}
          className="inline-flex items-center justify-center rounded bg-primary px-6 py-2.5 text-center font-medium text-white hover:bg-opacity-90 disabled:bg-opacity-50"
        >
          {isSubmitting ? "Saving..." : initialData ? "Update" : "Create"}{" "}
          Coupon
        </button>
      </div>
    </form>
  );
};

export default CouponForm;
