/* 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 { Eye, ListChecks, SearchIcon } from 'lucide-react'

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

import { DotsHorizontalIcon } from "@radix-ui/react-icons";
import DataTable from "@/components/Table";
import Modal from "@/components/modal";
import Loading from "@/app/(dashoard)/components/loading";
import { ErrorMessage } from "@/components/ui/error-message";

import Image from "next/image"
import { ViewMatchResultDialog } from "./component/view-match-result-popover";
import { getMatchResults } from "@/lib/features/admin/match-result/service";
import { MatchResultProps } from "@/lib/features/admin/match-result/type";

const MatchResultPage = () => {


  // 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);
  };




  // match results
  const { data, isLoading, error } = useQuery({
    queryKey: ["match-result-list"],
    queryFn: () => getMatchResults(),
  });


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


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

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

  //columns
  const columns: ColumnDef<MatchResultProps>[] = [
    {
      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: "home",
      header: () => <div className="text-left table-size">Home</div>,
      cell: ({ row }) => {
        return (
          <div className="text-left font-normal table-size flex gap-2" onClick={() => openViewModal(row?.original?.id)}>
            <Image
              src={`${row?.original?.homeImage}`}
              alt={row?.original?.home}
              width={40}
              height={40}
              className="rounded-2xl shadow-2xl"
            />
            <span className="mt-4">{row.getValue("home")}</span>

          </div>
        );
      },
    },


    {
      accessorKey: "away",
      header: () => <div className="text-left table-size">Away</div>,
      cell: ({ row }) => {
        return (
          <div className="text-left font-normal table-size flex gap-2" onClick={() => openViewModal(row?.original?.id)}>
            <Image
              src={`${row?.original?.awayImage}`}
              alt={row?.original?.away}
              width={40}
              height={40}
              className="rounded-2xl shadow-2xl"
            />
            <span className="mt-4">{row.getValue("away")}</span>
          </div>
        );
      },
    },


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


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

    {
      accessorKey: "receiverGoals",
      header: () => <div className="text-left table-size text-blue-500">Result</div>,
      cell: ({ row }) => {
        return (
          <div className="text-left font-normal table-size" onClick={() => openViewModal(row?.original?.id)}>
            <b className="text-md text-blue-500">
              {row.getValue("receiverGoals") + " - " + row?.original?.visitorGoals}
            </b>
          </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?.id)}>
                <Eye />
                View
              </DropdownMenuItem>





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

  return (
    <>

      {/**************** match result details modal ******/}
      <Modal isOpen={isViewModalOpen} onClose={closeViewModal} size="md">
        <ViewMatchResultDialog dataId={Number(selectedId)} />
      </Modal>



      <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">
              <ListChecks />
              Match results
            </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" type="button" onClick={() => openAddModal()}>
            <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 MatchResultPage;