"use client";

import { Button } from "@/components/ui/button";
import { CardContent } from "@/components/ui/card";
import React, { useEffect, useRef, useState } from "react";
import { Input } from "@/components/ui/input";
import { Progress } from "@/components/ui/progress";
import { useGlobalContext } from "@/context/Provider";
import { Upload, Plus } from "lucide-react";
import apis from "@/utils/apis";

const AddCategory = ({ setImage, setName, cat_name, image }: { cat_name: any, setImage: any, setName: any, image: string }) => {
  const { Toast } = useGlobalContext();
  const [loading, setLoading] = useState(false);
  const [progress, setProgress] = useState(0);
  const [blobFile, setBlobFile] = useState<File | null>(null);
  const [fileName, setFileName] = useState("");
  const fileInputRef = useRef<HTMLInputElement>(null);

  // Handle File Selection Click
  const handleFileSelect = () => {
    if (fileInputRef?.current) {
      fileInputRef.current.click();
    }
  };

  const handleUploadImage = async (file: File) => {
    try {
      setLoading(true);
      setProgress(0);

      const apiRes = await apis.Common.uploadFile("file", file)
      setImage(apiRes?.key)
      Toast.success("Image uploaded successfully!")
    } catch (error) {
      Toast.error("Failed to upload image.");
    } finally {
      setLoading(false);
    }
  };

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    event.preventDefault();
    const file = event.target.files?.[0];

    if (file) {
      const maxFileSize = 5 * 1024 * 1024; // 5MB Limit
      const allowedTypes = ["image/jpeg", "image/png", "image/jpg"];

      if (!allowedTypes.includes(file.type)) {
        Toast.error("Only JPG and PNG images are allowed.");
        return;
      }

      if (file.size > maxFileSize) {
        Toast.error("Image size cannot be more than 5MB.");
        return;
      }

      setBlobFile(file);
      handleUploadImage(file);
    }
  };

  // Clear Uploaded Image
  const handleClear = () => {
    setBlobFile(null);
    setProgress(0);
    setFileName("");
    setImage("");
  };

  useEffect(() => {
    if (image === "") {
      setBlobFile(null)
    }
  }, [image]);


  return (
    <div className="bg-white w-full p-4">
      <div className="grid grid-cols-12 gap-4 w-full">
        <div className="col-span-12 w-full">
          <Input
            type="text"
            placeholder="Enter name"
            value={cat_name}
            maxLength={30}
            onChange={(e) => setName(e.target.value)}
            className="mb-4 h-[40px] w-full border border-[var(--primary-brand)] p-2 rounded-lg"
          />
          {(blobFile || image) ? (
            <div className="w-full">
              <CardContent className="p-0">
                <div className="flex items-center border justify-between border-b rounded-xl border-primary p-4">
                  <div className="flex w-full flex-col gap-2">
                    <div className="flex justify-between items-center space-x-4">
                      <div className="flex items-center gap-2">
                        <img
                          src={blobFile ? URL.createObjectURL(blobFile) : apis.BUCKET_ROOT + image}
                          alt="Preview"
                          className="w-16 h-16 rounded-lg object-cover"
                        />
                        <div>
                          <div className="font-semibold text-xs theme-color">{fileName}</div>
                        </div>
                      </div>
                      {!loading && (
                        <button
                          type="button"
                          className="text-gray cursor-pointer hover:text-red-500 focus:outline-none"
                          onClick={handleClear}
                        >
                          ✖
                        </button>
                      )}
                    </div>
                    {loading && (
                      <div className="flex items-center gap-2">
                        <Progress value={progress} />
                        <span className="text-gray text-xs font-normal">{progress}%</span>
                      </div>
                    )}
                  </div>
                </div>
              </CardContent>
            </div>
          ) : (
            <div className="flex flex-col items-center justify-center border-2 border-dashed border-[#ddd] rounded-lg py-6 cursor-pointer">
              <div className="flex flex-row p-2 justify-center items-center rounded-full bg-[var(--orange-100)]" onClick={handleFileSelect}>
                <Plus color="var(--primary-brand)" />
                <span className="text-[var(--primary-brand)] text-[14px] font-[500]">Add Image</span>
              </div>
              {/* <Upload className="h-8 w-8 text-gray-500 mb-2" />
            <Button
              size="lg"
              className="font-medium text-black bg-[var(--primary-brand)] hover:bg-yellow-600 px-4 py-2 text-sm"
              onClick={handleFileSelect}
            >
              Upload Image
            </Button> */}
              <Input
                type="file"
                accept=".jpg,.jpeg,.png"
                hidden
                ref={fileInputRef}
                onChange={handleFileChange}
                className="hidden"
              />
              <span className="text-[#999999] text-[12px] font-[400]">Couldn&apos;t find a suitable category?
                Add your own.</span>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default AddCategory;