"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, FileText, Pencil, PlusCircle, SearchIcon } from 'lucide-react'

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

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 { getNews } from "@/lib/features/admin/news/service";
import { NewsProps } from "@/lib/features/admin/news/type";
import { NewsFormDialog } from "./component/news-form-popover";
import { ViewNewsDialog } from "./component/view-news-popover";
import { UpdateNewsFormDialog } from "./component/update-news-form";

const News = () => {


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


  /////////////////create course modal
  const [isAddModalOpen, setAddModalOpen] = useState(false);

  const openAddModal = () => {
    setAddModalOpen(true);
  };

  const closeAddModal = () => {
    setAddModalOpen(false);
  };


  // news
  const { data, isLoading, error, refetch } = useQuery({
    queryKey: ["news-list"],
    queryFn: () => getNews(),
  });


  // handle refresh
  const handleRefresh = () => {
    refetch();
  };

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

  //console.log(data?.data)

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

  const courses: NewsProps[] = data?.data || [];

  //columns
  const columns: ColumnDef<NewsProps>[] = [
    {
      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: "image",
      header: () => <div className="text-left table-size">Photo</div>,
      cell: ({ row }) => {
        return (
          <div className="text-left font-normal table-size" onClick={() => openViewModal(row?.original?.id)}>
            <Image
              src={`${row.getValue("image")}`}
              alt={row?.original?.title}
              width={200}
              height={200}
              className="rounded-2xl shadow-2xl"
            />
          </div>
        );
      },
    },

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


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

    {
      accessorKey: "likes",
      header: () => <div className="text-left table-size">Likes</div>,
      cell: ({ row }) => {
        return (
          <div className="text-left font-normal table-size" onClick={() => openViewModal(row?.original?.id)}>
            {row.getValue("likes")}
          </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")}
          </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>


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



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

  return (
    <>


      {/**************** Add course modal */}
      <Modal isOpen={isAddModalOpen} onClose={closeAddModal} size="lg" >
        <NewsFormDialog onCloseModal={closeAddModal} refreshNow={handleRefresh} />
      </Modal>

      {/**************** news details modal ******/}
      <Modal isOpen={isViewModalOpen} onClose={closeViewModal} size="lg" >
        <ViewNewsDialog dataId={Number(selectedId)} />
      </Modal>

      {/**************** update news  modal ******/}
      <Modal isOpen={isUpdateModalOpen} onClose={closeUpdateModal} size="lg" >
        <UpdateNewsFormDialog dataId={Number(selectedId)} onCloseModal={closeUpdateModal} refreshNow={handleRefresh} />
      </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">
              <FileText />
              News
            </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={courses} />
      </div>
    </>
  );
};

export default News;