import Header from "@/components/header/Header";
import DashboardLayout from "@/components/Layout/DashboardLayout";
import Loader from "@/components/Loader/loader";
import PreviousButton from "@/components/previousBtn/previousButton";
import MyTable from "@/components/tables/MyTable";
import styles from "@/styles/modules/userManagement.module.css";
import {
  useGetPaymentHistoryQuery,
  useLazyGetPaymentCSVQuery,
  useLazyGetPaymentExcelQuery,
} from "@/utils/Redux-Toolkit/services/Payment";
import {
  GridColDef,
  GridPaginationModel,
  GridRenderCellParams,
} from "@mui/x-data-grid";
import { useSession } from "next-auth/react";
import Image from "next/image";
import React, { useEffect, useMemo, useState } from "react";
// import { useRouter } from "next/router";
import {
  PaymentFilters,
  PaymentFilterModel,
} from "@/components/tables/PaymentSearch";
import toast from "react-hot-toast";
import NotFoundCard from "@/components/Cards/NotFoundCard";
import StatusBadge from "@/components/ui/StatusBadge";

const PaymentManagement = () => {
  // Session
  const session = useSession();
  // const router = useRouter();
  const token = session?.data?.user?.token || "";

  // RTK Query
  const { data, error, isLoading } = useGetPaymentHistoryQuery(
    { token },
    { skip: !token, refetchOnMountOrArgChange: true }
  );
  const [triggerGetExcel] = useLazyGetPaymentExcelQuery();
  const [triggerGetCSV] = useLazyGetPaymentCSVQuery();
  // states
  const [tableData, setTableData] = useState([]);
  const [filters, setFilters] = useState<PaymentFilterModel>({
    captureId: "",
    payer: "",
    payee: "",
    purpose: "",
    status: "",
    createdDate: "",
  });

  const [paginationModel, setPaginationModel] = useState<GridPaginationModel>({
    page: 0,
    pageSize: 10,
  });

  const filteredRows = useMemo(() => {
    return tableData?.filter((row: any) => {
      if (
        filters?.payer &&
        !row?.payerUser?.name
          .toLowerCase()
          .includes(filters?.payer?.toLowerCase())
      )
        return false;
      if (
        filters?.payee &&
        !row?.payeeUser?.name
          .toLowerCase()
          .includes(filters?.payee?.toLowerCase())
      )
        return false;
      if (filters?.purpose && row?.purpose !== filters?.purpose) return false;
      if (filters?.status && row?.status !== filters?.status) return false;
      if (filters?.createdDate) {
        const rowDate = new Date(row?.createdAt).toISOString().slice(0, 10);
        if (rowDate !== filters?.createdDate) return false;
      }
      // if (filters?.captureId && row?.captureId !== filters?.captureId)
      //   return false;
      if (
        filters?.captureId &&
        !row?.captureId
          ?.toLowerCase()
          .includes(filters?.captureId?.toLowerCase())
      )
        return false;
      return true;
    });
  }, [tableData, filters]);

  // Paginate filtered rows on the frontend
  const paginatedRows = useMemo(() => {
    const startIndex = paginationModel.page * paginationModel.pageSize;
    const endIndex = startIndex + paginationModel.pageSize;
    return filteredRows?.slice(startIndex, endIndex) || [];
  }, [filteredRows, paginationModel]);

  const columns: GridColDef[] = [
    { field: "id", headerName: "ID", width: 70 },
    {
      field: "captureId",
      headerName: "Transaction ID",
      width: 170,
      renderCell: (params: GridRenderCellParams) => {
        if (params.value && params.value.length > 1) {
          return <p>{params.value}</p>;
        } else {
          return <p>N/A</p>;
        }
      },
    },
    {
      field: "payerUser",
      headerName: "Payer",
      width: 160,
      renderCell: (params: GridRenderCellParams) => {
        const { name, image } = params?.value;
        return (
          <div
            style={{
              alignItems: "center",
              display: "flex",
              justifyContent: "flex-start",
              gap: "12px",
              position: "relative",
            }}
          >
            <Image
              src={image}
              alt={name}
              width={100}
              height={100}
              style={{
                width: "35px",
                height: "35px",
                borderRadius: "50%",
                objectFit: "cover",
              }}
            />

            {/* {userType === "waiter" ? (
              <div
                style={{
                  width: "20px",
                  height: "20px",
                  display: "flex",
                  justifyContent: "center",
                  alignItems: "center",
                  flexShrink: "0",
                  position: "absolute",
                  left: "19px",
                  top: "26px",
                  backgroundColor: "rgb(29 66 138)",
                  borderRadius: "50%",
                }}
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  viewBox="0 0 512 512"
                  style={{ width: "12px", fill: "#fff" }}
                >
                  <path d="M216 64c-13.3 0-24 10.7-24 24s10.7 24 24 24l16 0 0 33.3C119.6 157.2 32 252.4 32 368l448 0c0-115.6-87.6-210.8-200-222.7l0-33.3 16 0c13.3 0 24-10.7 24-24s-10.7-24-24-24l-40 0-40 0zM24 400c-13.3 0-24 10.7-24 24s10.7 24 24 24l464 0c13.3 0 24-10.7 24-24s-10.7-24-24-24L24 400z" />
                </svg>
              </div>
            ) : userType === "client" ? (
              <div
                style={{
                  width: "20px",
                  height: "20px",
                  display: "flex",
                  justifyContent: "center",
                  alignItems: "center",
                  flexShrink: "0",
                  position: "absolute",
                  left: "19px",
                  top: "26px",
                  backgroundColor: "#152e61",
                  borderRadius: "50%",
                }}
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  viewBox="0 0 448 512"
                  style={{ width: "12px", fill: "#fff" }}
                >
                  <path d="M96 128a128 128 0 1 0 256 0A128 128 0 1 0 96 128zm94.5 200.2l18.6 31L175.8 483.1l-36-146.9c-2-8.1-9.8-13.4-17.9-11.3C51.9 342.4 0 405.8 0 481.3c0 17 13.8 30.7 30.7 30.7l131.7 0c0 0 0 0 .1 0l5.5 0 112 0 5.5 0c0 0 0 0 .1 0l131.7 0c17 0 30.7-13.8 30.7-30.7c0-75.5-51.9-138.9-121.9-156.4c-8.1-2-15.9 3.3-17.9 11.3l-36 146.9L238.9 359.2l18.6-31c6.4-10.7-1.3-24.2-13.7-24.2L224 304l-19.7 0c-12.4 0-20.1 13.6-13.7 24.2z" />
                </svg>
              </div>
            ) : null} */}

            <p>{name}</p>
          </div>
        );
      },
    },
    {
      field: "payeeUser",
      headerName: "Payee",
      width: 160,
      renderCell: (params: GridRenderCellParams) => {
        const { name, image } = params?.value;
        return (
          <div
            style={{
              alignItems: "center",
              display: "flex",
              justifyContent: "flex-start",
              gap: "12px",
              position: "relative",
            }}
          >
            <Image
              src={image}
              alt={name}
              width={100}
              height={100}
              style={{
                width: "35px",
                height: "35px",
                borderRadius: "50%",
                objectFit: "cover",
              }}
            />

            {/* {userType === "waiter" ? (
              <div
                style={{
                  width: "20px",
                  height: "20px",
                  display: "flex",
                  justifyContent: "center",
                  alignItems: "center",
                  flexShrink: "0",
                  position: "absolute",
                  left: "19px",
                  top: "26px",
                  backgroundColor: "rgb(29 66 138)",
                  borderRadius: "50%",
                }}
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  viewBox="0 0 512 512"
                  style={{ width: "12px", fill: "#fff" }}
                >
                  <path d="M216 64c-13.3 0-24 10.7-24 24s10.7 24 24 24l16 0 0 33.3C119.6 157.2 32 252.4 32 368l448 0c0-115.6-87.6-210.8-200-222.7l0-33.3 16 0c13.3 0 24-10.7 24-24s-10.7-24-24-24l-40 0-40 0zM24 400c-13.3 0-24 10.7-24 24s10.7 24 24 24l464 0c13.3 0 24-10.7 24-24s-10.7-24-24-24L24 400z" />
                </svg>
              </div>
            ) : userType === "client" ? (
              <div
                style={{
                  width: "20px",
                  height: "20px",
                  display: "flex",
                  justifyContent: "center",
                  alignItems: "center",
                  flexShrink: "0",
                  position: "absolute",
                  left: "19px",
                  top: "26px",
                  backgroundColor: "#152e61",
                  borderRadius: "50%",
                }}
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  viewBox="0 0 448 512"
                  style={{ width: "12px", fill: "#fff" }}
                >
                  <path d="M96 128a128 128 0 1 0 256 0A128 128 0 1 0 96 128zm94.5 200.2l18.6 31L175.8 483.1l-36-146.9c-2-8.1-9.8-13.4-17.9-11.3C51.9 342.4 0 405.8 0 481.3c0 17 13.8 30.7 30.7 30.7l131.7 0c0 0 0 0 .1 0l5.5 0 112 0 5.5 0c0 0 0 0 .1 0l131.7 0c17 0 30.7-13.8 30.7-30.7c0-75.5-51.9-138.9-121.9-156.4c-8.1-2-15.9 3.3-17.9 11.3l-36 146.9L238.9 359.2l18.6-31c6.4-10.7-1.3-24.2-13.7-24.2L224 304l-19.7 0c-12.4 0-20.1 13.6-13.7 24.2z" />
                </svg>
              </div>
            ) : null} */}

            <p>{name}</p>
          </div>
        );
      },
    },
    {
      field: "assignmentId",
      headerName: "Item Id",
      width: 130,
      renderCell: (params: GridRenderCellParams) => {
        // console.log(params.value);
        return <p>{params.value}</p>;
      },
    },
    { field: "purpose", headerName: "Purpose", width: 130 },
    {
      field: "amount",
      headerName: "Amount",
      renderCell: (params: GridRenderCellParams) => {
        return (
          <p>
            {params.value
              ? ` $${parseFloat(params.value.split("$")[1].toString()).toFixed(
                  3
                )}`
              : "---"}
          </p>
        );
      },
      width: 100,
    },
    {
      field: "orderId",
      headerName: "Order Id",
      width: 140,
    },
    {
      field: "currency",
      headerName: "Currency",
      width: 80,
    },
    {
      field: "createdAt",
      headerName: "Created At",
      width: 100,
    },
    {
      field: "status",
      headerName: "Status",
      width: 180,
      renderCell: (params: GridRenderCellParams) => {
        if (!params.value) return null;
        return <StatusBadge status={params.value} />;
      },
    },
  ];
  const clearAll = () => {
    setFilters({
      payer: "",
      payee: "",
      purpose: "",
      status: "",
      createdDate: "",
      captureId: "",
    });
  };
  // Reset pagination to first page when filters change
  useEffect(() => {
    setPaginationModel({ page: 0, pageSize: paginationModel.pageSize });
  }, [filters]);

  // Use Effects
  useEffect(() => {
    const filteratedData =
      data?.data &&
      data?.data?.map((e: TransectionHistory, id: number) => {
        const uniqueKey = id + 1;
        return {
          id: uniqueKey < 10 ? `0${uniqueKey}` : uniqueKey,
          payerUser: {
            name: `${e?.payerId ? e?.payerId.firstname ?? "---" : "---"} ${
              e?.payerId ? e?.payerId.lastname ?? "---" : "---"
            }`,
            image: e?.payerId?.image?.startsWith("https://")
              ? e?.payerId?.image
              : "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT1oyt9166XWnxUIF4AgPIJSA2AfNh1ebiRig&s",
            userType: e?.payerId?.userType,
          },
          payeeUser: {
            name: `${e?.payeeId ? e?.payeeId?.firstname ?? "---" : "---"} ${
              e?.payeeId ? e?.payeeId?.lastname ?? "---" : "---"
            }`,
            image: e?.payeeId?.image?.startsWith("https://")
              ? e?.payeeId?.image
              : "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT1oyt9166XWnxUIF4AgPIJSA2AfNh1ebiRig&s",
            userType: e?.payeeId?.userType,
          },
          purpose: e.purpose,
          amount: `$${e.amount}`,
          orderId: e.orderId,
          currency: e.currency,
          createdAt: e.createdAt.slice(0, -14),
          status: e.orderStatus,
          assignmentId: e.assignmentId?._id,
          captureId: e.captureId,
          details: e,
        };
      });

    setTableData(filteratedData);
  }, [data]);

  const handleDownloadExcel = async () => {
    const { data, error } = await triggerGetExcel({ token });
    if (data?.success && data.fileUrl) {
      // The fileUrl is already a public S3 link
      const url = data.fileUrl;
      // Optional: derive a default filename from the URL
      const fileName = url.split("/").pop() || "report.xlsx";
      // Create an <a> tag to trigger download
      const link = document.createElement("a");
      link.href = url;
      link.download = fileName; // <-- download attribute :contentReference[oaicite:1]{index=1}
      document.body.appendChild(link);
      link.click();
      link.remove();
    } else {
      console.error("Failed to download report", error);
      toast.error("Could not retrieve report.");
    }
  };
  const handleDownloadCSV = async () => {
    const { data, error } = await triggerGetCSV({ token });
    if (data?.success && data.fileUrl) {
      // The fileUrl is already a public S3 link
      const url = data.fileUrl;
      // Optional: derive a default filename from the URL
      const fileName = url.split("/").pop() || "report.csv";
      // Create an <a> tag to trigger download
      const link = document.createElement("a");
      link.href = url;
      link.download = fileName; // <-- download attribute :contentReference[oaicite:1]{index=1}
      document.body.appendChild(link);
      link.click();
      link.remove();
    } else {
      console.error("Failed to download report", error);
      toast.error("Could not retrieve report.");
    }
  };

  return (
    <DashboardLayout>
      <Header />
      <div className="mainContent">
        <div className={styles.topPart}>
          <div className={styles.leftSide}>
            <PreviousButton />
            <h1>Payment Management</h1>
          </div>

          {/* {tableData && tableData?.length > 1 && (
            <form action="" className={styles.form}>
              <div className={styles.inputWrapper}>
                <input
                  type="text"
                  id="userSortingValue"
                  name="userSortingValue"
                  autoComplete="off"
                  placeholder="Enter here..."
                  // onChange={(e) => sortedFunction(e.target.value)}
                />

                <svg
                  width="25"
                  height="24"
                  viewBox="0 0 25 24"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path
                    d="M11.6416 21.75C5.9916 21.75 1.3916 17.15 1.3916 11.5C1.3916 5.85 5.9916 1.25 11.6416 1.25C17.2916 1.25 21.8916 5.85 21.8916 11.5C21.8916 17.15 17.2916 21.75 11.6416 21.75ZM11.6416 2.75C6.8116 2.75 2.8916 6.68 2.8916 11.5C2.8916 16.32 6.8116 20.25 11.6416 20.25C16.4716 20.25 20.3916 16.32 20.3916 11.5C20.3916 6.68 16.4716 2.75 11.6416 2.75Z"
                    fill="white"
                  />
                  <path
                    d="M22.142 22.7504C21.952 22.7504 21.762 22.6804 21.612 22.5304L19.612 20.5304C19.322 20.2404 19.322 19.7604 19.612 19.4704C19.902 19.1804 20.382 19.1804 20.672 19.4704L22.672 21.4704C22.962 21.7604 22.962 22.2404 22.672 22.5304C22.522 22.6804 22.332 22.7504 22.142 22.7504Z"
                    fill="white"
                  />
                </svg>
              </div>

              <select
                name="filteraionOption"
                id="filteraionOption"
                // onChange={(e) => setCategory(e.target.value)}
              >
                <option value="userName">Name</option>
                <option value="userEmail">Email</option>
              </select>
            </form>
          )} */}
        </div>
        <PaymentFilters
          filters={filters}
          onChange={setFilters}
          onClear={clearAll}
        />
        {isLoading ? (
          <Loader
            style={
              {
                "--loaderColor": "#1D428A",
              } as React.CSSProperties
            }
          />
        ) : error ? (
          <div className="fullWidth">
            <p className="errorMessage">Oh, there was an error.</p>
          </div>
        ) : tableData && tableData?.length ? (
          <MyTable
            columns={columns}
            rows={paginatedRows}
            section="Payments"
            onDownloadExcel={handleDownloadExcel}
            onDownloadCSV={handleDownloadCSV}
            isRowClickable={true}
            paginationModel={paginationModel}
            onPaginationModelChange={setPaginationModel}
            paginationInfo={{
              totalDocs: filteredRows?.length || 0,
              totalPages: Math.ceil(
                (filteredRows?.length || 0) / paginationModel.pageSize
              ),
              CurrentPage: paginationModel.page,
              LastPage:
                Math.ceil(
                  (filteredRows?.length || 0) / paginationModel.pageSize
                ) - 1,
              hasNext:
                (paginationModel.page + 1) * paginationModel.pageSize <
                (filteredRows?.length || 0),
              hasPrevious: paginationModel.page > 0,
            }}
          />
        ) : (
          <div className="fullWidth">
            <NotFoundCard message="There are no transaction history yet." />
          </div>
        )}
      </div>
    </DashboardLayout>
  );
};

export default PaymentManagement;
