"use client";

import React, { useState, useMemo } from "react";
import { Typography, Dropdown, Button, Modal } from "antd";
import {
  PlusOutlined,
  PrinterOutlined,
  EditOutlined,
  DeleteOutlined,
  SaveOutlined,
  SendOutlined,
  CopyOutlined,
  FilePdfOutlined,
  ArrowLeftOutlined,
  EllipsisOutlined,
  FileExcelFilled,
  FileExcelOutlined,
  FileAddTwoTone,
  FileOutlined,
} from "@ant-design/icons";
import { usePathname, useRouter } from "next/navigation";
import InputItem from "./FormItems";



export default function PageHead({
  title,
  page,
  dropDownItems: initialDropDownItems,
  filter,
}) {
  const pathname = usePathname();
  const router = useRouter();
  const [printModalVisible, setPrintModalVisible] = useState(false);



  const segments = pathname.split("/").filter(Boolean);
  const lastSegment = segments[segments.length - 1];
  const titleFinal = title || lastSegment;

  const iconMap = {
    "Add new": <PlusOutlined />,
    Print: <PrinterOutlined />,
    Edit: <EditOutlined />,
    Delete: <DeleteOutlined />,
    Duplicate: <CopyOutlined />,
    "Download PDF": <FilePdfOutlined />,
      "Download Excel": <FileExcelOutlined />,
        "Download CSV": <FileOutlined />,
    Send: <SendOutlined />,
    Save: <SaveOutlined />,
  };

  // Memoized print item
  const printItem = useMemo(() => {
    return (initialDropDownItems || []).find((item) => item.label === "Print");
  }, [initialDropDownItems]);

  // Memoized dropdown items with action override for Print
  const dropDownItems = useMemo(() => {
    return (initialDropDownItems || []).map((item) => {
      if (item.label === "Print") {
        return {
          ...item,
          action: () => {
            if (item.component) {
              setPrintModalVisible(true);
            } else if (item.url) {
              router.push(item.url);
            } else {
              window.print();
            }
          },
        };
      }
      return item;
    });
  }, [initialDropDownItems, router]);

  // Memoized menu items for Ant Dropdown
  const menuItems = useMemo(() => {
    return dropDownItems.map((item, index) => ({
      key: String(index + 1),
      label: item.label,
      icon: iconMap[item.label] || null,
    }));
  }, [dropDownItems]);

  const handleMenuClick = ({ key, domEvent }) => {
    domEvent.preventDefault();
    const item = dropDownItems?.[parseInt(key, 10) - 1];
    if (!item) return;

    if (item.action && typeof item.action === "function") {
      item.action();
    } else if (item.url) {
      router.push(item.url);
    } else {
      console.warn(`No action or URL defined for "${item.label}"`);
    }
  };




  return (
    <>


      <div className="bg-white py-3 border-y border-gray-100">
        <div className="container">
          <div className="flex justify-between items-center">
            <div className="flex items-center gap-3">
              {page !== "dashboard" && (
                <Button
                  type="text"
                  onClick={() => window.history.back()}
                  icon={<ArrowLeftOutlined />}
                  className="md:hidden"
                />
              )}
              <Typography.Title
                level={5}
                className="!mb-0 !text-base capitalize"
              >
                {titleFinal}
              </Typography.Title>
            </div>

            {menuItems.length > 0 && (
              <Dropdown
                menu={{
                  items: menuItems,
                  onClick: handleMenuClick,
                }}
                trigger={["click"]}
                placement="bottomRight"
              >
                <Button
                  type="text"
                  icon={<EllipsisOutlined className="text-lg text-gray-500" />}
                />
              </Dropdown>
            )}
          </div>
        </div>
        {filter && (
          <div className="border-t border-gray-100 pt-3 mt-3">
            <div className="container">
              <Filter />
            </div>
          </div>
        )}
      </div>

      <Modal
        title={printItem?.modaltitle || "Print Document"}
        open={printModalVisible}
        onCancel={() => setPrintModalVisible(false)}
        footer={null}
        width="80%"
      >
        {printItem?.printData}
        {printItem?.component}
      </Modal>
    </>
  );
}
