"use client";

import { useEffect, useState, useCallback } from "react";
import { Permission } from "../auth-context";
import { api } from "../api";
import { sharedStyles } from "../styles/shared";
import { Header } from "../components/Header";
import { useRequireAuth } from "../hooks/useRequireAuth";
import { components } from "../generated/api";

// Use generated types from OpenAPI schema
type _CounterRecord = components["schemas"]["CounterRecordResponse"];
type _SumRecord = components["schemas"]["SumRecordResponse"];
type PaginatedCounterRecords = components["schemas"]["PaginatedResponse_CounterRecordResponse_"];
type PaginatedSumRecords = components["schemas"]["PaginatedResponse_SumRecordResponse_"];

export default function AuditPage() {
  const [counterData, setCounterData] = useState<PaginatedCounterRecords | null>(null);
  const [sumData, setSumData] = useState<PaginatedSumRecords | null>(null);
  const [counterError, setCounterError] = useState<string | null>(null);
  const [sumError, setSumError] = useState<string | null>(null);
  const [counterPage, setCounterPage] = useState(1);
  const [sumPage, setSumPage] = useState(1);
  const { user, isLoading, isAuthorized } = useRequireAuth({
    requiredPermission: Permission.VIEW_AUDIT,
    fallbackRedirect: "/",
  });

  const fetchCounterRecords = useCallback(async (page: number) => {
    setCounterError(null);
    try {
      const data = await api.get<PaginatedCounterRecords>(
        `/api/audit/counter?page=${page}&per_page=10`
      );
      setCounterData(data);
    } catch (err) {
      setCounterData(null);
      setCounterError(err instanceof Error ? err.message : "Failed to load counter records");
    }
  }, []);

  const fetchSumRecords = useCallback(async (page: number) => {
    setSumError(null);
    try {
      const data = await api.get<PaginatedSumRecords>(
        `/api/audit/sum?page=${page}&per_page=10`
      );
      setSumData(data);
    } catch (err) {
      setSumData(null);
      setSumError(err instanceof Error ? err.message : "Failed to load sum records");
    }
  }, []);

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

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

  const formatDate = (dateStr: string) => {
    return new Date(dateStr).toLocaleString();
  };

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

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

  return (
    <main style={styles.main}>
      <Header currentPage="audit" />

      <div style={styles.content}>
        <div style={styles.tablesContainer}>
          {/* Counter Records Table */}
          <div style={styles.tableCard}>
            <div style={styles.tableHeader}>
              <h2 style={styles.tableTitle}>Counter Activity</h2>
              <span style={styles.totalCount}>
                {counterData?.total ?? 0} records
              </span>
            </div>
            <div style={styles.tableWrapper}>
              <table style={styles.table}>
                <thead>
                  <tr>
                    <th style={styles.th}>User</th>
                    <th style={styles.th}>Before</th>
                    <th style={styles.th}>After</th>
                    <th style={styles.th}>Date</th>
                  </tr>
                </thead>
                <tbody>
                  {counterError && (
                    <tr>
                      <td colSpan={4} style={styles.errorRow}>{counterError}</td>
                    </tr>
                  )}
                  {!counterError && counterData?.records.map((record) => (
                    <tr key={record.id} style={styles.tr}>
                      <td style={styles.td}>{record.user_email}</td>
                      <td style={styles.tdNum}>{record.value_before}</td>
                      <td style={styles.tdNum}>{record.value_after}</td>
                      <td style={styles.tdDate}>{formatDate(record.created_at)}</td>
                    </tr>
                  ))}
                  {!counterError && (!counterData || counterData.records.length === 0) && (
                    <tr>
                      <td colSpan={4} style={styles.emptyRow}>No records yet</td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
            {counterData && counterData.total_pages > 1 && (
              <div style={styles.pagination}>
                <button
                  onClick={() => setCounterPage((p) => Math.max(1, p - 1))}
                  disabled={counterPage === 1}
                  style={styles.pageBtn}
                >
                  ←
                </button>
                <span style={styles.pageInfo}>
                  {counterPage} / {counterData.total_pages}
                </span>
                <button
                  onClick={() => setCounterPage((p) => Math.min(counterData.total_pages, p + 1))}
                  disabled={counterPage === counterData.total_pages}
                  style={styles.pageBtn}
                >
                  →
                </button>
              </div>
            )}
          </div>

          {/* Sum Records Table */}
          <div style={styles.tableCard}>
            <div style={styles.tableHeader}>
              <h2 style={styles.tableTitle}>Sum Activity</h2>
              <span style={styles.totalCount}>
                {sumData?.total ?? 0} records
              </span>
            </div>
            <div style={styles.tableWrapper}>
              <table style={styles.table}>
                <thead>
                  <tr>
                    <th style={styles.th}>User</th>
                    <th style={styles.th}>A</th>
                    <th style={styles.th}>B</th>
                    <th style={styles.th}>Result</th>
                    <th style={styles.th}>Date</th>
                  </tr>
                </thead>
                <tbody>
                  {sumError && (
                    <tr>
                      <td colSpan={5} style={styles.errorRow}>{sumError}</td>
                    </tr>
                  )}
                  {!sumError && sumData?.records.map((record) => (
                    <tr key={record.id} style={styles.tr}>
                      <td style={styles.td}>{record.user_email}</td>
                      <td style={styles.tdNum}>{record.a}</td>
                      <td style={styles.tdNum}>{record.b}</td>
                      <td style={styles.tdResult}>{record.result}</td>
                      <td style={styles.tdDate}>{formatDate(record.created_at)}</td>
                    </tr>
                  ))}
                  {!sumError && (!sumData || sumData.records.length === 0) && (
                    <tr>
                      <td colSpan={5} style={styles.emptyRow}>No records yet</td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
            {sumData && sumData.total_pages > 1 && (
              <div style={styles.pagination}>
                <button
                  onClick={() => setSumPage((p) => Math.max(1, p - 1))}
                  disabled={sumPage === 1}
                  style={styles.pageBtn}
                >
                  ←
                </button>
                <span style={styles.pageInfo}>
                  {sumPage} / {sumData.total_pages}
                </span>
                <button
                  onClick={() => setSumPage((p) => Math.min(sumData.total_pages, p + 1))}
                  disabled={sumPage === sumData.total_pages}
                  style={styles.pageBtn}
                >
                  →
                </button>
              </div>
            )}
          </div>
        </div>
      </div>
    </main>
  );
}

const pageStyles: Record<string, React.CSSProperties> = {
  // Override content for audit-specific layout
  content: {
    flex: 1,
    padding: "2rem",
    overflowY: "auto",
  },
  tablesContainer: {
    display: "flex",
    flexDirection: "column",
    gap: "2rem",
    maxWidth: "1200px",
    margin: "0 auto",
  },
  tableCard: {
    background: "rgba(255, 255, 255, 0.03)",
    backdropFilter: "blur(10px)",
    border: "1px solid rgba(255, 255, 255, 0.08)",
    borderRadius: "20px",
    padding: "1.5rem",
    boxShadow: "0 25px 50px -12px rgba(0, 0, 0, 0.5)",
  },
  tableHeader: {
    display: "flex",
    justifyContent: "space-between",
    alignItems: "center",
    marginBottom: "1rem",
  },
  tableTitle: {
    fontFamily: "'Instrument Serif', Georgia, serif",
    fontSize: "1.5rem",
    fontWeight: 400,
    color: "#fff",
    margin: 0,
  },
  totalCount: {
    fontFamily: "'DM Sans', system-ui, sans-serif",
    fontSize: "0.875rem",
    color: "rgba(255, 255, 255, 0.4)",
  },
  tableWrapper: {
    overflowX: "auto",
  },
  table: {
    width: "100%",
    borderCollapse: "collapse",
    fontFamily: "'DM Sans', system-ui, sans-serif",
  },
  th: {
    textAlign: "left",
    padding: "0.75rem 1rem",
    fontSize: "0.75rem",
    fontWeight: 600,
    color: "rgba(255, 255, 255, 0.4)",
    textTransform: "uppercase",
    letterSpacing: "0.05em",
    borderBottom: "1px solid rgba(255, 255, 255, 0.08)",
  },
  tr: {
    borderBottom: "1px solid rgba(255, 255, 255, 0.04)",
  },
  td: {
    padding: "0.875rem 1rem",
    fontSize: "0.875rem",
    color: "rgba(255, 255, 255, 0.7)",
  },
  tdNum: {
    padding: "0.875rem 1rem",
    fontSize: "0.875rem",
    color: "rgba(255, 255, 255, 0.9)",
    fontFamily: "'DM Sans', monospace",
  },
  tdResult: {
    padding: "0.875rem 1rem",
    fontSize: "0.875rem",
    color: "#a78bfa",
    fontWeight: 600,
    fontFamily: "'DM Sans', monospace",
  },
  tdDate: {
    padding: "0.875rem 1rem",
    fontSize: "0.75rem",
    color: "rgba(255, 255, 255, 0.4)",
  },
  emptyRow: {
    padding: "2rem 1rem",
    textAlign: "center",
    color: "rgba(255, 255, 255, 0.3)",
    fontSize: "0.875rem",
  },
  errorRow: {
    padding: "2rem 1rem",
    textAlign: "center",
    color: "#f87171",
    fontSize: "0.875rem",
  },
  pagination: {
    display: "flex",
    justifyContent: "center",
    alignItems: "center",
    gap: "1rem",
    marginTop: "1rem",
    paddingTop: "1rem",
    borderTop: "1px solid rgba(255, 255, 255, 0.06)",
  },
  pageBtn: {
    fontFamily: "'DM Sans', system-ui, sans-serif",
    padding: "0.5rem 1rem",
    fontSize: "1rem",
    background: "rgba(255, 255, 255, 0.05)",
    color: "rgba(255, 255, 255, 0.7)",
    border: "1px solid rgba(255, 255, 255, 0.1)",
    borderRadius: "8px",
    cursor: "pointer",
    transition: "all 0.2s",
  },
  pageInfo: {
    fontFamily: "'DM Sans', system-ui, sans-serif",
    fontSize: "0.875rem",
    color: "rgba(255, 255, 255, 0.5)",
  },
};

const styles = { ...sharedStyles, ...pageStyles };
