"use client";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { createProduct } from "@/services/create-product";
import { toastError, toastSuccess } from "@/services/custom-toast";
import { updateProduct } from "@/services/update-product";
import { zodResolver } from "@hookform/resolvers/zod";
import {
  ChartNoAxesCombined,
  ChevronDown,
  Link,
  Loader2,
  ScrollText,
} from "lucide-react";
import { useLocale, useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { useRef, useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import FallbackImage from "../../shared/FallbackImage";
import SubmitButton from "../../shared/SubmitButton";
import DeleteProductDialog from "../DeleteProductDialog";
import DuplicateProductDialog from "../DuplicateProductDialog";
import PhotoVideoDialog from "./PhotoVideoDialog";
import { useQueryClient } from "@tanstack/react-query";

const VendorCard = ({ product, isSubmit, categories, setDialogOpen }) => {
  const queryClient = useQueryClient();
  const showMore = [
    {
      name: "get-link",
      icon: Link,
      className: "",
      onClick: () => {
        navigator.clipboard
          .writeText(`${location.host}/products/${product?.id}`)
          .then(() => {
            toastSuccess(t("link-copied"));
          });
      },
    },
    {
      name: "duplicated",
      icon: ScrollText,
      className: "",
      onClick: () => setDuplicateDialogOpen(true),
    },
    {
      name: "delete",
      icon: ChartNoAxesCombined,
      className: "text-red-500",
      onClick: () => setDeleteDialogOpen(true),
    },
  ];
  const router = useRouter();
  const e = useTranslations("form-errors");

  const title =
    product?.product_details.length > 0
      ? product?.product_details[0]?.title
      : "";

  const categoryId = product?.categories[0]?.pivot?.category_id;

  const productImage =
    product?.product_photos?.length > 0
      ? product?.product_photos?.[0]?.photo
      : null;

  const f = useTranslations("form-labels");
  const t = useTranslations("vendor");
  const locale = useLocale();
  const [imageLoading, setImageLoading] = useState(false);
  const [imageSrc, setImageSrc] = useState(null);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [duplicateDialogOpen, setDuplicateDialogOpen] = useState(false);
  const fileInputRef = useRef(null);
  const form = useForm({
    resolver: zodResolver(
      z
        .object({
          product_name: z
            .string({ message: e("required") })
            .min(2, { message: e("min2") })
            .trim(),
          price: z
            .string({ errorMap: () => ({ message: e("required") }) })
            .min(1)
            .refine((value) => !isNaN(value) && parseFloat(value) > 0, {
              message: t("positive_number"),
            }),
          cost: z
            .string({ errorMap: () => ({ message: e("required") }) })
            .min(1)
            .refine((value) => !isNaN(value) && parseFloat(value) > 0, {
              message: t("positive_number"),
            }),
          category_id: z
            .string({ errorMap: () => ({ message: e("required") }) })
            .min(1),
          max_count: z
            .string({ errorMap: () => ({ message: e("required") }) })
            .min(1)
            .refine((value) => !isNaN(value) && parseFloat(value) > -1, {
              message: t("positive_number"),
            }),
          is_free_shipping: z
            .string({ errorMap: () => ({ message: e("required") }) })
            .min(1),
        })
        .refine((data) => data.cost <= data.price, {
          message: t("cost-bigger-than-price-error"),
          path: ["price"],
        })
    ),
    defaultValues: {
      product_name: title,
      category_id: categoryId,
      cost: product?.cost,
      price: Number(product?.price).toFixed(2),
      max_count: product?.max_count,
      is_free_shipping: product?.is_free_shipping,
    },
  });

  async function onSubmit(values) {
    const formData = new FormData();
    for (const [key, value] of Object.entries(values)) {
      formData.append(key, value);
    }
    formData.delete("category_id");
    formData.append("categories[]", values.category_id);
    if (product) {
      // If here product update it
      formData.append("id", product.id);
      const { message, error } = await updateProduct(formData);
      if (error) {
        toastError(message);
        return;
      }
      toastSuccess(message);
      return;
    }
    const { message, error } = await createProduct(formData);
    if (error) {
      toastError(message);
      return;
    }
    setDialogOpen(false);
    toastSuccess(message);
    queryClient.refetchQueries({ queryKey: ["/user/products"] });
  }

  const handleImageChange = async (e) => {
    setImageLoading(true);
    const file = e.target.files[0];
    if (!file) return;

    const formData = new FormData();
    formData.append("id", product.id);
    formData.append("image", file);
    const { data, message, error } = await postData({
      endPoint: "/user/products/images",
      token,
      body: formData,
    });
    setImageLoading(false);
    if (error) {
      toastError(message);
      return;
    }
    // Update the image source with the new image URL
    setImageSrc(data?.image); // Assuming image is returned in the API response
    toastSuccess(message);
  };

  return (
    <section className="max-w-md mx-auto p-2 md:p-6 bg-white shadow-md rounded-md h-full">
      {/* Product Image and Change Button */}
      {!isSubmit && (
        <div className="mb-4">
          <FallbackImage
            src={productImage ?? imageSrc ?? ""}
            width={500}
            height={300}
            alt={`${title} photo's`}
            className="w-full h-48 object-cover rounded-t-md"
          />
          {imageLoading ? (
            <Loader2 size={25} className="mx-auto text-main animate-spin" />
          ) : (
            // add main image and video
            <PhotoVideoDialog productId={product?.id} product={product} />
          )}
          <input
            type="file"
            ref={fileInputRef} // Reference to hidden file input
            onChange={handleImageChange} // Handle file selection
            className="hidden" // Hide the input
            accept="image/*" // Accept only image files
          />
        </div>
      )}

      {/* Title Input */}
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)}>
          <FormField
            name="product_name"
            control={form.control}
            render={({ field }) => (
              <FormItem className="min-h-[60px] ">
                {" "}
                {/* Set a minimum height */}
                <FormControl>
                  <Input
                    type="text"
                    {...field}
                    placeholder={f("product-name")}
                  />
                </FormControl>
                <FormMessage /> {/* Reserve space for error message */}
              </FormItem>
            )}
          />
          <FormField
            name="category_id"
            control={form.control}
            render={({ field }) => (
              <FormItem className="min-h-[60px] ">
                <FormControl>
                  <Select
                    dir={locale == "ar" ? "rtl" : "ltr"}
                    value={field.value}
                    onValueChange={field.onChange}
                  >
                    <SelectTrigger className="w-full border-gray-300 rounded-md shadow-sm">
                      <SelectValue placeholder={f("section")} />
                    </SelectTrigger>
                    <SelectContent className="z-[1000]">
                      {categories
                        ?.filter(
                          (category) => category?.parent_cat?.translation?.title
                        )
                        .map((category) => {
                          const id = category?.parent_cat?.id;
                          const details = category?.parent_cat?.translation;
                          return (
                            <SelectItem key={id} value={String(id)}>
                              {details.title}
                            </SelectItem>
                          );
                        })}
                    </SelectContent>
                  </Select>
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          {/* Cost and Price Inputs */}
          <div className="grid grid-cols-2 gap-4 mbs-4">
            <FormField
              name="price"
              control={form.control}
              render={({ field }) => (
                <FormItem className="min-h-[60px]">
                  <FormControl>
                    <Input type="number" {...field} placeholder={f("price")} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              name="cost"
              control={form.control}
              render={({ field }) => (
                <FormItem className="min-h-[60px] ">
                  <FormControl>
                    <Input type="number" {...field} placeholder={f("cost")} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </div>
          {/* Quantity Input */}
          <FormField
            name="max_count"
            control={form.control}
            render={({ field }) => (
              <FormItem className="min-h-[60px] ">
                <FormControl>
                  <Input type="number" placeholder={f("stock")} {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          {/* Radio Buttons */}
          <FormField
            control={form.control}
            name="is_free_shipping"
            render={({ field }) => (
              <FormItem className="min-h-[60px] space-y-3 ">
                <FormControl>
                  <RadioGroup
                    onValueChange={field.onChange}
                    value={field.value}
                    className="flex justify-around "
                  >
                    <FormItem className="flex items-center space-x-3 space-y-0">
                      <FormLabel className="font-normal">
                        {f("pay-charging")}
                      </FormLabel>
                      <FormControl>
                        <RadioGroupItem value="0" />
                      </FormControl>
                    </FormItem>
                    <FormItem className="flex items-center space-x-3 space-y-0">
                      <FormLabel className="font-normal">
                        {f("free-charging")}
                      </FormLabel>
                      <FormControl>
                        <RadioGroupItem value="1" />
                      </FormControl>
                    </FormItem>
                  </RadioGroup>
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          {/* Save Button */}
          {isSubmit ? (
            <SubmitButton
              loading={form.formState.isSubmitting}
              text={f("save")}
              className="bg-main hover:bg-main/90"
            />
          ) : (
            <div className="grid md:grid-cols-2 gap-4">
              <SubmitButton
                loading={form.formState.isSubmitting}
                isIcon={false}
                text={f("save")}
              />
              <Button
                type="button" // Important: this prevents form submission
                variant="outline"
                onClick={() => {
                  if (product?.max_count == 0) {
                    return toastError(t("product-has-no-quantity"));
                  }
                  router.push(`/vendor/product-vendor-details/${product?.id}`);
                }}
              >
                {t("product-details")}
              </Button>
              <DropdownMenu>
                <DropdownMenuTrigger asChild className="md:col-span-2">
                  <Button variant="outline">
                    <ChevronDown />
                    {t("more")}
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent>
                  {showMore.map((item, i) => (
                    <DropdownMenuItem
                      onClick={item.onClick}
                      className={`flex gap-2 cursor-pointer ${item.className}`}
                      key={i}
                    >
                      <item.icon size={15} />
                      <span>{t(item.name)}</span>
                    </DropdownMenuItem>
                  ))}
                </DropdownMenuContent>
              </DropdownMenu>
            </div>
          )}
        </form>
      </Form>
      <DeleteProductDialog
        id={product?.id}
        dialogOpen={deleteDialogOpen}
        setDialogOpen={setDeleteDialogOpen}
      />
      <DuplicateProductDialog
        id={product?.id}
        dialogOpen={duplicateDialogOpen}
        setDialogOpen={setDuplicateDialogOpen}
      />
    </section>
  );
};

export default VendorCard;
