"use client";

/* eslint-disable @typescript-eslint/no-explicit-any */
import styles from "./home-cell-card.module.scss";
import {
  FiMapPin,
  FiCalendar,
  FiClock,
  FiPhone,
  FiEdit,
  FiTrash2,
} from "react-icons/fi";
import { usePage } from "@inertiajs/react";
import { useEffect, useState } from "react";
import churchLogo from "../../../../../public/logo.png";

interface Props {
  cell: any;
  loading?: boolean;
  onEdit?: (cell: any) => void;
  onDelete?: (id: number) => void;
}

/* ================= COUNTDOWN ================= */
const getCountdown = (dateString: string) => {
  const now = new Date().getTime();
  const target = new Date(dateString).getTime();

  const diff = target - now;

  if (diff <= 0) return "Ongoing";

  const days = Math.floor(diff / (1000 * 60 * 60 * 24));
  const hours = Math.floor(
    (diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
  );

  if (days > 0) return `In ${days} day${days > 1 ? "s" : ""}`;
  return `In ${hours} hr${hours > 1 ? "s" : ""}`;
};

export default function HomeCellCard({
  cell,
  loading,
  onEdit,
  onDelete,
}: Props) {
  const { url } = usePage();
  const isDashboard = url.includes("/dashboard");

  const [countdown, setCountdown] = useState("");

  useEffect(() => {
    if (!cell?.nextMeeting) return;

    const update = () => setCountdown(getCountdown(cell.nextMeeting));

    update();
    const interval = setInterval(update, 60000);

    return () => clearInterval(interval);
  }, [cell]);

  if (loading) return <HomeCellCardSkeleton />;

  const members = cell?.members || [];
  const visibleMembers = members.slice(0, 5);
  const remaining = members.length - visibleMembers.length;

  return (
    <div className={styles.card}>
      <div className={styles.top}>
        <div className={styles.logo}>
          <img src={churchLogo} alt="Censers Church" />
        </div>

        <div className={styles.info}>
          <h3 className={styles.name}>{cell?.name}</h3>
          <span className={styles.members}>
            {members.length} Members
          </span>
        </div>
      </div>

      <div className={styles.locationRow}>
        <FiMapPin />
        <span>{cell?.location || cell?.address}</span>
      </div>

      <div className={styles.scheduleRow}>
        <div className={styles.scheduleItem}>
          <FiCalendar />
          <span>{cell?.day || cell?.meeting_day}</span>
        </div>

        <div className={styles.scheduleItem}>
          <FiClock />
          <span>{cell?.time || cell?.meeting_time}</span>
        </div>
      </div>

      { !isDashboard && (<div className={styles.nextMeeting}>
        <span>Next Meeting</span>
        <strong>{countdown}</strong>
      </div>) }

      <div className={styles.divider} />

      {/* ================= FOOTER ================= */}
      <div className={styles.group}>

        {/* ================= MEMBER MODE (UNCHANGED) ================= */}
        {!isDashboard && (
          <>
            <div className={styles.avatars}>
              {visibleMembers.map((m: any, i: number) => (
                <img key={i} src={m.avatar} alt={m.name} />
              ))}

              {remaining > 0 && (
                <div className={styles.more}>+{remaining}</div>
              )}
            </div>

            <a
              href={`tel:${cell?.phone || cell?.leader_phone || "08000000000"}`}
              className={styles.call}
              onClick={(e) => e.stopPropagation()}
            >
              <FiPhone />
              <span>{cell?.phone || "Call"}</span>
            </a>
          </>
        )}

        {/* ================= DASHBOARD MODE (UPDATED FULL WIDTH) ================= */}
        {isDashboard && (
          <div className={styles.actions}>
            <button
              onClick={(e) => {
                e.preventDefault();
                e.stopPropagation();
                onEdit?.(cell);
              }}
              className={styles.editBtn}
            >
              <FiEdit />
              <span>Update</span>
            </button>

            <button
              onClick={(e) => {
                e.preventDefault();
                e.stopPropagation();
                onDelete?.(cell.id);
              }}
              className={styles.deleteBtn}
            >
              <FiTrash2 />
              <span>Delete</span>
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

/* ================= ORIGINAL SKELETON (UNCHANGED) ================= */
export function HomeCellCardSkeleton() {
  return (
    <div className={`${styles.card} ${styles.skeleton}`}>
      <div className={styles.top}>
        <div className={styles.skelLogo} />
        <div className={styles.skelText}>
          <div className={styles.skelTitle} />
          <div className={styles.skelSub} />
        </div>
      </div>

      <div className={styles.skelLocation} />

      <div className={styles.scheduleRow}>
        <div className={styles.skelScheduleItem} />
        <div className={styles.skelScheduleItem} />
      </div>

      <div className={styles.skelNext} />

      <div className={styles.divider} />

      <div className={styles.group}>
        <div className={styles.skelAvatars}>
          <span />
          <span />
          <span />
        </div>

        <div className={styles.skelBtn} />
      </div>
    </div>
  );
}