"use client";

import React, { useEffect, useState, useCallback } from "react";
import { useRouter } from "next/navigation";
import toast from "react-hot-toast";
import styles from "../commonstyle/dattabale.module.css";
import { EnterpriseLoader } from "../../../../components/loader/loader";
import MeetingsHeader from "./MeetingsHeader";
import MeetingRow, { MeetingRowData } from "./MeetingRow";
import { makeMeetingApi } from "@/lib/api/meeting.api";

const getStaffToken = () =>
  typeof window !== "undefined" ? localStorage.getItem("access_token") || "" : "";

export default function MeetingsPage() {
  const router = useRouter();
  const api = makeMeetingApi({ getToken: getStaffToken });

  const [meetings, setMeetings] = useState<MeetingRowData[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [showNew, setShowNew] = useState(false);
  const [joinCode, setJoinCode] = useState("");
  const [creating, setCreating] = useState(false);
  const [title, setTitle] = useState("");

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const res = await api.listMeetings();
      const data = res?.data ?? res ?? [];
      setMeetings(Array.isArray(data) ? data : []);
      setError("");
    } catch (e: any) {
      setError(e?.message || "Failed to load meetings");
    } finally {
      setLoading(false);
    }
  }, []); // eslint-disable-line

  useEffect(() => { load(); }, [load]);

  const openRoom = (code: string) => {
    if (!code) return;
    router.push(`/modules/meetings/room/${code}`);
  };

  const createMeeting = async () => {
    if (!title.trim()) { toast.error("Give the meeting a title."); return; }
    setCreating(true);
    try {
      const res = await api.createMeeting({ title: title.trim() });
      const code = res?.data?.room_code || res?.room_code || res?.data?.roomCode || res?.roomCode;
      if (!code) throw new Error("No room code returned");
      toast.success("Meeting created");
      setShowNew(false); setTitle("");
      openRoom(code);
    } catch (e: any) {
      toast.error(e?.message || "Could not create meeting");
    } finally {
      setCreating(false);
    }
  };

  const endMeeting = async (row: MeetingRowData) => {
    try {
      await api.endMeeting(row.id);
      toast.success("Meeting ended");
      load();
    } catch (e: any) {
      toast.error(e?.message || "Could not end meeting");
    }
  };

  if (loading) return <EnterpriseLoader />;

  if (error) {
    return (
      <div className={styles.container}>
        <MeetingsHeader onRefresh={load} onNew={() => setShowNew(true)} />
        <div className={styles.errorContainer}>
          <div className={styles.errorIcon}>!</div>
          <div className={styles.errorTitle}>Couldn't load meetings</div>
          <div className={styles.errorMessage}>{error}</div>
          <button className={styles.errorButton} onClick={load}>Try again</button>
        </div>
      </div>
    );
  }

  return (
    <div className={styles.container}>
      <MeetingsHeader totalMeetings={meetings.length} onRefresh={load} onNew={() => setShowNew(true)} />

      {/* quick join by code */}
      <div style={{
        display: "flex", alignItems: "center", gap: 10, background: "#fff",
        border: "1px solid #e5e7eb", borderRadius: 10, padding: "10px 14px", margin: "0 0 16px",
      }}>
        <input
          value={joinCode}
          onChange={(e) => setJoinCode(e.target.value)}
          onKeyDown={(e) => e.key === "Enter" && openRoom(joinCode.trim())}
          placeholder="Enter a meeting code to join…"
          style={{ flex: 1, border: "none", outline: "none", fontSize: 14, color: "#1f2937" }}
        />
        <button
          disabled={!joinCode.trim()}
          onClick={() => openRoom(joinCode.trim())}
          style={{
            border: "none", background: "#f3eefb", color: "#6d28d9", fontWeight: 700,
            fontSize: 13, padding: "8px 18px", borderRadius: 8, cursor: "pointer",
            opacity: joinCode.trim() ? 1 : 0.5,
          }}
        >Join</button>
      </div>

      <div className={styles.tableWrapper}>
        <table className={styles.table} style={{ tableLayout: "fixed", width: "100%" }}>
          <colgroup>
            <col style={{ width: "30%" }} />
            <col style={{ width: "16%" }} />
            <col style={{ width: "20%" }} />
            <col style={{ width: "16%" }} />
            <col style={{ width: "10%" }} />
            <col style={{ width: "8%" }} />
          </colgroup>
          <thead>
            <tr>
              <th>Meeting</th>
              <th>Code</th>
              <th>Date / Time</th>
              <th>Host</th>
              <th>Status</th>
              <th style={{ textAlign: "right" }}>Actions</th>
            </tr>
          </thead>
          <tbody>
            {meetings.length === 0 ? (
              <tr>
                <td colSpan={6} style={{ textAlign: "center", padding: "50px 20px", color: "#9ca3af" }}>
                  No meetings yet. Click “New Meeting” to start one.
                </td>
              </tr>
            ) : (
              meetings.map((m) => (
                <MeetingRow key={m.id} row={m} onJoin={openRoom} onEnd={endMeeting} />
              ))
            )}
          </tbody>
        </table>
      </div>

      {/* New meeting modal */}
      {showNew && (
        <div
          onClick={() => setShowNew(false)}
          style={{ position: "fixed", inset: 0, background: "rgba(17,24,39,0.5)", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 1000, padding: 20 }}
        >
          <div onClick={(e) => e.stopPropagation()} style={{ width: "100%", maxWidth: 420, background: "#fff", borderRadius: 14, padding: 24 }}>
            <h3 style={{ margin: "0 0 16px", fontSize: 18, fontWeight: 700, color: "#111827" }}>New meeting</h3>
            <label style={{ fontSize: 11, fontWeight: 700, color: "#6b7280", textTransform: "uppercase", letterSpacing: ".05em" }}>Title</label>
            <input
              value={title} onChange={(e) => setTitle(e.target.value)} autoFocus
              placeholder="e.g. Stage 1 Audit — Meridian Marine"
              style={{ width: "100%", height: 44, border: "1.5px solid #e5e7eb", borderRadius: 10, padding: "0 13px", fontSize: 14, marginTop: 6, marginBottom: 16, boxSizing: "border-box", outline: "none" }}
            />
            <div style={{ display: "flex", gap: 10, justifyContent: "flex-end" }}>
              <button onClick={() => setShowNew(false)} style={{ padding: "10px 18px", border: "1.5px solid #e5e7eb", background: "#fff", borderRadius: 10, fontWeight: 600, cursor: "pointer" }}>Cancel</button>
              <button onClick={createMeeting} disabled={creating} style={{ padding: "10px 20px", border: "none", background: "linear-gradient(135deg,#7c3aed,#4a0080)", color: "#fff", borderRadius: 10, fontWeight: 700, cursor: "pointer", opacity: creating ? 0.6 : 1 }}>
                {creating ? "Creating…" : "Create & join"}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}