/* eslint-disable react-hooks/rules-of-hooks */
"use client";
import React, { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Checkbox } from "@radix-ui/react-checkbox";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";

import { Input } from '@/components/ui/input'
import { Separator } from '@/components/ui/separator'
import { DollarSign, Eye, Pencil, PlusCircle, SearchIcon } from 'lucide-react'

import { ColumnDef } from "@tanstack/react-table";

import { DotsHorizontalIcon } from "@radix-ui/react-icons";
import DataTable from "@/components/Table";
import Loading from "@/app/(dashoard)/components/loading";
import { ErrorMessage } from "@/components/ui/error-message";
import { getPayments } from "@/lib/features/admin/payment/service";
import { PaymentProps } from "@/lib/features/admin/payment/type";

const Users = () => {


  // merge branches
  const [selectedId, setSelectedId] = useState<number | null>(null);


  /////////////////view user modal
  const [isViewModalOpen, setViewModalOpen] = useState(false);

  const openViewModal = (id: number) => {
    setSelectedId(id);
    setViewModalOpen(true);
  };

  // const closeViewModal = () => {
  //   setViewModalOpen(false);
  //   setSelectedId(null);
  // };



  /////////////////update user modal
  const [isUpdateModalOpen, setUpdateModalOpen] = useState(false);

  const openUpdateModal = (id: number) => {
    setSelectedId(id);
    setUpdateModalOpen(true);
  };

  // const closeUpdateModal = () => {
  //   setUpdateModalOpen(false);
  //   setSelectedId(null);
  // };

  // students
  const { data, isLoading, error } = useQuery({
    queryKey: ["payment-list"],
    queryFn: () => getPayments(),
  });

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

  console.log(isUpdateModalOpen, isViewModalOpen, selectedId)

  //error
  if (error) {
    return <ErrorMessage error={error} fallback="Dashboard error" />
  }

  const rowData: PaymentProps[] = data?.data || [];

  //columns
  const columns: ColumnDef<PaymentProps>[] = [
    {
      id: "select",
      header: ({ table }) => (
        <Checkbox
          checked={
            table.getIsAllPageRowsSelected() ||
            (table.getIsSomePageRowsSelected() && "indeterminate")
          }
          onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
          aria-label="Select all"
        />
      ),
      cell: ({ row }) => (
        <Checkbox
          checked={row.getIsSelected()}
          onCheckedChange={(value) => row.toggleSelected(!!value)}
          aria-label="Select row"
        />
      ),
      enableSorting: false,
      enableHiding: false,
    },


    {
      accessorKey: "tbl_userFname",
      header: () => <div className="text-left table-size">Names</div>,
      cell: ({ row }) => {
        return (
          <div className="text-left font-normal table-size" onClick={() => openViewModal(row?.original?.tbl_enrolId)}>
            {row.getValue("tbl_userFname") + " " + row.original?.tbl_userLname}
          </div>
        );
      },
    },

    {
      accessorKey: "tbl_userTel",
      header: () => <div className="text-left table-size">Tel</div>,
      cell: ({ row }) => {
        return (
          <div className="text-left font-normal table-size" onClick={() => openViewModal(row?.original?.tbl_enrolId)}>
            {row.getValue("tbl_userTel")}
          </div>
        );
      },
    },


    {
      accessorKey: "tbl_userEmail",
      header: () => <div className="text-left table-size">Email</div>,
      cell: ({ row }) => {
        return (
          <div className="text-left font-normal table-size" onClick={() => openViewModal(row?.original?.tbl_enrolId)}>
            {row.getValue("tbl_userEmail")}
          </div>
        );
      },
    },


    {
      accessorKey: "tbl_userName",
      header: () => <div className="text-left table-size">Username</div>,
      cell: ({ row }) => {
        return (
          <div className="text-left font-normal table-size" onClick={() => openViewModal(row?.original?.tbl_enrolId)}>
            {row.getValue("tbl_userName")}
          </div>
        );
      },
    },

    {
      accessorKey: "tbl_courseName",
      header: () => <div className="text-left table-size">Course</div>,
      cell: ({ row }) => {
        return (
          <div className="text-left font-normal table-size" onClick={() => openViewModal(row?.original?.tbl_enrolId)}>
            {row.getValue("tbl_courseName")}
          </div>
        );
      },
    },


    {
      accessorKey: "tbl_enrolDate",
      header: () => <div className="text-left table-size">Enrol date</div>,
      cell: ({ row }) => {
        return (
          <div className="text-left font-normal table-size" onClick={() => openViewModal(row?.original?.tbl_enrolId)}>
            {row.getValue("tbl_enrolDate")}
          </div>
        );
      },
    },


    {
      accessorKey: "tbl_paid_courseAmt",
      header: () => <div className="text-left table-size">Paid amount</div>,
      cell: ({ row }) => {
        return (
          <div className="text-left font-normal table-size" onClick={() => openViewModal(row?.original?.tbl_enrolId)}>
            RWF {row.getValue("tbl_paid_courseAmt")}
          </div>
        );
      },
    },

    {
      accessorKey: "tbl_paid_courseDate",
      header: () => <div className="text-left table-size">Pay date</div>,
      cell: ({ row }) => {
        return (
          <div className="text-left font-normal table-size" onClick={() => openViewModal(row?.original?.tbl_enrolId)}>
            {row.getValue("tbl_paid_courseDate") + ' ' + row?.original?.tbl_paid_courseTime}
          </div>
        );
      },
    },


    {
      id: "actions",
      enableHiding: false,
      header: "Actions",
      cell: ({ row }) => {

        return (
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="ghost" className="h-8 w-8 p-0">
                <span className="sr-only">Open menu</span>
                <DotsHorizontalIcon className="h-4 w-4" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuSeparator />

              <DropdownMenuItem onClick={() => openViewModal(row?.original?.tbl_enrolId)}>
                <Eye />
                User details
              </DropdownMenuItem>


              <>
                <DropdownMenuItem onClick={() => openUpdateModal(row?.original?.tbl_enrolId)}>
                  <Pencil className="text-blue-500" />
                  Update
                </DropdownMenuItem>
              </>



            </DropdownMenuContent>
          </DropdownMenu>
        );
      },
    },
  ];

  return (
    <>




      <div className="flex flex-row">
        <div className="flex items-center justify-between">
          <div className="space-y-1">
            <h4 className="text-2xl font-semibold tracking-tight flex gap-2">
              <DollarSign />
              Payments
            </h4>
          </div>
        </div>

        <div className="ml-auto mr-4 flex items-center space-x-3">
          <Input type="" placeholder="Search" />
          <Button className="px-4 py-2 button">
            <SearchIcon />
          </Button>
        </div>

        <div className="ml-auto mr-4">

          <Button className="button">
            <PlusCircle className="mr-0 h-4 w-4" />
          </Button>

        </div>
      </div>

      <Separator className="my-0" />
      <div>
        <DataTable size={16} columns={columns} data={rowData} />
      </div>
    </>
  );
};

export default Users;