"use client";

import { useEffect, useState, useCallback } from "react";
import { api } from "../api";
import { Header } from "../components/Header";
import { useRequireAuth } from "../hooks/useRequireAuth";
import { components } from "../generated/api";
import constants from "../../../shared/constants.json";
import {
  layoutStyles,
  cardStyles,
  typographyStyles,
  badgeStyles,
  buttonStyles,
} from "../styles/shared";

// Use generated type from OpenAPI schema
type Invite = components["schemas"]["UserInviteResponse"];

export default function InvitesPage() {
  const { user, isLoading, isAuthorized } = useRequireAuth({
    requiredRole: constants.roles.REGULAR,
    fallbackRedirect: "/audit",
  });
  const [invites, setInvites] = useState<Invite[]>([]);
  const [isLoadingInvites, setIsLoadingInvites] = useState(true);
  const [copiedId, setCopiedId] = useState<number | null>(null);

  const fetchInvites = useCallback(async () => {
    try {
      const data = await api.get<Invite[]>("/api/invites");
      setInvites(data);
    } catch (err) {
      console.error("Failed to load invites:", err);
    } finally {
      setIsLoadingInvites(false);
    }
  }, []);

  useEffect(() => {
    if (user && isAuthorized) {
      fetchInvites();
    }
  }, [user, isAuthorized, fetchInvites]);

  const getInviteUrl = (identifier: string) => {
    if (typeof window !== "undefined") {
      return `${window.location.origin}/signup/${identifier}`;
    }
    return `/signup/${identifier}`;
  };

  const copyToClipboard = async (invite: Invite) => {
    const url = getInviteUrl(invite.identifier);
    try {
      await navigator.clipboard.writeText(url);
      setCopiedId(invite.id);
      setTimeout(() => setCopiedId(null), 2000);
    } catch (err) {
      console.error("Failed to copy:", err);
    }
  };

  if (isLoading || isLoadingInvites) {
    return (
      <main style={layoutStyles.main}>
        <div style={layoutStyles.loader}>Loading...</div>
      </main>
    );
  }

  if (!user || !isAuthorized) {
    return null;
  }

  const { READY, SPENT, REVOKED } = constants.inviteStatuses;
  const readyInvites = invites.filter((i) => i.status === READY);
  const spentInvites = invites.filter((i) => i.status === SPENT);
  const revokedInvites = invites.filter((i) => i.status === REVOKED);

  return (
    <main style={layoutStyles.main}>
      <Header currentPage="invites" />

      <div style={layoutStyles.contentCentered}>
        <div style={styles.pageCard}>
          <div style={cardStyles.cardHeader}>
            <h1 style={cardStyles.cardTitle}>My Invites</h1>
            <p style={cardStyles.cardSubtitle}>
              Share your invite codes with friends to let them join
            </p>
          </div>

          {invites.length === 0 ? (
            <div style={styles.emptyState}>
              <p style={styles.emptyText}>You don&apos;t have any invites yet.</p>
              <p style={styles.emptyHint}>Contact an admin if you need invite codes to share.</p>
            </div>
          ) : (
            <div style={styles.sections}>
              {/* Ready Invites */}
              {readyInvites.length > 0 && (
                <div style={styles.section}>
                  <h2 style={typographyStyles.sectionTitle}>Available ({readyInvites.length})</h2>
                  <p style={typographyStyles.sectionHint}>
                    Share these links with people you want to invite
                  </p>
                  <div style={styles.inviteList}>
                    {readyInvites.map((invite) => (
                      <div key={invite.id} style={styles.inviteCard}>
                        <div style={styles.inviteCode}>{invite.identifier}</div>
                        <div style={styles.inviteActions}>
                          <button
                            onClick={() => copyToClipboard(invite)}
                            style={buttonStyles.accentButton}
                          >
                            {copiedId === invite.id ? "Copied!" : "Copy Link"}
                          </button>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Spent Invites */}
              {spentInvites.length > 0 && (
                <div style={styles.section}>
                  <h2 style={typographyStyles.sectionTitle}>Used ({spentInvites.length})</h2>
                  <div style={styles.inviteList}>
                    {spentInvites.map((invite) => (
                      <div key={invite.id} style={styles.inviteCardSpent}>
                        <div style={styles.inviteCode}>{invite.identifier}</div>
                        <div style={styles.inviteeMeta}>
                          <span style={{ ...badgeStyles.badge, ...badgeStyles.badgeSuccess }}>
                            Used
                          </span>
                          <span style={styles.inviteeEmail}>by {invite.used_by_email}</span>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Revoked Invites */}
              {revokedInvites.length > 0 && (
                <div style={styles.section}>
                  <h2 style={typographyStyles.sectionTitle}>Revoked ({revokedInvites.length})</h2>
                  <div style={styles.inviteList}>
                    {revokedInvites.map((invite) => (
                      <div key={invite.id} style={styles.inviteCardRevoked}>
                        <div style={styles.inviteCode}>{invite.identifier}</div>
                        <span style={{ ...badgeStyles.badge, ...badgeStyles.badgeError }}>
                          Revoked
                        </span>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </main>
  );
}

// Page-specific styles
const styles: Record<string, React.CSSProperties> = {
  pageCard: {
    ...cardStyles.card,
    width: "100%",
    maxWidth: "600px",
  },
  emptyState: {
    textAlign: "center",
    padding: "2rem 0",
  },
  emptyText: {
    fontFamily: "'DM Sans', system-ui, sans-serif",
    color: "rgba(255, 255, 255, 0.6)",
    fontSize: "1rem",
    margin: 0,
  },
  emptyHint: {
    fontFamily: "'DM Sans', system-ui, sans-serif",
    color: "rgba(255, 255, 255, 0.4)",
    fontSize: "0.85rem",
    marginTop: "0.5rem",
  },
  sections: {
    display: "flex",
    flexDirection: "column",
    gap: "2rem",
  },
  section: {
    display: "flex",
    flexDirection: "column",
    gap: "0.75rem",
  },
  inviteList: {
    display: "flex",
    flexDirection: "column",
    gap: "0.75rem",
  },
  inviteCard: {
    background: "rgba(99, 102, 241, 0.1)",
    border: "1px solid rgba(99, 102, 241, 0.3)",
    borderRadius: "12px",
    padding: "1rem",
    display: "flex",
    justifyContent: "space-between",
    alignItems: "center",
  },
  inviteCardSpent: {
    background: "rgba(34, 197, 94, 0.08)",
    border: "1px solid rgba(34, 197, 94, 0.2)",
    borderRadius: "12px",
    padding: "1rem",
    display: "flex",
    justifyContent: "space-between",
    alignItems: "center",
  },
  inviteCardRevoked: {
    background: "rgba(239, 68, 68, 0.08)",
    border: "1px solid rgba(239, 68, 68, 0.2)",
    borderRadius: "12px",
    padding: "1rem",
    display: "flex",
    justifyContent: "space-between",
    alignItems: "center",
    opacity: 0.7,
  },
  inviteCode: {
    fontFamily: "'DM Mono', monospace",
    fontSize: "0.95rem",
    color: "#fff",
    letterSpacing: "0.02em",
  },
  inviteActions: {
    display: "flex",
    gap: "0.5rem",
  },
  inviteeMeta: {
    display: "flex",
    alignItems: "center",
    gap: "0.5rem",
  },
  inviteeEmail: {
    fontFamily: "'DM Sans', system-ui, sans-serif",
    fontSize: "0.8rem",
    color: "rgba(255, 255, 255, 0.6)",
  },
};
