"use client"

import {getUsefulById} from "@/shared/api/usefulSvc";
import {UsefulItem} from "@/shared/types/useful";
import {useState} from "react";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger
} from "@/shared/ui/dialog";
import {Accordion, AccordionContent, AccordionItem, AccordionTrigger} from "@/shared/ui/accordion";
import {Button} from "@/shared/ui/button";
import Image from "next/image";
import { useTranslations } from "next-intl";

interface UsefulItemData {
  id: number
  name: string
  description: string
  video_url?: string
  link_url?: string
  file_url?: string
}

interface UsefulSectionProps {
  usefuls: UsefulItem[]
}

const UsefulSection = ({ usefuls }: UsefulSectionProps) => {
  const [items, setItems] = useState<UsefulItemData[]>([])
  const [openId, setOpenId] = useState<number | null>(null)
  const t = useTranslations("")

  const fetchItems = async (id: number) => {
    try {
      const { data } = await getUsefulById(id);
      setItems(data);
    } catch (error) {
      console.error("Error fetching items", error);
    }
  }

  const handleDialogOpen = (isOpen: boolean, id: number) => {
    if (isOpen && id !== openId) {
      setOpenId(id);
      fetchItems(id);
    }
  }

  return (
      <div className={"my-container section-wrapper"}>
        <h1 className={"section-title text-center"}>{t("Foydali")}</h1>
        <div className={"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mt-12 px-4 md:px-0"}>
          {usefuls.map((useful) => (
              <div key={useful.id} className={"cursor-pointer border hover:border-primary transition-all duration-400 bg-white p-12 w-full flex flex-col justify-center items-center gap-2 h-full"}>
                <Dialog onOpenChange={(isOpen) => handleDialogOpen(isOpen, useful.id)}>
                  <DialogTrigger asChild>
                    <div className={"p-12 w-full flex flex-col items-center gap-2"}>
                      <Image src={useful.image} alt={useful.name} width={100} height={100} />
                      <h1 className={"text-xl font-bold text-center"}>{useful.name}</h1>
                    </div>
                  </DialogTrigger>
                  <DialogContent className="sm:max-w-6/12">
                    <DialogHeader>
                      <DialogTitle>{useful.name}</DialogTitle>
                      <DialogDescription>
                        {t("Foydali ma'lumotlar ro'yxati")}
                      </DialogDescription>
                    </DialogHeader>

                    <Accordion type="single" collapsible className="w-full">
                      {items.map((item) => (
                          <AccordionItem value={`item-${item.id}`} key={item.id}>
                            <AccordionTrigger>{item.name}</AccordionTrigger>
                            <AccordionContent>
                              <div className={`${item.video_url && "grid grid-cols-2"}`}>
                                <p className="mb-2">{item.description}</p>
                                {item.video_url && (
                                    <iframe
                                        width="100%"
                                        height="315"
                                        src={item.video_url.replace("watch?v=", "embed/")}
                                        title={item.name}
                                        className={"rounded-xl"}
                                        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                                        allowFullScreen
                                    ></iframe>
                                )}
                              </div>
                              {item.file_url && (
                                  <a href={item.file_url} target="_blank" rel="noopener noreferrer">
                                    <Button size="sm">{t("Download PDF")}</Button>
                                  </a>
                              )}

                              {item.link_url && (
                                  <a href={item.link_url} target="_blank" rel="noopener noreferrer">
                                    <Button size="sm">{t("Download PDF")}</Button>
                                  </a>
                              )}
                            </AccordionContent>
                          </AccordionItem>
                      ))}
                    </Accordion>

                    <DialogFooter>
                      <Button size={"lg"} type="button" onClick={() => setOpenId(null)}>
                        {t("Yopish")}
                      </Button>
                    </DialogFooter>
                  </DialogContent>
                </Dialog>
              </div>
          ))}
        </div>
      </div>
  );
}

export default UsefulSection;
