/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";

import { useState } from "react";
import { router, usePage } from "@inertiajs/react";

import DashboardLayout from "@/layouts/dashboard";
import Pagination from "@/components/dashboard/pagination";
import { usePaginatedData } from "@/hooks/usePaginatedData";

import DashboardHeader from "@/components/shared/DashPageHeader";
import DashStatsCard from "@/components/shared/DashStatsCard";
import NewDataTable, { Action, Column } from "@/components/shared/NewDataTable";
import MemberSearch from "@/components/members/member-search";
import ConfirmModal from "@/components/modals/confirmation-modal";
import AppointmentDetailsModal from "@/components/modals/appointment-details-modal";
import PageIntro from "@/components/dashboard/page-intro";

import AppointmentToggleCard from "@/components/dashboard/appointment-toggle-card";
import AssignAppointmentModal from "@/components/modals/assign-appointment-modal";
import RescheduleAppointmentModal from "@/components/modals/reschedule-appointment-modal";

//Analytics 
import AppointmentTrendsChart from "@/components/dashboard/appointment-trend-chart";
import AppointmentDemographics from "@/components/dashboard/appointment-demographies-chart";

import DailyBookingLimitCard from "@/components/dashboard/appointment-booking-limit-card";

import styles from "./appointments.module.scss";

import {
  MdPendingActions,
  MdIncompleteCircle,
  MdOutlineScheduleSend,
  MdFreeCancellation,
} from "react-icons/md";
import { GrNotes } from "react-icons/gr";
import { formatDateReadable } from "@/lib/utils";

/* ================= CALENDAR ================= */
const days = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"];

const getDays = (month: number, year: number) => {
  const firstDay = new Date(year, month, 1).getDay();
  const totalDays = new Date(year, month + 1, 0).getDate();
  const blanks = Array(firstDay).fill(null);
  const daysArr = Array.from({ length: totalDays }, (_, i) => i + 1);
  return [...blanks, ...daysArr];
};

const CalendarUI = ({ month, year, setMonth, setYear, handleSelect }: any) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0);

  const currentMonth = today.getMonth();
  const currentYear = today.getFullYear();

  // 🔥 Check if current view is THIS month
  const isCurrentMonth = month === currentMonth && year === currentYear;

  // 🔥 HANDLE PREV (BLOCK if current month)
  const handlePrev = () => {
    if (isCurrentMonth) return;

    if (month === 0) {
      setMonth(11);
      setYear((prev: number) => prev - 1);
    } else {
      setMonth(month - 1);
    }
  };

  // 🔥 HANDLE NEXT (normal)
  const handleNext = () => {
    if (month === 11) {
      setMonth(0);
      setYear((prev: number) => prev + 1);
    } else {
      setMonth(month + 1);
    }
  };

  return (
    <div className={styles.calendar}>
      {/* HEADER */}
      <div className={styles.calendarHeader}>
        <button
          onClick={handlePrev}
          disabled={isCurrentMonth}
          className={isCurrentMonth ? styles.disabledNav : ""}
        >
          ‹
        </button>

        <h4>
          {new Date(year, month).toLocaleString("default", {
            month: "long",
          })}{" "}
          {year}
        </h4>

        <button onClick={handleNext}>›</button>
      </div>

      {/* GRID */}
      <div className={styles.calendarGrid}>
        {days.map((d) => (
          <span key={d}>{d}</span>
        ))}

        {getDays(month, year).map((d, i) => {
          if (!d) return <button key={i} disabled />;

          const date = new Date(year, month, d);
          date.setHours(0, 0, 0, 0);

          const isPast = date < today;

          return (
            <button
              key={i}
              disabled={isPast}
              onClick={() => !isPast && handleSelect(d)}
              className={isPast ? styles.disabledDay : ""}
            >
              {d}
            </button>
          );
        })}
      </div>
    </div>
  );
};

/* ================= PAGE ================= */

