import React, { JSX, useEffect, useState } from "react";
import { fetchPlayers } from "../api";
import { User, UserRole } from "../../components/interfaces/users";
import UsersPage from "./Users";
import TMP from "./TMP";
import TeamManagement from "../Teams";
import Teams from "./Teams";

// type User = {
//     id: string;
//     name: string;
//     email: string;
//     role: "user" | "admin";
//     banned?: boolean;
// };

type Team = {
    id: string;
    name: string;
    members: number;
};

type EventItem = {
    id: string;
    title: string;
    date: string; // ISO
    location?: string;
};

const containerStyle: React.CSSProperties = {
    display: "flex",
    height: "100%",
    gap: 20,
    padding: 20,
    boxSizing: "border-box",
    fontFamily: "Inter, Roboto, Arial, sans-serif",
};

const sidebarStyle: React.CSSProperties = {
    width: 220,
    borderRight: "1px solid #e6e6e6",
    paddingRight: 12,
};

const tabButtonStyle = (active: boolean): React.CSSProperties => ({
    display: "block",
    width: "100%",
    textAlign: "left",
    padding: "8px 10px",
    marginBottom: 6,
    cursor: "pointer",
    borderRadius: 6,
    background: active ? "#0b5fff1a" : "transparent",
    border: active ? "1px solid #0b5fff33" : "1px solid transparent",
});

const contentStyle: React.CSSProperties = {
    flex: 1,
    minWidth: 0,
    overflowY: "auto",
};

