"use client";
import React, {useEffect, useState} from "react";
import {Button} from "./ui/button";
import {toast} from "react-toastify";
import privateApi from "@/service/http/privateCall.axios";
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "./ui/dialog";
import {Label} from "./ui/label";
import {Input} from "./ui/input";
import {API_URL, UsersType} from "@/constants";
import {Language} from "@/types";
import Loader from "./Loader";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "./ui/select";
async function fetchLanguages() {
    console.log('users table exports')

  const res = await fetch(`${API_URL}/language/get/all`,{cache:"no-cache"});

  if (!res.ok) {
    throw new Error("Failed to get data");
  }

  const data = await res.json();

  return data;
}
export default function UsersTableExport({table}: {table: UsersType}) {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<Language[]>([]);
  const [limit, setLimit] = useState<number | null>(null);
  const [lang, setLang] = useState<string>("fa");

  useEffect(() => {
    let active = true;

    setLoading(true);
    fetchLanguages()
      .then((res) => {
        if (!active) return;
        setData(res.data);
      })
      .catch(console.error)
      .finally(() => active && setLoading(false));

    return () => {
      active = false;
    };
  }, []);

  if (loading) {
    return <Loader />;
  }
  const exportUsers = async () => {
    try {
      await privateApi.get(
        `/user/export/${table}${lang && `?lang=${lang}`}${
          limit ? `&limit=${limit}` : ""
        }`
      );

      toast.success("دانلود آماده شد!");
    } catch (error) {
      toast.error("خطا در خروجی گرفتن اکسل");
    }
  };

  return (
    <Dialog>
      <form dir="ltr" onSubmit={exportUsers}>
        <DialogTrigger asChild>
          <Button
            variant="outline"
            className="text-green-800 shadow-sm shadow-green-600 w-[240px] max-w-full"
          >
            <span>
              <svg
                stroke="currentColor"
                fill="currentColor"
                strokeWidth="0"
                viewBox="0 0 24 24"
                height="1em"
                width="1em"
                xmlns="http://www.w3.org/2000/svg"
              >
                <path d="M2.85858 2.87732L15.4293 1.0815C15.7027 1.04245 15.9559 1.2324 15.995 1.50577C15.9983 1.52919 16 1.55282 16 1.57648V22.4235C16 22.6996 15.7761 22.9235 15.5 22.9235C15.4763 22.9235 15.4527 22.9218 15.4293 22.9184L2.85858 21.1226C2.36593 21.0522 2 20.6303 2 20.1327V3.86727C2 3.36962 2.36593 2.9477 2.85858 2.87732ZM4 4.73457V19.2654L14 20.694V3.30599L4 4.73457ZM17 19H20V4.99997H17V2.99997H21C21.5523 2.99997 22 3.44769 22 3.99997V20C22 20.5523 21.5523 21 21 21H17V19ZM10.2 12L13 16H10.6L9 13.7143L7.39999 16H5L7.8 12L5 7.99997H7.39999L9 10.2857L10.6 7.99997H13L10.2 12Z"></path>
              </svg>
            </span>
            <span>خروجی اکسل</span>
          </Button>
        </DialogTrigger>
        <DialogContent className="sm:max-w-[425px]" dir="rtl">
          <DialogHeader>
            <DialogTitle>تنظیمات خروجی</DialogTitle>
            {/* <DialogDescription>
              Make changes to your profile here. Click save when you&apos;re
              done.
            </DialogDescription> */}
          </DialogHeader>
          <div className="grid gap-4 w-full">
            <div className="grid gap-3 w-full">
              <Label htmlFor="name-1">تعداد کاربران برای خروجی</Label>
              <Input
                value={limit ? String(limit) : ""}
                onChange={(e) => setLimit(+e.target.value)}
                id="name-1"
                name="name"
              />
            </div>
            <div className="grid gap-3 w-full">
              <Label htmlFor="username-1">انتخاب زبان</Label>
              <Select
                dir="rtl"
                value={lang}
                onValueChange={(value) => setLang(value)}
              >
                <SelectTrigger>
                  <SelectValue placeholder="انتخاب تخصص" />
                </SelectTrigger>

                <SelectContent className="w-full">
                  {data.map((exp) => {
                    return (
                      <SelectItem key={exp.id} value={String(exp.slug)}>
                        {exp.title}
                      </SelectItem>
                    );
                  })}
                </SelectContent>
              </Select>
            </div>
          </div>
          <DialogFooter>
            <DialogClose asChild>
              <Button variant="outline">انصراف</Button>
            </DialogClose>
            <Button onClick={exportUsers} type="submit">
              ذخیره تغییرات
            </Button>
          </DialogFooter>
        </DialogContent>
      </form>
    </Dialog>
  );
}