const DashboardAppointments = ({ allAppointments, is_accepting_appointments, analyticsStats, daily_booking_limit, today_bookings }: any) => {
  const { props }: any = usePage();

  // console.log("All analytics", allAppointments)

  const backendAppointments = allAppointments.data || [];

  /* ================= STATE ================= */
  const [loading, setLoading] = useState(false);
  const [confirmToggle, setConfirmToggle] = useState(false);

  const [detailsModal, setDetailsModal] = useState(false);
  const [assignModal, setAssignModal] = useState(false);
  const [selectedAppointment, setSelectedAppointment] = useState<any>(null);

  const [bulkMode, setBulkMode] = useState(false);
  const [selectedIds, setSelectedIds] = useState<number[]>([]);

  const today = new Date();
  const [month, setMonth] = useState(today.getMonth());
  const [year, setYear] = useState(today.getFullYear());
  const [selectedDate, setSelectedDate] = useState<number | null>(null);
  const [showCalendar, setShowCalendar] = useState(false);

  const [submitting, setSubmitting] = useState(false);
  const [isReschedule, setIsReschedule] = useState(false);

  const [rescheduleModal, setRescheduleModal] = useState(false);

  const [confirmComplete, setConfirmComplete] = useState(false);

  const [targetAppointment, setTargetAppointment] = useState<any>(null);


  const [form, setForm] = useState({
    hour: "07",
    minute: "00",
    period: "AM",
    reason: "",
  });

  const handleChange = (key: string, value: string) => {
    setForm((prev) => ({ ...prev, [key]: value }));
  };

  /* ================= FILTER ================= */
  const [searchTerm, setSearchTerm] = useState(props.filters?.search || "");

  const [localFilters, setLocalFilters] = useState({
    status: props.filters?.status || "",
    sort: props.filters?.sort || "latest",
  });

  const { handlePageChange } = usePaginatedData(10);

  const applyFilters = (newFilters = {}) => {
    const updated = { ...localFilters, ...newFilters };
    setLocalFilters(updated);
    setLoading(true);

    router.get(route("dashboard.appointments.index"), updated, {
      preserveState: true,
      replace: true,
      onSuccess: () => setTimeout(() => setLoading(false), 800),
    });
  };

  const clearFilters = () => {
    setSearchTerm("");
    setLocalFilters({ status: "", sort: "latest" });

    router.get(route("dashboard.appointments.index"), {}, {
      preserveState: true,
      replace: true,
    });
  };

  /* ================= DATA ================= */
  const appointments = backendAppointments?.map((a: any) => ({
    id: a.id,
    full_name: a.name,
    // email: clipEmail(a.email, 10),
    date: formatDateReadable(a.created_at),
    status: a.status,
    raw: a,
  }));

 /* ================= ASSIGN ================= */
  const handleAssign = () => {
    // 🔒 prevent submit if no date selected
    if (!selectedDate) return;

    const assigned_date = `${year}-${String(month + 1).padStart(
      2,
      "0"
    )}-${String(selectedDate).padStart(2, "0")}`;

    let hour = parseInt(form.hour);
    if (form.period === "PM" && hour !== 12) hour += 12;
    if (form.period === "AM" && hour === 12) hour = 0;

    const assigned_time = `${String(hour).padStart(2, "0")}:${form.minute}:00`;

    const payload = {
      assigned_date,
      assigned_time,
      venue: "office",
    };

    // 🔥 COMMON OPTIONS (clean + reusable)
    const options = {
      preserveScroll: true,
      preserveState: true,

      onStart: () => setSubmitting(true),
      onFinish: () => setSubmitting(false),

      onError: () => {
        // modal stays open automatically
      },

      onSuccess: (page: any) => {
        const hasErrors =
          page.props.errors &&
          Object.keys(page.props.errors).length > 0;

        if (!hasErrors) {
          setAssignModal(false);

          setSelectedDate(null);
          setSelectedAppointment(null);
          setSelectedIds([]);
          setBulkMode(false);

          setForm({
            hour: "10",
            minute: "00",
            period: "AM",
            reason: ""
          });
        }
      },
    };

    // ================= SINGLE ASSIGN =================
    if (selectedAppointment) {
      router.post(
        route(
          "dashboard.appointments.assign",
          selectedAppointment.id
        ),
        payload,
        options
      );
    }

    // ================= BULK ASSIGN =================
    else if (selectedIds.length > 0) {
      router.post(
        route("dashboard.appointments.bulkAssign"),
        {
          ...payload,
          appointments: selectedIds, 
        },
        options
      );
    }
  };

  /* ================= RESCHEDULE ================= */
  const handleReschedule = () => {
  if (!selectedDate || !selectedAppointment) return;

  const assigned_date = `${year}-${String(month + 1).padStart(
    2,
    "0"
  )}-${String(selectedDate).padStart(2, "0")}`;

  let hour = parseInt(form.hour);
  if (form.period === "PM" && hour !== 12) hour += 12;
  if (form.period === "AM" && hour === 12) hour = 0;

  const assigned_time = `${String(hour).padStart(2, "0")}:${form.minute}:00`;

  const payload = {
    assigned_date,
    assigned_time,
    reason: form.reason || "",
  };

  router.post(
    route("dashboard.appointments.reschedule", selectedAppointment.id),
    payload,
    {
      preserveScroll: true,
      preserveState: true,

      onStart: () => setSubmitting(true),
      onFinish: () => setSubmitting(false),

      onSuccess: (page: any) => {
        const hasErrors =
          page.props.errors &&
          Object.keys(page.props.errors).length > 0;

        if (!hasErrors) {
          setRescheduleModal(false);
          setSelectedAppointment(null);
          setSelectedDate(null);

          setForm({
            hour: "10",
            minute: "00",
            period: "AM",
            reason: ""
          });
        }
      },
    }
  );
};

/* ================= MARK AS COMPLETE ================= */
const handleComplete = () => {
  if (!targetAppointment) return;

  router.post(
    route("dashboard.appointments.complete", targetAppointment.id),
    {},
    {
      preserveScroll: true,

      onSuccess: () => {
        setConfirmComplete(false);
        setTargetAppointment(null);
      },
    }
  );
};

/* ================= STATS ================= */
  const stats = [
    {
      title: "Total",
      value: backendAppointments.length,
      icon: <MdPendingActions />,
    },
    {
      title: "Completed",
      value: backendAppointments.filter((a: any) => a.status === "completed").length,
      icon: <GrNotes />,
    },
    {
      title: "Assigned",
      value: backendAppointments.filter((a: any) => a.status === "assigned").length,
      icon: <MdIncompleteCircle />,
    },
    {
      title: "Cancelled",
      value: backendAppointments.filter((a: any) => a.status === "cancelled").length,
      icon: <MdFreeCancellation />,
    },
    {
      title: "Rescheduled",
      value: backendAppointments.filter((a: any) => a.status === "rescheduled").length,
      icon: <MdOutlineScheduleSend />,
    },
  ];

  /* ================= TABLE ================= */
  const columns: Column<any>[] = [
     {
      header: "",
      accessor: (row) => {
        const checked = selectedIds.includes(row.id);

        return (
          <label className={styles.checkbox}>
            <input
              type="checkbox"
              checked={checked}
              onChange={() => {
                if (checked) {
                  setSelectedIds((prev) =>
                    prev.filter((id) => id !== row.id)
                  );
                } else {
                  setSelectedIds((prev) => [...prev, row.id]);
                }
              }}
            />
            <span className={styles.checkmark} />
          </label>
        );
      },
    },
    { header: "Full Name", accessor: "full_name" },
    // { header: "Email Address", accessor: "email" },
    { header: "Booked Date", accessor: "date" },
    { header: "Status", accessor: "status" },
  ];

   const actions: Action<any>[] = [
  {
    label: "View",
    variant: "view",
    onClick: (row) => {
      setSelectedAppointment(row.raw);
      setDetailsModal(true);
    },
  },

  {
    label: "Assign",
    variant: "update",
    onClick: (row) => {
      // Prevent assigning already processed
      if (["assigned", "completed", "cancelled"].includes(row.raw.status)) return;

      setSelectedAppointment(row.raw);
      setSelectedIds([]);
      setBulkMode(false);
      setAssignModal(true);
    },
  },

  {
    label: "Reschedule",
    variant: "update",
    onClick: (row) => {
      // Only allow reschedule if already assigned
      if (row.raw.status !== "assigned") return;

      setSelectedAppointment(row.raw);
      setSelectedIds([]);
      setBulkMode(false);

      setIsReschedule(true);
      setRescheduleModal(true); 
    },
  },

  {
    label: "Mark Completed",
    onClick: (row) => {
      if (row.raw.status === "pending") return;

      setTargetAppointment(row.raw); 
      setConfirmComplete(true);   
    },
  },
];

  /* ================= RENDER ================= */

  return (
    <>
      {/* MODALS */}
      {detailsModal && selectedAppointment && (
        <AppointmentDetailsModal
          appointment={selectedAppointment}
          onClose={() => setDetailsModal(false)}
        />
      )}

      <AssignAppointmentModal
        isOpen={assignModal}
        onClose={() => setAssignModal(false)}
        onAssign={handleAssign}
        month={month}
        year={year}
        setMonth={setMonth}
        setYear={setYear}
        selectedDate={selectedDate}
        setSelectedDate={setSelectedDate}
        showCalendar={showCalendar}
        setShowCalendar={setShowCalendar}
        form={form}
        handleChange={handleChange}
        CalendarUI={CalendarUI}
      />

      {rescheduleModal && (
        <RescheduleAppointmentModal
          isOpen={rescheduleModal}
          onClose={() => {
            setRescheduleModal(false);
            setIsReschedule(false);
          }}
          appointment={selectedAppointment}
          onSubmit={handleReschedule}
          month={month}
          year={year}
          setMonth={setMonth}
          setYear={setYear}
          selectedDate={selectedDate}
          setSelectedDate={setSelectedDate}
          showCalendar={showCalendar}
          setShowCalendar={setShowCalendar}
          form={form}
          handleChange={handleChange}
          CalendarUI={CalendarUI}
        />
      )}

      {confirmComplete && (
        <ConfirmModal
          isOpen
          title="Mark as Completed"
          message="Are you sure you want to mark this appointment as completed?"
          onConfirm={handleComplete}
          onCancel={() => {
            setConfirmComplete(false);
            setTargetAppointment(null);
          }}
        />
      )}

      {confirmToggle && (
        <ConfirmModal
          isOpen
          title="Confirm Action"
          message={
            is_accepting_appointments
              ? "Stop accepting appointments?"
              : "Start accepting appointments?"
          }
          onConfirm={() => {
            router.post(route("dashboard.appointments.toggleBooking"));
            setConfirmToggle(false);
          }}
          onCancel={() => setConfirmToggle(false)}
        />
      )}

      {/* PAGE */}
      <div className={styles.appointments}>
        <DashboardHeader
          title="Manage Appointments"
          description="View & manage all appointments seamlessly"
        />

        <div className={styles.content}>
          {/* TOGGLE CARD */}
          <AppointmentToggleCard
            isActive={is_accepting_appointments}
            onToggle={() => setConfirmToggle(true)}
          />

           <DailyBookingLimitCard
              limit={ daily_booking_limit || 10}
              currentCount={ today_bookings || 0}
            />

          {/* STATS */}
          <DashStatsCard stats={stats} /><br /><br />

          <AppointmentTrendsChart data={analyticsStats?.monthly || []} /><br />

          <AppointmentDemographics stats={analyticsStats} />

          {/* TABLE SECTION */}
          <div className={styles.tableSection}>
            <PageIntro
              title="Appointments"
              description="Manage all appointments"
            />

            {/* FILTERS */}
               <div className={styles.filterBar}>
                <MemberSearch
                  placeholder="Search..."
                  value={searchTerm}
                  onChange={(val: string) => setSearchTerm(val)}
                  url={route("dashboard.appointments.index")}
                />

                <select
                  value={localFilters.status}
                  onChange={(e) => {
                    const val = e.target.value;
                    setLocalFilters((prev) => ({ ...prev, status: val }));
                    applyFilters({ status: val });
                  }}
                >
                  <option value="">All</option>
                  <option value="pending">Pending</option>
                  <option value="assigned">Assigned</option>
                  <option value="completed">Completed</option>
                </select>

                {/* <select
                  value={localFilters.sort}
                  onChange={(e) => {
                    const val = e.target.value;
                    setLocalFilters((prev) => ({ ...prev, sort: val }));
                    applyFilters({ sort: val });
                  }}
                >
                  <option value="latest">Latest</option>
                  <option value="oldest">Oldest</option>
                </select> */}

                <button onClick={clearFilters} className={styles.clearBtn}>
                  Clear
                </button>
              </div>

              <div style={{ paddingTop: ".6rem" }} className={styles.filterChips}>
                {searchTerm && <span>Search: {searchTerm}</span>}
                {localFilters.status && <span>Status: {localFilters.status}</span>}
                {localFilters.sort !== "latest" && (
                  <span>Sort: {localFilters.sort}</span>
                )}
              </div>

                {/* BULK ASSIGNMENT */}
                  <div className={styles.bulkActions}>
                    <button
                      disabled={selectedIds.length === 0}
                      onClick={() => {
                        setBulkMode(true);
                        setAssignModal(true);
                      }}
                    >
                      Bulk Assign ({selectedIds.length})
                    </button>
                  </div>

                {/* TABLE */}
                <NewDataTable
                  data={appointments}
                  columns={columns}
                  actions={actions}
                />

            {/* PAGINATION */}
            <Pagination
              links={allAppointments?.links}
              onChange={handlePageChange}
            />
          </div>
        </div>
      </div>
    </>
  );
};

DashboardAppointments.layout = (page: any) => (
  <DashboardLayout title="Appointments">{page}</DashboardLayout>
);

export default DashboardAppointments;