export default function Administration(): JSX.Element {
    const [activeTab, setActiveTab] = useState<
        "users" | "teams" | "events" | "settings" | "TMP"
    >("users");

    const [teams, setTeams] = useState<Team[]>([]);
    const [events, setEvents] = useState<EventItem[]>([]);

    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);

    // Form state for creating event
    const [newEventTitle, setNewEventTitle] = useState("");
    const [newEventDate, setNewEventDate] = useState("");
    const [newEventLocation, setNewEventLocation] = useState("");
    const token = localStorage.getItem('token');

    useEffect(() => {
        // fetch all admin resources when component mounts
        if (token) refreshAll();
    }, []);

    async function refreshAll() {
        if (!token) return;
        setLoading(true);
        setError(null);
        try {
            // Replace these endpoints with your backend API
            
            const [uRes, tRes, eRes] = await Promise.all([
                fetch("/api/admin/players"),
                fetch("/api/admin/teams"),
                fetch("/api/admin/events"),
            ]);

            if (!tRes.ok || !eRes.ok) {
                throw new Error("Failed to fetch admin resources");
            }
            
            // console.log(uRes);
            const [tJson, eJson] = await Promise.all([
                tRes.json(),
                eRes.json(),
            ]);
            
            setTeams(tJson as Team[]);
            setEvents(eJson as EventItem[]);
            

        } catch (err: any) {
            setError(err?.message ?? "Unknown error");
        } finally {
            setLoading(false);
        }
    }

    async function deleteTeam(team: Team) {
        if (!window.confirm(`Delete team "${team.name}"? This cannot be undone.`)) return;
        try {
            const res = await fetch(`/api/admin/teams/${team.id}`, { method: "DELETE" });
            if (!res.ok) throw new Error("Failed to delete team");
            setTeams((prev) => prev.filter((t) => t.id !== team.id));
        } catch (err: any) {
            alert(err?.message ?? "Failed to delete team");
        }
    }

    async function createEvent(e: React.FormEvent) {
        e.preventDefault();
        if (!newEventTitle || !newEventDate) {
            alert("Title and date required");
            return;
        }
        try {
            const payload = {
                title: newEventTitle,
                date: new Date(newEventDate).toISOString(),
                location: newEventLocation || undefined,
            };
            const res = await fetch("/api/admin/events", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify(payload),
            });
            if (!res.ok) throw new Error("Failed to create event");
            const created: EventItem = await res.json();
            setEvents((prev) => [created, ...prev]);
            setNewEventTitle("");
            setNewEventDate("");
            setNewEventLocation("");
            setActiveTab("events");
        } catch (err: any) {
            alert(err?.message ?? "Failed to create event");
        }
    }

    async function deleteEvent(ev: EventItem) {
        if (!window.confirm(`Delete event "${ev.title}"?`)) return;
        try {
            const res = await fetch(`/api/admin/events/${ev.id}`, { method: "DELETE" });
            if (!res.ok) throw new Error("Failed to delete event");
            setEvents((prev) => prev.filter((x) => x.id !== ev.id));
        } catch (err: any) {
            alert(err?.message ?? "Failed to delete event");
        }
    }

    return (
        <div style={containerStyle}>
            <aside style={sidebarStyle}>
                <h3>Administration</h3>
                <div>
                    <button
                        style={tabButtonStyle(activeTab === "users")}
                        onClick={() => setActiveTab("users")}
                    >
                        Users
                    </button>
                    <button
                        style={tabButtonStyle(activeTab === "teams")}
                        onClick={() => setActiveTab("teams")}
                    >
                        Teams
                    </button>
                    <button
                        style={tabButtonStyle(activeTab === "events")}
                        onClick={() => setActiveTab("events")}
                    >
                        Events
                    </button>
                    <button
                        style={tabButtonStyle(activeTab === "settings")}
                        onClick={() => setActiveTab("settings")}
                    >
                        Settings
                    </button>
                    <button
                        style={tabButtonStyle(activeTab === "TMP")}
                        onClick={() => {
                            setActiveTab("TMP");
                        }}
                    >
                        TMP
                    </button>
                </div>

                <div style={{ marginTop: 20 }}>
                    <button onClick={refreshAll} style={{ padding: "6px 10px", cursor: "pointer" }}>
                        Refresh
                    </button>
                </div>

                {loading && <p style={{ marginTop: 12 }}>Loading...</p>}
                {error && <p style={{ marginTop: 12, color: "red" }}>{error}</p>}
            </aside>

            <main style={contentStyle}>
                {activeTab === "users" && (
                    <section>
                        <h2>Users</h2>
                        <p>Manage user accounts, roles and bans.</p>
                        <div style={{ marginTop: 12 }}>
                            <UsersPage />
                        </div>                       
                    </section>
                )}

                {activeTab === "teams" && (
                    <section>
                        <Teams />
                        
                    </section>
                )}

                {activeTab === "events" && (
                    <section>
                        <h2>Events</h2>
                        <p>Create and manage events</p>

                        <form onSubmit={createEvent} style={{ marginTop: 12, marginBottom: 24 }}>
                            <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                                <input
                                    placeholder="Event title"
                                    value={newEventTitle}
                                    onChange={(e) => setNewEventTitle(e.target.value)}
                                    style={{ padding: 8, flex: 1 }}
                                />
                                <input
                                    type="date"
                                    value={newEventDate}
                                    onChange={(e) => setNewEventDate(e.target.value)}
                                    style={{ padding: 8 }}
                                />
                                <input
                                    placeholder="Location (optional)"
                                    value={newEventLocation}
                                    onChange={(e) => setNewEventLocation(e.target.value)}
                                    style={{ padding: 8 }}
                                />
                                <button type="submit" style={{ padding: "8px 12px" }}>
                                    Create
                                </button>
                            </div>
                        </form>

                        <div>
                            {events.length === 0 ? (
                                <p>No events.</p>
                            ) : (
                                <ul style={{ paddingLeft: 0, listStyle: "none" }}>
                                    {events.map((ev) => (
                                        <li
                                            key={ev.id}
                                            style={{
                                                display: "flex",
                                                justifyContent: "space-between",
                                                padding: "8px 0",
                                                borderBottom: "1px solid #f2f2f2",
                                            }}
                                        >
                                            <div>
                                                <strong>{ev.title}</strong>
                                                <div style={{ fontSize: 13, color: "#666" }}>
                                                    {new Date(ev.date).toLocaleString()} {ev.location ? `• ${ev.location}` : ""}
                                                </div>
                                            </div>
                                            <div>
                                                <button style={{ marginRight: 8 }}>Edit</button>
                                                <button onClick={() => deleteEvent(ev)}>Delete</button>
                                            </div>
                                        </li>
                                    ))}
                                </ul>
                            )}
                        </div>
                    </section>
                )}

                {activeTab === "settings" && (
                    <section>
                        <h2>Settings</h2>
                        <p>Application-wide administrative settings.</p>
                        <div style={{ marginTop: 12 }}>
                            <p style={{ fontSize: 14, color: "#444" }}>
                                Use these settings to control global features. Implement actual controls as needed.
                            </p>

                            <div style={{ marginTop: 12 }}>
                                <label style={{ display: "block", marginBottom: 8 }}>
                                    <input type="checkbox" /> Allow public registration
                                </label>
                                <label style={{ display: "block", marginBottom: 8 }}>
                                    <input type="checkbox" /> Require email verification
                                </label>
                                <div style={{ marginTop: 12 }}>
                                    <button onClick={() => alert("Settings saved (stub)")}>Save settings</button>
                                </div>
                            </div>
                        </div>
                    </section>
                )}
                {activeTab === "TMP" && (
                    <section>
                        <h2>TMP Tab</h2>
                        <TMP/>
                    </section>
                )}
            </main>
        </div>
    );
}