"use client";

import React, { Fragment, useState, useEffect, useRef } from "react";
import { useDispatch, useSelector } from "react-redux";
import Pusher from "pusher-js";
import { RootState } from "../../../store";
import {
  getTickets,
  repliesTickets,
  repliesTicketsId,
  addTickets,
  ticketNotification,
} from "../../../api/api";
import { toast } from "react-toastify";
import { FaPaperPlane } from "react-icons/fa";
import { unwrapResult } from "@reduxjs/toolkit";
import { Menu, Transition } from "@headlessui/react";
import { ChevronDownIcon } from "@heroicons/react/20/solid";
import { Formik, Form, Field, ErrorMessage } from "formik";
import * as Yup from "yup";

const TicketManagement: React.FC = () => {
  const dispatch = useDispatch<any>();
  const [selectedTicket, setSelectedTicket] = useState<number | null>(null);
  const [newReply, setNewReply] = useState("");
  const [showTicketForm, setShowTicketForm] = useState(false);
  const { ticketsData, ticketRepliesData } = useSelector(
    (state: RootState) => state.TicketsReducer
  );

  const chatContainerRef = useRef<HTMLDivElement>(null);
  const handleAddTicket = async (values: any) => {
    try {
      const payload: any = {
        listing_id: "",
        category: "general",
        subject: values.subject,
        message: values.description,
        priority: values.priority,
      };

      const resultAction = await dispatch(addTickets(payload));
      const response = unwrapResult(resultAction);

      if (response.success) {
        toast.success("Ticket created successfully!");
        setShowTicketForm(false);
        dispatch(getTickets());
      } else {
        toast.error(response.message || "Failed to create ticket.");
      }
    } catch {
      toast.error(
        "An error occurred while creating the ticket. Please try again."
      );
    }
  };

  const handelTicket = () => {
    setShowTicketForm(true);
  };

  const handleAddReply = async () => {
    if (!newReply.trim() || !selectedTicket) {
      alert("Please type a message before sending.");
      return;
    }

    try {
      const response = await dispatch(
        repliesTicketsId({
          id: selectedTicket,
          message: newReply,
        })
      );

      setNewReply(""); // Clear input field
      // Handle response
      if (response.payload.success) {
        if (response.payload.reply.message === "Reply sent successfully.") {
          dispatch(repliesTickets(selectedTicket)); // Fetch updated replies
        }
      }
    } catch {
      return null;
    }
  };

  const handleViewClick = (ticketId: number) => {
    setSelectedTicket(ticketId);
  };

  // inside your component
  const handleTicketClick = async (ticketId: number) => {
    try {
      handleViewClick(ticketId);

      // delay before dispatching getTickets
      setTimeout(async () => {
        try {
          await dispatch(getTickets()).unwrap(); // wait until API finishes
          dispatch(ticketNotification()); // fire notification
        } catch (error) {
          console.error("Error dispatching actions:", error);
        }
      }, 100);
    } catch (error) {
      console.error("Error handling ticket click:", error);
    }
  };
  useEffect(() => {
    dispatch(getTickets());
  }, [dispatch]);

  useEffect(() => {
    if (selectedTicket) {
      dispatch(repliesTickets(selectedTicket));
    }
  }, [dispatch, selectedTicket]);

  useEffect(() => {
    if (!selectedTicket) return;

    const appKey = process.env.NEXT_PUBLIC_PUSHER_APP_KEY!;
    const cluster = process.env.NEXT_PUBLIC_PUSHER_APP_CLUSTER!;
    let pusher = new Pusher(appKey, {
      cluster,
      forceTLS: true,
    });

    const reconnectPusher = () => {
      pusher.unsubscribe(`tickets.${selectedTicket}`);
      pusher.disconnect();
      pusher = new Pusher(appKey, { cluster, forceTLS: true });
      subscribeToPusherEvents();
    };

    const subscribeToPusherEvents = () => {
      const channel = pusher.subscribe(`tickets.${selectedTicket}`);
      channel.bind("App\\Events\\TicketReplySent", (data: any) => {
        console.log("New message received!", data);
        dispatch(repliesTickets(selectedTicket));
      });
    };

    subscribeToPusherEvents();

    pusher.connection.bind("disconnected", () => {
      console.warn("Pusher disconnected. Attempting to reconnect...");
      reconnectPusher();
    });

    // Cleanup on unmount or ticket change
    return () => {
      console.log("Cleaning up Pusher...");
      pusher.unsubscribe(`ticket.${selectedTicket}`);
      pusher.disconnect();
    };
  }, [selectedTicket, dispatch]);

  const ticketValidationSchema = Yup.object({
    priority: Yup.string().required("Priority is required"),
    subject: Yup.string().required("Subject is required"),
    description: Yup.string().required("Description is required"),
  });

  useEffect(() => {
    if (chatContainerRef.current) {
      chatContainerRef.current.scrollTop =
        chatContainerRef.current.scrollHeight;
    }
  }, [ticketRepliesData]);
  return (
    <div className=" max-w-full overflow-auto bg-[#F8F9F9] flex flex-col items-center">
      <div className="w-full bg-white shadow-md rounded-lg p-6 lg:overflow-auto">
        <div className="flex justify-between mb-6 flex-wrap">
          <h1 className="text-2xl font-bold w-full sm:w-auto xs:text-center xs:pb-4 md:p-0 text-black">
            Customer Support
          </h1>
          <button className="animation-custom-button" onClick={handelTicket}>
            Create Ticket
          </button>
        </div>
        <div></div>
        {showTicketForm && (
          <div className="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50 z-50">
            <div className="bg-white p-6 rounded-lg shadow-lg w-full max-w-lg relative">
              {/* Close Button */}
              <button
                className="absolute top-0 right-3 text-black font-normal cursor-pointer hover:text-gray-800 text-4xl p-0"
                onClick={() => setShowTicketForm(false)}
              >
                &times;
              </button>

              {/* Header */}
              <h2 className="text-xl font-semibold mb-4 text-center">
                Create New Ticket
              </h2>

              <Formik
                initialValues={{ priority: "", subject: "", description: "" }}
                validationSchema={ticketValidationSchema}
                onSubmit={(values, { resetForm }) => {
                  handleAddTicket(values);
                  resetForm();
                  setShowTicketForm(false);
                }}
              >
                {({ setFieldValue, values, touched, errors }) => (
                  <Form>
                    {/* Priority Dropdown */}
                    <div className="mb-4">
                      <Menu
                        as="div"
                        className="relative inline-block w-full text-left"
                      >
                        <div>
                          <Menu.Button className="inline-flex justify-between items-center w-full rounded-md bg-white px-4 py-2 border border-gray-300 text-sm text-gray-700 shadow-sm hover:bg-gray-50">
                            {values.priority || "Select Priority"}
                            <ChevronDownIcon className="ml-2 h-5 w-5 text-gray-500" />
                          </Menu.Button>
                        </div>
                        <Transition
                          as={Fragment}
                          enter="transition ease-out duration-100"
                          enterFrom="transform opacity-0 scale-95"
                          enterTo="transform opacity-100 scale-100"
                          leave="transition ease-in duration-75"
                          leaveFrom="transform opacity-100 scale-100"
                          leaveTo="transform opacity-0 scale-95"
                        >
                          <Menu.Items className="absolute z-10 mt-2 w-full rounded-md bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none overflow-hidden">
                            <div className="">
                              {["High", "Low"].map((level) => (
                                <Menu.Item key={level}>
                                  {({ active }) => (
                                    <button
                                      type="button"
                                      onClick={() =>
                                        setFieldValue("priority", level)
                                      }
                                      className={`${
                                        active
                                          ? "bg-navy text-white dark:bg-gray-600"
                                          : "text-gray-900 dark:text-white"
                                      } block w-full text-left px-4 py-3 text-sm cursor-pointer text-black rounded-none border-b border-gray-200`}
                                    >
                                      {level}
                                    </button>
                                  )}
                                </Menu.Item>
                              ))}
                            </div>
                          </Menu.Items>
                        </Transition>
                      </Menu>
                      {touched.priority && errors.priority && (
                        <div className="text-red-500 text-sm mt-1 text-center">
                          {errors.priority}
                        </div>
                      )}
                    </div>

                    {/* Subject Input */}
                    <div className="mb-3">
                      <Field
                        type="text"
                        name="subject"
                        placeholder="Subject"
                        className="w-full p-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 text-[#111827]"
                      />
                      <ErrorMessage
                        name="subject"
                        component="div"
                        className="text-red-500 text-sm mt-1 text-center"
                      />
                    </div>

                    {/* Description Textarea */}
                    <div className="mb-3">
                      <Field
                        as="textarea"
                        name="description"
                        placeholder="Enter Ticket Description"
                        className="w-full p-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 text-[#111827]"
                      />
                      <ErrorMessage
                        name="description"
                        component="div"
                        className="text-red-500 text-sm mt-1 text-center"
                      />
                    </div>

                    {/* Submit Button */}
                    <button
                      type="submit"
                      className="bg-navy text-white px-4 py-2 rounded-md w-full"
                    >
                      Submit Ticket
                    </button>
                  </Form>
                )}
              </Formik>
            </div>
          </div>
        )}
        <div>
          {!selectedTicket ? (
            <>
              <div>
                <h2 className="text-xl text-center font-semibold mb-4 text-black ">
                  All Tickets
                </h2>
              </div>
              <div className="mt-4 bg-white overflow-hidden">
                <div className="overflow-y-auto max-h-96 mt-5 mb-10">
                  <table className="w-full table-auto border-collapse border border-gray-200">
                    <thead className="bg-white">
                      <tr className="font-system text-[#000000] text-[1rem] font-medium text-left bg-gray-300">
                        <th className=" py-2 text-left px-4">Sr.No</th>
                        <th className=" py-2 text-left px-4">From</th>
                        <th className=" py-2 text-left px-4 text-nowrap">
                          Auction Title
                        </th>
                        <th className=" py-2 text-left px-4">Subject</th>
                        <th className=" py-2 text-left px-4">Category</th>
                        <th className=" py-2 text-left px-4">Priority</th>
                        <th className=" py-2 text-left px-4">Status</th>
                        <th className=" py-2 text-left px-4">Actions</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-200">
                      {ticketsData?.data?.tickets?.length > 0 ? (
                        ticketsData?.data?.tickets
                          ?.slice()
                          .reverse()
                          .map((ticket: any, index: number) => (
                            <tr
                              key={ticket.id}
                              className="text-start text-[#6B7280] text-[14px] hover:bg-gray-50"
                            >
                              <td className="px-4 py-2 text-center">
                                {index + 1}
                              </td>
                              <td className="px-4 py-2">{ticket.user.name}</td>
                              <td
                                className={`px-4 py-2 capitalize ${
                                  ticket.listing?.product_name
                                    ? "text-left"
                                    : "text-center"
                                }`}
                              >
                                {ticket.listing?.product_name || "-"}
                              </td>
                              <td className="px-4 py-2">{ticket.subject}</td>
                              <td className="px-4 py-2 capitalize">
                                {ticket.category}
                              </td>
                              <td className="px-4 py-2 capitalize">
                                {ticket.priority}
                              </td>
                              <td className="py-2 px-4 capitalize">
                                <span
                                  className={`px-2 py-1 text-sm rounded ${
                                    ticket.status === "closed"
                                      ? "bg-green-200 text-green-800"
                                      : "bg-red-200 text-red-800"
                                  }`}
                                >
                                  {ticket.status || "Open"}
                                </span>
                              </td>
                              <td className="py-2 px-4">
                                <div className="flex items-center justify-center gap-2 relative">
                                  <button
                                    className="track-custom-button relative overflow-visible"
                                    onClick={() => handleTicketClick(ticket.id)}
                                  >
                                    View
                                  </button>

                                  {ticket?.unread_count > 0 && (
                                    <span className="absolute -top-2 right-[10%] bg-yellow-400 text-black text-xs font-bold rounded-full h-5 w-5 flex items-center justify-center shadow z-50">
                                      {ticket.unread_count}
                                    </span>
                                  )}
                                </div>
                              </td>
                            </tr>
                          ))
                      ) : (
                        <tr>
                          <td
                            colSpan={8}
                            className="py-4 text-center text-lg text-gray-500"
                          >
                            No Tickets found.
                          </td>
                        </tr>
                      )}
                    </tbody>
                  </table>
                </div>
              </div>
            </>
          ) : (
            <>
              <div className="flex items-center justify-between mb-6">
                <button
                  className="text-gray-600 hover:text-gray-800 flex gap-2"
                  onClick={() => setSelectedTicket(null)}
                >
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    fill="none"
                    viewBox="0 0 24 24"
                    strokeWidth={1.5}
                    stroke="currentColor"
                    className="size-6"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      d="M10.5 19.5 3 12m0 0 7.5-7.5M3 12h18"
                    />
                  </svg>{" "}
                  Back to Tickets
                </button>
              </div>
              <hr />

              <div className="space-y-4 mb-6">
                <div
                  className="bg-gray-50 p-4 rounded-md h-64 overflow-y-auto flex flex-col"
                  ref={chatContainerRef}
                >
                  {/* Show original user message (ticket message) */}
                  {ticketRepliesData?.replies?.ticket?.message && (
                    <div className="p-3 rounded-md max-w-[70%] mt-3 bg-gray-100 self-end ml-auto text-right">
                      <p>{ticketRepliesData?.replies?.ticket?.message}</p>
                      <p className="text-xs text-gray-400 mt-1">
                        {new Date(
                          ticketRepliesData.replies.ticket.created_at
                        ).toLocaleString()}
                      </p>
                    </div>
                  )}

                  {/* Show replies */}
                  {/* {ticketRepliesData.replies?.ticket?.replies?.length ? (
                    ticketRepliesData.replies.ticket.replies.map(
                      (reply: any, idx: number) => (
                        <div
                          key={idx}
                          className={`p-3 rounded-md max-w-[70%] mt-3 ${
                            reply.is_admin
                              ? "bg-gray-100 self-start mr-auto text-left"
                              : "bg-gray-100 self-end ml-auto text-right"
                          }`}
                        >
                          <p>{reply.message}</p>
                          <p className="text-xs text-gray-400 mt-1">
                            {new Date(reply.created_at).toLocaleString()}
                          </p>
                        </div>
                      )
                    )
                  ) : (
                    <p className="text-center">No replies yet.</p>
                  )} */}
                  <>
                    {ticketRepliesData.replies?.ticket?.replies?.map(
                      (reply: any, idx: number) => (
                        <div
                          key={idx}
                          className={`p-3 rounded-md max-w-[70%] mt-3 ${
                            reply.is_admin
                              ? "bg-gray-100 self-start mr-auto text-left"
                              : "bg-gray-100 self-end ml-auto text-right"
                          }`}
                        >
                          <p>{reply.message}</p>
                          <p className="text-xs text-gray-400 mt-1">
                            {new Date(reply.created_at).toLocaleString()}
                          </p>
                        </div>
                      )
                    )}

                    {/* Show message only if no admin replies */}
                    {!ticketRepliesData.replies?.ticket?.replies?.some(
                      (reply: any) => reply.is_admin === 1
                    ) && (
                      <p className="text-center mt-4 text-gray-500">
                        No replies yet
                      </p>
                    )}
                  </>
                </div>

                <hr />
              </div>

              <div className="flex items-center">
                {ticketRepliesData?.replies?.ticket?.status === "closed" ? (
                  <>
                    <div className="text-center w-full text-black font-bold">
                      This ticket is closed.
                    </div>
                  </>
                ) : (
                  <>
                    <input
                      type="text"
                      placeholder="Type your reply..."
                      className="flex-grow bg-gray-100 border border-gray-300 rounded-lg p-2 mr-2 focus:outline-none focus:ring-2 focus:ring-blue-400"
                      value={newReply}
                      onKeyDown={(e) => {
                        if (e.key === "Enter") {
                          handleAddReply();
                        }
                      }}
                      onChange={(e) => setNewReply(e.target.value)}
                    />

                    <button
                      className="bg-blue-500 text-white rounded-full p-2 hover:bg-blue-600"
                      onClick={handleAddReply}
                    >
                      <FaPaperPlane size={20} />
                    </button>
                  </>
                )}
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
};

export default TicketManagement;
