"use client";

import { useMutation, useQuery } from "@tanstack/react-query";
import _ from "lodash";
import {
  Archive,
  Check,
  Download,
  HistoryIcon,
  Plus,
  Share,
  Star,
  Trash2,
  UploadCloud,
  UserPlus,
  X,
} from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import { useSearchParams } from "react-router";
import { toast } from "sonner";
import { productApi } from "~/api/products-api.service";
import {
  DataTable,
  type Column,
  type TableState,
} from "~/components/core/data-table";
import Loader from "~/components/loader";
import { Button } from "~/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "~/components/ui/card";
import { delay } from "~/features/delay";
import {
  stateToURLQuery,
  urlQueryToState,
} from "~/features/state-url-converter";
import { useAppSelector } from "~/hooks/use-app-dispatch";
import { useUsersContext } from "~/layouts/contexts/user-layout.context";
import type { RootState } from "~/store";
import ProductModal from "./components/modals/product-modal";
import { Badge } from "~/components/ui/badge";
import { HistoryModal } from "./components/modals/history-modal";
import { Textarea } from "~/components/ui/textarea";

export default function List() {
  // const { setEdit } = useUserModal();
  const [searchParams, setSearchParams] = useSearchParams();

  const [openHistories, setOpenHistories] = useState<IHistory[]>([]);

  const prevStates = useRef<Record<string, any>>(null);

  const [initStates, setInitStates] = useState<Record<string, any> | undefined>(
    undefined
  );

  const [states, setStates] = useState<TableState<IProduct> | undefined>(
    undefined
  );

  const { user } = useAppSelector((state: RootState) => state.app);

  const handleDelete = async (data: IProduct) => {
    const result = await productApi.delete(data);

    if (!result) return;

    refetch();
  };

  const handleBulkDelete = async (selectedUsers: IProduct[]) => {
    const result = await productApi.bulkDelete(selectedUsers);

    if (!result) return;

    refetch();

    toast.info(`Successfully deleted ${selectedUsers.length} products.`, {
      duration: 3000,
      description: "The products have been removed from the system.",
    });
  };

  const columns: Column<IProduct>[] = [
    {
      key: "sku",
      label: "Sku",
      displayType: "text",
      sortable: true,
    },
    {
      key: "title",
      label: "Title",
      displayType: "text",
      sortable: true,
    },
    {
      key: "description",
      label: "Description",
      displayType: "custom",
      sortable: true,
      render(value, row) {
        return (
          <Textarea readOnly value={value} className="resize-none"></Textarea>
        );
      },
    },
    {
      key: "tags",
      label: "Tags",
      displayType: "custom",
      render: (value, row) => {
        if (!row.tags.length) {
          return <Badge variant={"secondary"}>No tags</Badge>;
        }

        return (
          <div className="flex items-center gap-1 max-w-[200px] flex-wrap">
            {row.tags.map((role) => {
              return <Badge key={role}>{role}</Badge>;
            })}
          </div>
        );
      },
    },
    {
      key: "condition",
      label: "Condition",
      displayType: "badge",
    },
    {
      key: "brand",
      label: "Brand",
      displayType: "text",
    },
    {
      key: "location",
      label: "Location",
      displayType: "text",
    },
    {
      key: "created_at",
      label: "Created at",
      displayType: "datetime",
      sortable: true,
    },
    {
      key: "histories",
      label: "Status",
      displayType: "custom",
      render(value, row) {
        return (
          <div className="w-full flex items-center justify-center">
            {row.status ? (
              <Button size={"xs"} className="w-fit" variant={"ghost"}>
                <Check size={14} className="text-green-500" />
              </Button>
            ) : (
              <Button size={"xs"} className="w-fit" variant={"ghost"}>
                <X size={14} className="text-red-500" />
              </Button>
            )}
          </div>
        );
      },
    },
  ];

  const filterOptions: FilterOption[] = [
    {
      key: "title",
      label: "Title",
      type: "text" as const,
    },
    {
      key: "sku",
      label: "Sku",
      type: "text" as const,
    },
    {
      key: "description",
      label: "Description",
      type: "text" as const,
    },
    {
      key: "title",
      label: "Title",
      type: "text" as const,
    },
  ];

  const bulkActions = [
    {
      key: "delete",
      label: "Delete",
      icon: <Trash2 className="h-4 w-4 text-destructive" />,
      variant: "destructive" as const,
      action: handleBulkDelete,
      confirmMessage:
        "Are you sure you want to delete the selected products? This action cannot be undone.",
    },
  ];

  // 🎯 Custom Actions - Đa dạng và có điều kiện
  const customActions = [
    {
      key: "publist",
      label: "Publist",
      icon: <UploadCloud className="h-4 w-4" />,
      action: (data: IProduct) => {
        handlePublist(data);
      },
    },
    {
      key: "histories",
      label: "Histories",
      icon: <HistoryIcon className="h-4 w-4" />,
      action: (data: IProduct) => {
        setOpenHistories(data.histories);
      },
    },
  ];

  // Init state from URL
  useEffect(() => {
    const s = urlQueryToState(searchParams);
    setInitStates(s);
    setStates((prev) => (prev ? prev : s) as TableState<IProduct>); // Only set if state is not already set
  }, []);

  // Convert state to query string + only update if different from previous
  useEffect(() => {
    if (!states) return;

    const query = stateToURLQuery(states);
    setSearchParams(query);

    const { data, ...curStates } = states;
    if (_.isEqual(curStates, prevStates.current)) return;

    prevStates.current = curStates;
  }, [states]);

  // 👉 Stable queryKey to avoid unnecessary refetches
  const queryKey = useMemo(() => ["users", states], [states]);

  const { data, isLoading, refetch } = useQuery({
    queryKey,
    queryFn: async () => {
      if (!states) return [];
      await delay(300); // Simulate delay to see loading
      const res = await productApi.index(states as TableState<IProduct>);
      return res;
    },
    enabled: !!states,
  });

  const publistMutation = useMutation({
    mutationFn: async (data: Partial<IProduct>) => {
      await delay(300);

      return productApi.customAction(data.id || 0, "publist", data);
    },
    onSuccess: (data) => {
      console.log({ data });
      refetch();
    },
  });

  const handlePublist = async (data: Partial<IProduct>) => {
    toast.promise(
      publistMutation.mutateAsync(data), // gọi function để trả về promise
      {
        loading: "Loading...",
        success: (result) => `${data?.title} toast has been added`,
        error: "Error",
      }
    );
  };

  if (!initStates) return <Loader />;

  return (
    <div className="mx-auto space-y-6 ">
      <div className="max-w-full flex flex-col gap-6 ">
        <Card>
          <CardHeader className="flex items-center justify-between">
            <div>
              <CardTitle className="mb-1">Product</CardTitle>
              <CardDescription>Product</CardDescription>
            </div>

            <ProductModal onSubmit={refetch}>
              <Button>
                <Plus /> Create
              </Button>
            </ProductModal>
          </CardHeader>
          <CardContent>
            <div className="">
              <DataTable
                customActions={customActions}
                initialState={initStates}
                data={data?.data || []}
                columns={columns}
                searchKeys={["title"]}
                filterOptions={filterOptions}
                selectable={true}
                bulkActions={bulkActions}
                pagination={{
                  currentPage: data?.current_page || 1,
                  pageSize: data?.per_page || 10,
                  totalItems: data?.total || 0,
                  totalPages: data?.last_page || 0,
                  startIndex: data?.from || 0,
                  endIndex: data?.to || 0,
                }}
                loading={isLoading}
                onPaginationChange={(p) => {
                  setStates(
                    (prev) =>
                      ({
                        ...prev,
                        pagination: {
                          ...prev?.pagination,
                          currentPage: p.currentPage,
                          pageSize: p.pageSize,
                        },
                      } as TableState<IProduct>)
                  );
                }}
                onFilterChange={({ search, ...filters }) => {
                  setStates(
                    (prev) =>
                      ({
                        ...prev,
                        filters,
                        search,
                      } as TableState<IProduct>)
                  );
                }}
                onSortChange={(sort) => {
                  setStates(
                    (prev) =>
                      ({
                        ...prev,
                        sort,
                      } as TableState<IProduct>)
                  );
                }}
                onDelete={handleDelete}
                // onEdit={setEdit}
                options={{
                  disableDel(data) {
                    return data.id === user?.id;
                  },
                }}
              />
            </div>
          </CardContent>
        </Card>
      </div>

      <HistoryModal
        data={openHistories}
        open={openHistories.length > 0} // mở khi có ít nhất 1 item
        setOpen={(value) => {
          if (!value) setOpenHistories([]);
        }}
      />
    </div>
  );
}
