"use client";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Textarea } from "@/components/ui/textarea";
import { useState } from "react";

import { Calendar } from "@/components/ui/calendar";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { CalendarIcon, Loader2 } from "lucide-react";
import { useLocale, useTranslations } from "next-intl";
import { FaMinus, FaPlus } from "react-icons/fa";
import { TbShoppingBagPlus } from "react-icons/tb";
export default function ProductFormComponentRedesignThree({
  customFormInputs,
  product,
  loading,
  quantity,
  addProductToCart,
  handleIncrement,
  handleDecrement,
}) {
  const t = useTranslations("single-product");
  const l = useLocale();
  const dir = l === "en" ? "ltr" : "rtl";
  // Form state management
  const [formData, setFormData] = useState({});
  const [errors, setErrors] = useState({});

  // Handle input changes
  const handleChange = (fieldName, value) => {
    setFormData((prev) => ({
      ...prev,
      [fieldName]: value,
    }));

    // Clear error for this field
    if (errors[fieldName]) {
      setErrors((prev) => {
        const newErrors = { ...prev };
        delete newErrors[fieldName];
        return newErrors;
      });
    }
  };

  // Validate form before submission
  const validateForm = () => {
    const newErrors = {};
    if (!customFormInputs) return true;

    customFormInputs.forEach((field) => {
      const fieldName = field.id.toString(); // Use field.id directly
      const value = formData[fieldName];

      if (field.required === "1") {
        switch (field.type) {
          case "smalltext":
          case "largetext":
            if (!value || value.trim() === "") {
              newErrors[fieldName] = `${field.name} ${t("is_required")}`;
            }
            break;

          case "number":
            if (value === undefined || value === null || value === "") {
              newErrors[fieldName] = `${field.name} ${t("is_required")}`;
            }
            break;

          case "checkbox":
            if (!value || (Array.isArray(value) && value.length === 0)) {
              newErrors[fieldName] = `${field.name} must be checked`;
            }
            break;

          case "radio":
            if (!value || (Array.isArray(value) && value.length === 0)) {
              newErrors[fieldName] = `${field.name} ${t("is_required")}`;
            }
            break;

          case "date":
            if (!value) {
              newErrors[fieldName] = `${field.name} ${t("is_required")}`;
            }
            break;

          case "time":
            if (!value) {
              newErrors[fieldName] = `${field.name} ${t("is_required")}`;
            }
            break;

          case "datetime":
            if (!value) {
              newErrors[fieldName] = `${field.name} ${t("is_required")}`;
            }
            break;

          case "image":
            if (!value) {
              newErrors[fieldName] = `${field.name} ${t("is_required")}`;
            }
            break;
        }
      }
    });

    setErrors(newErrors);

    const isValid = Object.keys(newErrors).length === 0;

    return isValid;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    const isValid = validateForm();
    if (!isValid) {
      return;
    }
    addProductToCart();
  };
  // Render input based on field type
  const renderField = (field) => {
    const fieldName = field.id;

    switch (field.type) {
      case "smalltext":
        return (
          <div>
            <Label>
              {field.name}{" "}
              {field.required === "1" && (
                <span className="text-red-500">*</span>
              )}
            </Label>
            <Input
              value={formData[fieldName] || ""}
              onChange={(e) => handleChange(fieldName, e.target.value)}
              placeholder={field.desc}
              className="mt-2"
            />
            {errors[fieldName] && (
              <p className="text-red-500 text-sm mt-1">{errors[fieldName]}</p>
            )}
          </div>
        );

      case "largetext":
        return (
          <div>
            <Label>
              {field.name}{" "}
              {field.required === "1" && (
                <span className="text-red-500">*</span>
              )}
            </Label>
            <Textarea
              value={formData[fieldName] || ""}
              onChange={(e) => handleChange(fieldName, e.target.value)}
              placeholder={field.desc}
              className="mt-2"
            />
            {errors[fieldName] && (
              <p className="text-red-500 text-sm mt-1">{errors[fieldName]}</p>
            )}
          </div>
        );

      case "checkbox":
        return (
          <div>
            <Label>
              {field.name}{" "}
              {field.required === "1" && (
                <span className="text-red-500">*</span>
              )}
            </Label>
            <div className="mt-2 flex gap-2">
              {field.options.map((option) => (
                <div
                  key={option.id}
                  className="flex items-center gap-2   space-x-2"
                >
                  <Checkbox
                    checked={
                      formData[fieldName]?.includes(option.name) || false
                    }
                    onCheckedChange={(checked) => {
                      const updatedValues = checked
                        ? [...(formData[fieldName] || []), option.name]
                        : formData[fieldName]?.filter(
                          (value) => value !== option.name
                        );
                      handleChange(fieldName, updatedValues);
                    }}
                    id={`${fieldName}-${option.id}`}
                  />
                  <Label htmlFor={`${fieldName}-${option.id}`} className="mx-2">
                    {option.name}
                  </Label>
                </div>
              ))}
            </div>
            {errors[fieldName] && (
              <p className="text-red-500 text-sm mt-1">{errors[fieldName]}</p>
            )}
          </div>
        );

      case "radio":
        return (
          <div>
            <Label>
              {field.name}{" "}
              {field.required === "1" && (
                <span className="text-red-500">*</span>
              )}
            </Label>
            <RadioGroup
              dir={dir}
              onValueChange={(value) => {
                // Always store the value as an array
                handleChange(fieldName, [value]);
              }}
              value={formData[fieldName] ? formData[fieldName][0] : ""}
              className="mt-2"
            >
              {field.options.map((option) => (
                <div
                  key={option.id}
                  className="flex items-center gap-2 space-x-2"
                >
                  <RadioGroupItem
                    dir={dir}
                    value={option.name}
                    id={`${fieldName}-${option.id}`}
                  />
                  <Label htmlFor={`${fieldName}-${option.id}`}>
                    {option.name}
                  </Label>
                </div>
              ))}
            </RadioGroup>
            {errors[fieldName] && (
              <p className="text-red-500 text-sm mt-1">{errors[fieldName]}</p>
            )}
          </div>
        );

      case "number":
        return (
          <div>
            <Label>
              {field.name}{" "}
              {field.required === "1" && (
                <span className="text-red-500">*</span>
              )}
            </Label>
            <Input
              type="number"
              value={formData[fieldName] || ""}
              onChange={(e) => handleChange(fieldName, e.target.value)}
              placeholder={field.desc}
              className="mt-2"
            />
            {errors[fieldName] && (
              <p className="text-red-500 text-sm mt-1">{errors[fieldName]}</p>
            )}
          </div>
        );

      case "date":
        return (
          <div>
            <Label>
              {field.name}{" "}
              {field.required === "1" && (
                <span className="text-red-500">*</span>
              )}
            </Label>
            <Popover>
              <PopoverTrigger asChild>
                <Button
                  variant="outline"
                  className="w-full justify-start text-left font-normal mt-2"
                >
                  <CalendarIcon className="mr-2 h-4 w-4" />
                  {formData[fieldName] ? (
                    new Date(formData[fieldName]).toLocaleDateString()
                  ) : (
                    <span>Pick a date</span>
                  )}
                </Button>
              </PopoverTrigger>
              <PopoverContent className="w-auto p-0">
                <Calendar
                  mode="single"
                  selected={
                    formData[fieldName]
                      ? new Date(formData[fieldName])
                      : undefined
                  }
                  onSelect={(date) => handleChange(fieldName, date)}
                  initialFocus
                />
              </PopoverContent>
            </Popover>
            {errors[fieldName] && (
              <p className="text-red-500 text-sm mt-1">{errors[fieldName]}</p>
            )}
          </div>
        );

      case "time":
        return (
          <div>
            <Label>
              {field.name}{" "}
              {field.required === "1" && (
                <span className="text-red-500">*</span>
              )}
            </Label>
            <Input
              type="time"
              value={formData[fieldName] || ""}
              onChange={(e) => handleChange(fieldName, e.target.value)}
              className="mt-2"
            />
            {errors[fieldName] && (
              <p className="text-red-500 text-sm mt-1">{errors[fieldName]}</p>
            )}
          </div>
        );

      case "datetime":
        return (
          <div>
            <Label>
              {field.name}{" "}
              {field.required === "1" && (
                <span className="text-red-500">*</span>
              )}
            </Label>
            <div className="flex space-x-2 mt-2">
              <Input
                type="date"
                value={
                  formData[fieldName]
                    ? new Date(formData[fieldName]).toISOString().split("T")[0]
                    : ""
                }
                onChange={(e) => {
                  const currentTime = formData[fieldName]
                    ? new Date(formData[fieldName]).toTimeString().slice(0, 5)
                    : "00:00";
                  handleChange(
                    fieldName,
                    new Date(`${e.target.value}T${currentTime}`)
                  );
                }}
                className="flex-1"
              />
              <Input
                type="time"
                value={
                  formData[fieldName]
                    ? new Date(formData[fieldName]).toTimeString().slice(0, 5)
                    : ""
                }
                onChange={(e) => {
                  const currentDate = formData[fieldName]
                    ? new Date(formData[fieldName]).toISOString().split("T")[0]
                    : new Date().toISOString().split("T")[0];
                  handleChange(
                    fieldName,
                    new Date(`${currentDate}T${e.target.value}`)
                  );
                }}
                className="flex-1"
              />
            </div>
            {errors[fieldName] && (
              <p className="text-red-500 text-sm mt-1">{errors[fieldName]}</p>
            )}
          </div>
        );

      case "image":
        return (
          <div>
            <Label>
              {field.name}{" "}
              {field.required === "1" && (
                <span className="text-red-500">*</span>
              )}
            </Label>
            <Input
              type="file"
              accept="image/*"
              onChange={(e) => {
                const file = e.target.files?.[0];
                handleChange(fieldName, file);
              }}
              className="mt-2"
            />
            {errors[fieldName] && (
              <p className="text-red-500 text-sm mt-1">{errors[fieldName]}</p>
            )}
          </div>
        );

      default:
        return null;
    }
  };

  return (
    <form
      onSubmit={handleSubmit}
      className=" container mx-auto max-w-5xl  rounded-md  "
    >
      {customFormInputs &&
        Array.isArray(customFormInputs) &&
        customFormInputs.length > 0 &&
        customFormInputs?.map((field) => (
          <div key={field.id}>{renderField(field)}</div>
        ))}

      <div className="flex mt-4 items-center gap-6">
        {/* Add to Cart Button */}
        {Number(product.stock) ? (
          <>
            <Button
              disabled={loading || quantity > Number(product.stock)}
              className="flex items-center gap-2  bg-main hover:bg-secondary hover:text-main rounded-full duration-150 mt-0 w-4/6 "
              onClick={handleSubmit}
            >
              {loading ? (
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              ) : (
                <TbShoppingBagPlus size={20} />
              )}
              {t("add-to-cart")}
            </Button>
            {/* Quantity Controls */}
            <div className="h-12 px-6 flex items-center justify-center gap-6 bg-white rounded-full">
              <button
                onClick={handleIncrement}
                type="button"
                disabled={quantity >= Number(product.stock)}
              >
                <FaPlus size={12} />
              </button>
              <p className="text-xl text-center font-semibold w-8">
                {quantity?.toString()?.padStart(2, "0")}
              </p>
              <button
                type="button"
                onClick={handleDecrement}
                disabled={quantity <= 1}
              >
                <FaMinus size={12} />
              </button>
            </div>
          </>
        ) : (
          <p className="text-red-500 font-extrabold">{t("no-stock")}</p>
        )}
      </div>
    </form>
  );
}
