"use client";
import axios from "axios";
import { Link } from "react-router-dom";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useQuery } from "@tanstack/react-query";
import { useLanguage } from "@/store/language-context";

import Breadcrumb from "@/ui/breadcrumb";
import AccreditationsLoading from "@/views/accreditations/loading";
import errorimg from "@/assets/used-images/error.png";

import { cn } from "@/lib/utils";
import { ArrowUpLeft, FilterIcon, RefreshCcw } from "lucide-react";
import { Button } from "@/components/ui/button";

import AccreditationsFilter from "./components/filter";

const Accreditations = () => {
    const { URL } = useLanguage();
    const { t } = useTranslation();
    const [filter, setFilter] = useState(false);
    const [search, setSearch] = useState("");

    const { data: accreditations, error, isLoading, refetch } = useQuery({
        queryKey: ['accreditations', URL, search],
        queryFn: async () => {
            const response = await axios.get(`${URL}/dependencies?title=${search}`);
            if (response.status !== 200) throw new Error(t('custom.err'))
            return response?.data?.data?.data
        },
        staleTime: 1000 * 60 * 10,  // 10min
        gcTime: 1000 * 60 * 10,
        refetchOnMount: false,
        refetchOnWindowFocus: false,
        retry: 0,
    });

    if (error) {
        return (
            <div className="text-center py-8 flex flex-col items-center justify-center gap-4 layout h-screen">
                <p className="text-red-500 text-xl">{t('custom.err')}</p>
                <div className="grid place-items-center">
                    <Button
                        variant="outline"
                        className="mt-2 bg-secondary-tw text-white px-4 py-2 rounded-md"
                        onClick={() => refetch && refetch()}
                    >
                        {t('custom.try-again')} <RefreshCcw />
                    </Button>
                </div>
            </div>
        )
    };

    // if (isLoading) {
    //     return (
    //         <AccreditationsLoading />
    //     )
    // };

    return (
        <>
            <Breadcrumb pages={[t('routes.accreditations')]} />

            <div className="layout">
                <Button
                    disabled={isLoading}
                    className={cn("bg-primary-tw text-white",
                        filter ? "!opacity-0 h-0 w-0 " : "opacity-100 max-h-full w-24 mb-5"
                    )}
                    onClick={() => setFilter((prev) => !prev)}
                >
                    <FilterIcon size={24} color="white" />
                    <span>{t('training-courses.filter')}</span>
                </Button>
                <section className='flex items-start gap-2 w-full max-lg:flex-col'>
                    <AccreditationsFilter
                        filter={filter}
                        setFilter={setFilter}
                        setSearch={setSearch}
                        search={search}
                    />
                    <section className={cn(filter ? "w-full lg:w-8/12" : "w-full")}>
                        <section className={cn("grid gap-6 max-lg:px-2 w-full relative",
                            filter ? "xl:grid-cols-2" : "xl:grid-cols-3 2xl:grid-cols-4",
                            ((error || !accreditations?.length) && !isLoading) && "xl:!grid-cols-1"
                        )}>
                            {
                                isLoading ?
                                    <AccreditationsLoading />
                                    :
                                    accreditations?.length ?
                                        accreditations?.map((partner: any, i: number) => (
                                            <Link
                                                to={`/accreditations/${partner?.id}`}
                                                key={partner?.id || i}
                                                className="bg-white border border-gray-300 w-full overflow-hidden p-0 rounded-xl mb-3 mx-1 flex flex-col justify-between items-center"
                                            >
                                                <div className="w-full h-32 bg-gray-200 rounded-b-full relative overflow-hidden">
                                                </div>

                                                <div className="w-40 h-40 -mt-20 mb-4 relative z-10 bg-white rounded-full flex justify-center items-center">
                                                    <img
                                                        src={partner?.image}
                                                        alt={partner?.title || partner?.name}
                                                        className="w-28 h-20 object-contain"
                                                    />
                                                </div>

                                                <div className="px-4 mb-4 text-center capitalize">
                                                    <p className="text-lg font-medium text-common-text">
                                                        {partner?.title}
                                                    </p>
                                                </div>

                                                <div className="px-4 pb-4 w-full">
                                                    <button
                                                        className="w-full bg-primary-tw hover:bg-primary-tw/90 text-white font-medium py-2 px-4 rounded-lg transition-all  flex items-end justify-center group gap-1"
                                                    >
                                                        <span>
                                                            {t('custom.more-details')}
                                                        </span>
                                                        <span>
                                                            <ArrowUpLeft size={22} className='group-hover:-rotate-45 transition-all mt-1' />
                                                        </span>
                                                    </button>
                                                </div>
                                            </Link>
                                        ))
                                        :
                                        (
                                            <div className='grid place-items-center min-h-[50dvh]'>
                                                <img src={errorimg} alt="" className="w-3/12" />
                                            </div>
                                        )
                            }

                        </section>
                    </section>
                </section>
            </div>
        </>
    );
};
export default Accreditations;