"use client";

import { useEffect, useState, useCallback } from "react";
import { Permission } from "../auth-context";
import { api } from "../api";
import { layoutStyles, cardStyles, tableStyles, paginationStyles } 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={layoutStyles.main}>
        <div style={layoutStyles.loader}>Loading...</div>
      </main>
    );
  }

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

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

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

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

// Page-specific styles only
const styles: Record<string, React.CSSProperties> = {
  tablesContainer: {
    display: "flex",
    flexDirection: "column",
    gap: "2rem",
    maxWidth: "1200px",
    margin: "0 auto",
  },
  tdResult: {
    padding: "0.875rem 1rem",
    fontSize: "0.875rem",
    color: "#a78bfa",
    fontWeight: 600,
    fontFamily: "'DM Sans', monospace",
  },
};
