"use client";

import React from "react";
import Image from "next/image";
import moment from "moment";
import type { useCalendar } from "./useCalendar";
import { clickable } from "@/lib/a11y";

const asset = (path: string) => `/assets/${path}`;

/**
 * The panel beside the grid: the month-at-a-glance picker and the day's
 * entries grouped by what they are.
 *
 * It is hidden rather than unmounted on narrow screens, so the mini calendar
 * keeps the month the user last paged to.
 */
export default function CalendarSidebar({
  screen,
}: {
  screen: ReturnType<typeof useCalendar>;
}) {
  const {
    isRTL,
    miniCalendarDate,
    miniCalendarDates,
    sidebarOpen,
    groupedTasks,
    navigateMiniCalendar,
    handleMiniCalendarDayClick,
  } = screen;

  return (
    <div
      className={`${
        sidebarOpen ? "block" : "hidden md:block"
      } w-full md:w-[250px] lg:w-[250px] xl:w-[300px] 2xl:w-[300px] bg-indigo-900 text-white overflow-y-auto flex-shrink-0`}
    >
      <div className="p-4">
        {/* Header */}
        <div className="flex justify-between items-center mb-6">
          <div className="flex space-x-1">
            <div className="w-3 h-3 rounded-full bg-[#5271FF]" />
            <div className="w-3 h-3 rounded-full bg-[#D9EF61]" />
            <div className="w-3 h-3 rounded-full bg-[#70B4C2]" />
          </div>
          {/*
            No handler. Verified within this app only: `calnderplus.svg` is
            referenced from this one line and nothing wires an `onClick` to it,
            so today it is inert and is marked `alt=""` accordingly.
            Whether it is *meant* to be inert is a product question this review
            cannot answer from the Next.js app or the backend, and the earlier
            note here appealed to the legacy React app, which is out of scope.
            Recorded as an open question rather than an established decision.
          */}
          <Image
            src={asset("calander/calnderplus.svg")}
            alt=""
            width={20}
            height={20}
            unoptimized
          />
        </div>

        {/* Mini calendar */}
        <div className="mb-6">
          <div className="flex justify-between items-center text-lg mb-2">
            <div className="text-xl md:text-2xl">
              <span className="text-white">
                {moment(miniCalendarDate).format("MMMM")}
              </span>{" "}
              <span className="text-[#D9EF61]">
                {moment(miniCalendarDate).format("YYYY")}
              </span>
            </div>
            <div className="flex space-x-3">
              <button
                onClick={() => navigateMiniCalendar("prev")}
                className="text-gray-400 hover:text-white"
              >
                <Image
                  src={asset(
                    isRTL
                      ? "calander/rightarrow.svg"
                      : "calander/leftarrow.svg"
                  )}
                  alt="Previous"
                  width={16}
                  height={16}
                />
              </button>
              <button
                onClick={() => navigateMiniCalendar("next")}
                className="text-gray-400 hover:text-white"
              >
                <Image
                  src={asset(
                    isRTL
                      ? "calander/leftarrow.svg"
                      : "calander/rightarrow.svg"
                  )}
                  alt="Next"
                  width={16}
                  height={16}
                />
              </button>
            </div>
          </div>
          <div className="grid grid-cols-7 gap-1 text-center text-xs mb-2">
            {["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"].map(
              (day, i) => (
                <div key={i} className="text-[#71717A] py-1 text-[10px]">
                  {day}
                </div>
              )
            )}
            {miniCalendarDates.map((dateObj, i) => (
              <div
                key={i}
                className={`relative py-1 flex flex-col items-center ${
                  !dateObj.isCurrentMonth ? "text-gray-600" : ""
                } ${
                  dateObj.date
                    ? "cursor-pointer hover:bg-indigo-800 rounded"
                    : ""
                }`}
                /* A day cell jumps the main view to that date — keyboard
                   users had no way to do it. Spread only for a real day: the
                   condition is `handleMiniCalendarDayClick`'s own guard, so a
                   tab stop exists exactly where a press does something: the
                   blanks have no `date`, and the adjacent-month days it shows
                   greyed are not navigable either. */
                {...(dateObj.date && dateObj.isCurrentMonth
                  ? clickable(() => handleMiniCalendarDayClick(dateObj))
                  : {})}
              >
                {dateObj.day && (
                  <>
                    <div
                      className={`w-7 h-7 flex items-center justify-center rounded-full text-xs font-semibold ${
                        dateObj.isToday ? "bg-[#5271FF] h-7 w-7" : ""
                      }`}
                    >
                      {dateObj.day}
                    </div>
                    {dateObj.events && dateObj.events.length > 0 && (
                      <div className="flex space-x-0.5 mt-1">
                        {dateObj.events.slice(0, 3).map((event, idx) => (
                          <div
                            key={idx}
                            className="w-1 h-1 rounded-full"
                            style={{ backgroundColor: event.color }}
                          />
                        ))}
                      </div>
                    )}
                  </>
                )}
              </div>
            ))}
          </div>
        </div>

        {/* Tasks */}
        <div>
          {Object.entries(groupedTasks).map(([category, tasks], idx) => (
            <div key={idx} className="mb-4">
              <div
                className={`text-xs mb-2 font-bold text-[13px] pb-2 ${
                  category === "TODAY" ? "text-[#5271FF]" : "text-white"
                }`}
              >
                {category}
                {tasks[0].date && (
                  <span className="font-normal"> • {tasks[0].date}</span>
                )}
              </div>
              {tasks.map((task, taskIdx) => (
                <div key={taskIdx} className="mb-2 text-xs">
                  <div className="flex items-center">
                    <div className="w-3 h-3 rounded-full bg-blue-400 mr-2" />
                    <div className="text-[#A1A1AA] font-semibold">
                      {task.time}
                    </div>
                  </div>
                  <div className="ml-5 text-xs">{task.title}</div>
                </div>
              ))}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
