import postData from "@/api/post-data";
import SubmitButton from "@/app/ui/shared/SubmitButton";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { useFetchData } from "@/hooks";
import { changeProductVendorImage } from "@/services/change-product-vendor-image";
import { toastError, toastSuccess } from "@/services/custom-toast";
import { zodResolver } from "@hookform/resolvers/zod";
import { Upload, X } from "lucide-react";
import { useLocale, useTranslations } from "next-intl";
import { useRef, useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import FallbackImage from "../../shared/FallbackImage";
import Image from "next/image";

const MAX_FILE_SIZE = 1024 * 1024 * 10; // 10MB
const ACCEPTED_IMAGE_MIME_TYPES = [
  "image/jpeg",
  "image/jpg",
  "image/png",
  "image/webp",
];

export default function PhotoVideoDialog({ productId, product }) {
  const [selectedFile, setSelectedFile] = useState(null);
  const [previewUrl, setPreviewUrl] = useState(null);
  const [error, setError] = useState("");
  const [isModelOpen, setIsModelOpen] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const fileInputRef = useRef(null);
  const locale = useLocale();
  const t = useTranslations("vendor");
  const dir = locale === "en" ? "ltr" : "rtl";

  const form = useForm({
    defaultValues: {
      videoUrl: product?.video?.video || "",
    },
    resolver: zodResolver(
      z.object({
        videoUrl: z
          .string()
          .min(6, t("upload-valid-url")) // Ensure the URL is at least 6 characters long (you may adjust this)
          .url(t("upload-valid-url")), // This will ensure the string is a valid URL
      })
    ),
  });

  const {
    setError: setFormError,
    formState: { isSubmitting },
  } = form; // Form helpers

  async function onSubmit(data) {
    const formData = new FormData();
    formData.append("id", productId);
    formData.append("video", data.videoUrl);
    const {
      error,
      message,
      data: resData,
    } = await postData({
      endPoint: "/user/products/videos",
      body: formData,
      locale,
    });
    if (error) {
      return toastError(message);
    }
    toastSuccess("successfully-added-new-video");
    setIsModelOpen(false);
  }

  const triggerFileInput = () => {
    fileInputRef.current?.click();
  };

  const handleFileChange = (event) => {
    const file = event.target.files[0];

    // Validate file size
    if (file && file.size > MAX_FILE_SIZE) {
      setError(t("image-max-size"));
      setSelectedFile(null);
      setPreviewUrl(null);
      return;
    }

    // Validate file type
    if (file && !ACCEPTED_IMAGE_MIME_TYPES.includes(file.type)) {
      setError(t("invalid-image-type"));
      setSelectedFile(null);
      setPreviewUrl(null);
      return;
    }

    // Create preview URL
    const reader = new FileReader();
    reader.onloadend = () => {
      setPreviewUrl(reader.result);
    };
    reader?.readAsDataURL(file);

    setSelectedFile(file);
    setError("");
  };

  const clearFile = () => {
    setSelectedFile(null);
    setPreviewUrl(null);
    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
  };

  const handleSubmit = async (event) => {
    event.preventDefault();

    if (!selectedFile) {
      setError(t("add-main-image"));
      return;
    }
    setIsLoading(true);

    const formData = new FormData();
    formData.append("image", selectedFile);
    formData.append("id", productId);

    const { data, code, error } = await changeProductVendorImage(formData);

    if (error) {
      setError(t("failed-upload-image"));
    }
    if (!error) {
      setIsModelOpen(false);
    }

    setIsLoading(false);
    toastSuccess("addedsuccessfully");

    // Reset form after successful upload
    clearFile();
  };
  const mainImageSrc = product?.product_photos
    ?.filter((item) => item.main == "1")
    ?.at(0)?.photo;

  return (
    <Dialog onOpenChange={setIsModelOpen} open={isModelOpen} dir={dir}>
      <DialogTrigger asChild dir={dir}>
        <Button
          className="bg-main rounded-none hover:bg-main/90 w-full"
          size="sm"
        >
          {t("change-photo")}
        </Button>
      </DialogTrigger>
      <DialogContent className="sm:max-w-[425px]" dir={dir}>
        <DialogHeader dir={dir}>
          <DialogTitle dir={dir}>{t("add-main-photo-image")}</DialogTitle>
        </DialogHeader>
        {/* show the video */}
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
            <h2>{t("video-url")}</h2>
            <FormField
              name="videoUrl"
              control={form.control}
              render={({ field }) => (
                <FormItem>
                  <FormControl>
                    <Input
                      className="focus-visible:ring-dark border-dark"
                      {...field}
                      placeholder={t("video-url")}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <SubmitButton text={t("confirm")} loading={isSubmitting} />
          </form>
        </Form>
        {/* show the image */}
        <div className="flex w-full flex-col gap-2">
          <h2>{t("add-main-image")}</h2>
          <form onSubmit={handleSubmit}>
            <div>
              <div
                onClick={triggerFileInput}
                className="w-full border-2 border-dashed border-gray-300 
                     hover:border-blue-500 transition-colors duration-300 
                     rounded-lg p-6 flex flex-col items-center justify-center 
                     cursor-pointer group relative"
              >
                <input
                  ref={fileInputRef}
                  type="file"
                  accept="image/jpeg,image/png,image/webp"
                  onChange={handleFileChange}
                  className="hidden"
                />

                {previewUrl ? (
                  <div className="relative w-full h-64">
                    <FallbackImage
                      fill
                      src={previewUrl}
                      alt="Preview"
                      className="w-full h-full object-contain rounded-lg"
                    />
                    <button
                      type="button"
                      onClick={(e) => {
                        e.stopPropagation();
                        clearFile();
                      }}
                      className="absolute top-2 right-2 bg-red-500 text-white 
                               rounded-full p-1 hover:bg-red-600 transition-colors"
                    >
                      <X className="w-5 h-5" />
                    </button>
                  </div>
                ) : mainImageSrc ? (
                  <div className="relative w-full h-40">
                    <Image
                      unoptimized
                      className=" object-contain"
                      fill
                      src={mainImageSrc}
                      alt={mainImageSrc}
                    />
                  </div>
                ) : (
                  <>
                    <Upload
                      className="w-12 h-12 text-gray-400 group-hover:text-blue-500 
                           transition-colors duration-300 mb-4"
                    />
                    <p
                      className="text-gray-600 group-hover:text-blue-500 
                            transition-colors duration-300 text-center"
                    >
                      {t("upload-image-prompt")}
                    </p>
                  </>
                )}
              </div>

              {error && <p className="text-red-500 mt-2">{error}</p>}

              <SubmitButton
                text={t("confirm")}
                loading={isLoading}
                disabled={!selectedFile}
              />
            </div>
          </form>
        </div>
      </DialogContent>
    </Dialog>
  );
}
