"use client";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { toast } from "sonner";

import { Input } from "@/components/ui/input";
import { close, error, loading, successCallback } from "@/config/swal";
import {
  listData5Data,
  listDataAllNonPagination,
  mediaTrackingSave,
} from "@/service/media-tracking/media-tracking";
import { useEffect, useState } from "react";

export default function TrackingMediaModal(props: {
  triggerFetch: () => void;
}) {
  const [content, setContent] = useState<any>([]);
  const [inputValue, setInputValue] = useState("");
  const [selectedId, setSelectedId] = useState(0);
  useEffect(() => {
    initFecth();
  }, []);

  const initFecth = async () => {
    const response = await listData5Data();
    setContent(response?.data?.data.content);
  };

  const fecthAll = async (search?: string) => {
    const response = await listDataAllNonPagination(search || inputValue);
    setContent(response?.data?.data.content);
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    const nowLength = value.split(" ").length;
    const prevLength = inputValue.split(" ").length;

    setInputValue(value);

    if (value === "") {
      initFecth();
      setSelectedId(0);
    }

    if (/\s/.test(value)) {
      console.log("Terdapat spasi dalam input");
      fecthAll();
    }

    if (nowLength !== prevLength) {
      fecthAll();
    }
  };

  const doSave = async () => {
    loading();
    const req = {
      mediaUploadId: selectedId,
      duration: 24,
      scrapingPeriod: 3,
    };

    const res = await mediaTrackingSave(req);
    if (res?.error) {
      error(res?.message);
      return false;
    }
    close();

    toast("Berhasil Menambahkan", {
      description: "",
    });
    props.triggerFetch();
    return false;
  };

  return (
    <Dialog>
      <DialogTrigger asChild>
        <Button className="bg-blue-600" size="md">
          Tracking Berita
        </Button>
      </DialogTrigger>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>Form Tracking Berita</DialogTitle>
        </DialogHeader>
        <div className="flex flex-col gap-2">
          {" "}
          <Input
            type="text"
            placeholder="Content"
            value={inputValue}
            onChange={handleInputChange}
          />{" "}
          <div className="w-full border rounded-sm text-xs p-2 flex flex-col max-h-[300px] overflow-auto">
            {content.length > 0 &&
              content.map((item: any) => (
                <a
                  key={item.id}
                  className={`cursor-pointer  px-2 py-4 ${
                    selectedId === item.id
                      ? "font-bold bg-gray-200 rounded-sm"
                      : "hover:bg-gray-100 hover:font-semibold"
                  }`}
                  onClick={() => {
                    setSelectedId(item.id);
                    setInputValue(item.title);
                    fecthAll(item.title);
                  }}
                >
                  {item.title}
                </a>
              ))}
          </div>
        </div>
        {/* <DialogFooter className="sm:justify-start">
          <DialogClose asChild>
            <Button type="button">Close</Button>
          </DialogClose>
        </DialogFooter> */}
        <DialogFooter className="flex justify-end gap-2">
          <Button className="bg-blue-600 text-white" onClick={doSave}>
            Tracking Berita
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
