"use client"
import { Button } from "@/components/ui/button";
import { CardContent, CardDescription } from "@/components/ui/card";
import NotesCard from "../common/card/notes-card";
import React, { useEffect, useRef, useState } from "react";
import { Icons } from "../icons";
import { Progress } from "../ui/progress";
import apis from "@/utils/apis";
import { useGlobalContext } from "@/context/Provider";
import { useSearchParams } from "next/navigation";
import EnhancedCard from "../common/card/enhanced-card";
import { Input } from "../ui/input";
import { formatFileSize } from "@/utils/commonFunctions";
import Loader from "../common/loader";
import gif from "@/assets/gif/check.gif"





const UploadFile = () => {

  const searchParams = useSearchParams();
  const queryParams = Object.fromEntries(searchParams.entries());
  const { Toast } = useGlobalContext()
  const [loading, setLoading] = useState(false)
  const [loading2, setLoading2] = useState(false)
  const [loading3, setLoading3] = useState(false)
  const [details, setDetails] = useState<any>({})
  const [enhancedData, setEnhancedData] = useState<any>(null)
  const [blobFile, setBlobFile] = useState<File | null>(null);
  const fileInputRef: any = useRef(null);
  const [progress, setProgress] = useState(0);
  const [automationData, setAutomationData] = useState<any>()
  const [fileName, setfileName] = useState("")
  const [isCopied, setIsCopied] = useState(false);
  const dragItem = React.useRef<number | null>(null);
  const jobType = queryParams?.type;
  const dragOverItem = React.useRef<number | null>(null);
  const [card, setCard] = useState<any>([])
  const [exportLoading, setExportLoading] = useState(false)






  const dragStart = (e: any) => {
    dragItem.current = e;
  }
  const dragEnter = (e: any) => {
    dragOverItem.current = e;
  }


  const drop = () => {
    const copyListItems = [...card];
    const dragItemContent = copyListItems[dragItem.current as number];
    copyListItems.splice(dragItem.current as number, 1);
    copyListItems.splice(dragOverItem.current as number, 0, dragItemContent);
    dragItem.current = null;
    dragOverItem.current = null;
    setCard([...copyListItems]);
  }





  // generate automation.....................
  const generateAutomation = async () => {
    try {
      let payload = {
        job_id: queryParams?.job_id,
        file_path: fileName,
      }
      setLoading(true)
      const apiRes = await apis.Automation.generate(queryParams?.id as string, payload);
      const data = apiRes?.data?.replace(/^[\s\S]*?<html\b/, '<html').replace(/<\/html>[\s\S]*$/, '</html>');
      setAutomationData(data)

    } catch (error) {
      Toast.error(error)
    } finally {
      setLoading(false)
    }
  }




  //get details of automation and enhanced data..
  const fetchData = async () => {
    try {
      setLoading2(true);

      // get Automation Details.....
      const automationRes = await apis.Automation.details(queryParams?.id as string);
      setDetails(automationRes);

      // get enhanced details.....
      if (jobType === "jobListing") {
        const jobRes = await apis.Job.details(queryParams?.job_id);
        setEnhancedData(jobRes);
      }
    } catch (error) {
      Toast.error(error);
    } finally {
      setLoading2(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);




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


  // upload pdf....................
  const handleUploadPdf = async (file: any) => {
    try {
      setLoading3(true)
      const onUploadProgress = (event: any) => {
        const percent = Math.round((event.loaded * 100) / event.total);
        setProgress(50 + percent / 2);
      };
      const apiRes = await apis.Common.uploadFile("file", file, onUploadProgress)
      setfileName(apiRes?.data?.file_name)
    } catch (error) {
      Toast.error(error)
    } finally {
      setLoading3(false)
    }
  }


  // select pdf..................
  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setProgress(0);
    const file = event.target.files?.[0];
    if (file) {
      const maxFileSize = 50 * 1024 * 1024;
      if (file.size > maxFileSize) {
        Toast.error("PDF size cannot be more than 50MB");
        return;
      }

      setBlobFile(file);
      handleUploadPdf(file);
    }
  };


  const handleClear = () => {
    setBlobFile(null)
    setProgress(0)
  }


  const handleExport = async () => {
    try {
      setExportLoading(true)
      let payload = {
        title: details?.name,
        content: automationData
      }
      const apiRes = await apis.Automation.export(payload)
      const url = `${apiRes?.data?.base_url}/uploads/documents/${apiRes?.data?.file_name}`
      window.open(url, "_blank")
    } catch (error) {
      Toast.error(error)
    } finally {
      setExportLoading(false)
    }
  }
  const handleChange = (value: string) => {

    setAutomationData(value);
  };



  const handleCopyToClipboard = () => {
    const element: any = document.querySelector("[contentEditable]");
    if (element) {
      const textToCopy = element?.innerText;
      navigator.clipboard
        .writeText(textToCopy)
        .then(() => {
          setIsCopied(true);
          setTimeout(() => setIsCopied(false), 2000);
        })
        .catch((err) => {
          console.error("Failed to copy: ", err);
        });
    }
  };


  useEffect(() => {
    setCard([{ id: "enhancedCard", content: (index: number) => <EnhancedCard enhancedData={enhancedData} dragStart={dragStart} dragEnter={dragEnter} loading={loading2} /> }, { id: "notes", content: () => <NotesCard /> },])
  }, [enhancedData, loading2])

  return (
    <div className="bg-white w-full">

      <div className="grid grid-cols-12 gap-4 w-full">
        <div className="col-span-12 lg:col-span-12 w-full">
          {automationData ? (
            <div className="w-full ">
              <CardContent className="p-1">
                {/* <ScrollArea className="h-[400px]">
                  <div contentEditable dangerouslySetInnerHTML={{ __html: content }} className="min-h-[200px] border p-2"></div>
                </ScrollArea> */}

              </CardContent>
              <div className="mt-4 flex justify-end gap-2">
                <Button variant="default" className="text-primary h-10 bg-primary" onClick={handleExport}><Loader color={"text-primary"} loading={exportLoading} />Export</Button>
                {isCopied ? (
                  <div className="flex items-center gap-2 px-4 py-2 bg-green-100 border border-green-300 rounded-md h-10">
                    <img src={gif.src} alt="Copied" className="w-4 h-4" />
                    <span className="text-green-600 text-sm font-medium">Copied</span>
                  </div>
                ) : (
                  <Button className="theme-background h-10 text-white" onClick={handleCopyToClipboard}>Copy to Clipboard</Button>
                )}
              </div>
            </div>
          ) : blobFile ? (
            <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">
                        <Icons.Pdf />
                        <CardDescription className="text-gray text-xs">
                          <div className="font-semibold text-xs theme-color">{blobFile.name}</div>
                          {formatFileSize(blobFile.size)}
                        </CardDescription>
                      </div>
                      {loading || !loading3 && (
                        <button type="button" className="text-gray cursor-pointer hover:text-red-500 focus:outline-none " onClick={handleClear} disabled={loading}><Icons.CrossIcon /></button>
                      )}
                    </div>
                    {loading3 && (
                      <div className="flex items-center gap-2">
                        <Progress value={progress} />
                        <span className="text-gray text-xs font-normal">{progress}%</span>
                      </div>
                    )}
                  </div>
                </div>
                <div className="flex justify-end mt-6">

                </div>
              </CardContent>
            </div>
          ) : (
            <div className="">
              <CardContent className="flex flex-col items-center p-0 justify-center w-full">
                <div className=" border-2 border-dashed w-full border-primary rounded-lg flex flex-col items-center justify-center py-6">
                  <Button size={"lg"} className="flex  add-category-btn items-center font-medium gap-2 steps-proceed-btn mt-2 text-white px-4 py-2  text-sm hover:bg-yellow-600">
                    Add Cateory
                  </Button>
                  {/* <div className="w-12 h-12 rounded-full bg-blue-50 flex items-center justify-center mb-4"> */}
                  {/* <Upload className="h-6 w-6 cursor-pointer text-blue-500" onClick={handleFileSelect} /> */}
                  {/* </div> */}
                  <Input type="file" accept=".pdf" hidden ref={fileInputRef} onChange={handleFileChange} className="hidden" />
                  <p className="fs-12 cursor-pointer" onClick={handleFileSelect}>{"Couldn't find a suitable category? Add your own."}</p>
                </div>

              </CardContent>
            </div>
          )}
        </div>

        {/* AI Results and Notes Section */}
        {/* {
          jobType === "jobListing" && <div className="col-span-12 lg:col-span-4">
            <div className="space-y-4">
              <EnhancedCard enhancedData={enhancedData} />
              <NotesCard />
            </div>
          </div>
        } */}
        {
          jobType === "jobListing" && <div className="col-span-12 lg:col-span-4">
            {
              card?.map((res: any, index: number) => (
                <div
                  key={index}
                  onDragStart={() => dragStart(index)}
                  onDragEnter={() => dragEnter(index)}
                  onDragEnd={() => drop()}
                  draggable
                  className=" mb-6"
                >

                  {res?.content(index)}
                </div>
              ))
            }
          </div>
        }
      </div>
    </div >

  );
}


export default UploadFile;