import {
  useAutoUnlockList,
  useStartAutoUnlock,
  useStopAutoUnlock,
} from "@/state/profile/profile.action";
import Image from "next/image";
import React from "react";
import { ImageConstant } from "../../../constant/ImageConstant";
import {
  Pagination,
  PaginationContent,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious,
} from "../ui/pagination";
import { Switch } from "../ui/switch";

type Transaction = {
  id: string | number;
  created_at: string;
  amount: string;
  source: string;
  is_active?: boolean;
  series?: {
    series_id: string | number;
    title?: string;
    thumbnail_high_3x4?: string;
  };
  nextEpisodeToUnlock?: {
    episode_number?: number;
    coin_price?: number;
  };
};

// Corrected API response type
type TransactionResponse = {
  meta: {
    page: number;
    limit: number;
    total: number;
    lastPage: number;
  };
  items: Transaction[];
};

const EpisodeAutoUnlocked = () => {
  const [page, setPage] = React.useState(1);

  const payload = {
    page,
    limit: 5,
  };

  const { data, isLoading, error, refetch } = useAutoUnlockList(payload) as {
    data: TransactionResponse | undefined;
    isLoading: boolean;
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    error: any;
    refetch: () => void;
  };

  const startUnlock = useStartAutoUnlock();
  const stopUnlock = useStopAutoUnlock();

  const handleSwitchChange = (isChecked: boolean, tx: Transaction) => {
    if (isChecked) {
      startUnlock.mutate(
        { seriesId: tx.series?.series_id, priority: 1 },
        {
          onSuccess: () => {
            refetch(); // ✅ refetch after success
          },
        }
      );
    } else {
      stopUnlock.mutate(
        { seriesId: tx.series?.series_id, priority: 1 },
        {
          onSuccess: () => {
            refetch(); // ✅ refetch after success
          },
        }
      );
    }
  };

  return (
    <div>
      <div className="flex justify-between items-center">
        <h5 className="text-[18px] text-[#D1D0CF] font-medium">
          Episode on Auto-Unlock
        </h5>
      </div>
      <hr className="border-white opacity-10 my-5" />

      <div className="bg-[#1A1A1A] p-5 rounded-2xl">
        {isLoading ? (
          <div className="min-h-[500px] flex items-center justify-center">
            <p className="text-gray-400">Loading...</p>
          </div>
        ) : error ? (
          <p className="text-red-400">Failed to load transactions</p>
        ) : data && data?.items?.length > 0 ? (
          <>
            {data?.items?.map((tx, index: number) => (
              <div
                key={`${tx?.id}_${index}`}
                className="grid grid-cols-1 md:grid-cols-12 gap-6 bg-[#1A1A1A] p-5 rounded-[12px]"
              >
                <div className="md:col-span-10">
                  <div className="table gap-5  md:flex">
                    {/* <Image src={tx?.series?.thumbnail_high_3x4} alt="" /> */}
                    <div className="relative aspect-[3/4] w-32 md:w-40">
                      <Image
                        src={
                          tx?.series?.thumbnail_high_3x4?.startsWith("http")
                            ? tx.series.thumbnail_high_3x4
                            : tx?.series?.thumbnail_high_3x4
                              ? `${process.env.NEXT_PUBLIC_IMAGE_BASE_URL}/${tx.series.thumbnail_high_3x4}`
                              : ImageConstant.imagePlaceHolder
                        }
                        alt=""
                        fill
                        className="object-cover rounded-md"
                        quality={100}
                      />
                    </div>

                    <div>
                      <h5 className="text-[20px] text-white my-2">
                        {tx?.series?.title || ""}
                      </h5>
                      <div>
                        <h5 className="text-[#ece7e7] mb-2">
                          Played to Ep{" "}
                          {tx?.nextEpisodeToUnlock?.episode_number || 1}
                        </h5>

                        <h6 className="bg-[#3D3D3D] w-fit p-2 px-6 rounded-sm border-1 border-[#262525] mb-3 flex gap-2 font-semibold">
                          <Image
                            src={ImageConstant.coin}
                            alt=""
                            width={30}
                            height={30}
                            className="w-5 h-5"
                          />{" "}
                          {tx?.nextEpisodeToUnlock?.coin_price || 0}
                        </h6>
                      </div>
                    </div>
                  </div>
                </div>
                <div className="md:col-span-2 flex justify-end">
                  <Switch
                    checked={tx?.is_active === true}
                    onCheckedChange={(val) => handleSwitchChange(val, tx)}
                  />
                </div>
              </div>
            ))}
          </>
        ) : (
          <div className="min-h-[200px] flex items-center justify-center">
            <p className="text-gray-400">No Episode on Auto-Unlock</p>
          </div>
        )}

        {/* Pagination */}
        {data?.meta && data.meta.lastPage > 1 && (
          <Pagination className="mt-5">
            <PaginationContent>
              {/* Previous */}
              <PaginationItem>
                <PaginationPrevious
                  href="#"
                  onClick={() => page > 1 && setPage(page - 1)}
                />
              </PaginationItem>

              {/* Page Numbers */}
              {Array.from({ length: data.meta.lastPage }, (_, i) => i + 1)?.map(
                (p) => (
                  <PaginationItem key={p}>
                    <PaginationLink
                      href="#"
                      isActive={p === page}
                      onClick={() => setPage(p)}
                    >
                      {p}
                    </PaginationLink>
                  </PaginationItem>
                )
              )}

              {/* Next */}
              <PaginationItem>
                <PaginationNext
                  href="#"
                  onClick={() => page < data.meta.lastPage && setPage(page + 1)}
                />
              </PaginationItem>
            </PaginationContent>
          </Pagination>
        )}
      </div>
    </div>
  );
};

export default EpisodeAutoUnlocked;
