"use client";

import { Group, Paper, ScrollArea, Stack, Table, Text, Title } from "@mantine/core";
import { useMediaQuery } from "@mantine/hooks";
import { notifications } from "@mantine/notifications";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";

interface accountData {
  stAccountNo: string;
  stAccountType: string;
  stAvailableBalance: string;
  custname: string;
}

export default function AccountSummary() {
  const router = useRouter();
  const [authorized, setAuthorized] = useState<boolean | null>(null);
  const [accountData, setAccountData] = useState<accountData[]>([]);
  const isMobile = useMediaQuery("(max-width: 768px)");

  async function FetchAccountDetails() {
    try {
      const token = localStorage.getItem("access_token");
      const response = await fetch("/api/customer", {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
          "X-Login-Type": "IB",
          Authorization: `Bearer ${token}`,
        },
      });
      const data = await response.json();
      if (response.ok && Array.isArray(data)) {
        setAccountData(data);
        // sessionStorage.setItem("accountData", JSON.stringify(data));
      }
    } catch {
      notifications.show({
        withBorder: true,
        color: "red",
        title: "Please try again later",
        message: "Unable to Fetch, Please try again later",
        autoClose: 5000,
      });
    }
  }

  useEffect(() => {
    const token = localStorage.getItem("access_token");
    if (!token) {
      setAuthorized(false);
      router.push("/login");
    } else {
      setAuthorized(true);
    }
  }, []);

  useEffect(() => {
    if (authorized) {
      FetchAccountDetails();
    }
  }, [authorized]);

  const cellStyle = {
    border: "1px solid #ccc",
    padding: isMobile ? "8px" : "10px",
    fontSize: isMobile ? "13px" : "14px",
  };

  // Filter accounts
  const depositAccounts = accountData.filter(
    (acc) => !acc.stAccountType.toUpperCase().includes("LN")
  );
  const loanAccounts = accountData.filter((acc) =>
    acc.stAccountType.toUpperCase().includes("LN")
  );

  // Function to render table rows
  const renderRows = (data: accountData[]) =>
    data.map((acc, index) => (
      <tr key={index}>
        <td style={{ ...cellStyle, textAlign: "left" }}>{acc.stAccountType}</td>
        <td
          style={{ ...cellStyle, textAlign: "right", color: "#1c7ed6", cursor: "pointer" }}
          onClick={() => router.push(`/accounts/account_details?accNo=${acc.stAccountNo}`)}
        >
          {acc.stAccountNo}
        </td>
        <td style={{ ...cellStyle, textAlign: "right" }}>
          {parseFloat(acc.stAvailableBalance).toLocaleString("en-IN", {
            minimumFractionDigits: 2,
          })}
        </td>
      </tr>
    ));

  // Table component
  const renderTable = (title: string, rows: JSX.Element[]) => (
    <Paper shadow="sm" radius="md" p="md" withBorder w="100%"
    // bg="#97E6B8"
    >
      <Title order={isMobile ? 5 : 4} mb="sm">
        {title}
      </Title>
      <ScrollArea>
        <Table style={{ borderCollapse: "collapse", width: "100%" }}>
          <thead>
            <tr style={{ backgroundColor: "#3385ff" }}>
              <th style={{ ...cellStyle, textAlign: "left" }}>Account Type</th>
              <th style={{ ...cellStyle, textAlign: "right" }}>Account No.</th>
              {title.includes("Deposit Accounts (INR)") ?
                (<th style={{ ...cellStyle, textAlign: "right" }}> Credit Book Balance</th>)
                : (<th style={{ ...cellStyle, textAlign: "right" }}>Debit Book Balance</th>)}

            </tr>
          </thead>
          <tbody>{rows}</tbody>
        </Table>
      </ScrollArea>
    </Paper>
  );

  if (!authorized) return null;

  return (
    <Paper shadow="sm" radius="md" p="md" withBorder>
      <Title
        order={isMobile ? 4 : 3}
        mb="md"
        style={{ textAlign: isMobile ? "center" : "left" }}
      >
        Account Summary
      </Title>

      {/* ✅ Responsive layout: Group for desktop, Stack for mobile */}
      {isMobile ? (
        <Stack gap="md">
          {depositAccounts.length > 0 &&
            renderTable("Deposit Accounts (INR)", renderRows(depositAccounts))}
          {loanAccounts.length > 0 &&
            renderTable("Loan Accounts (INR)", renderRows(loanAccounts))}
        </Stack>
      ) : (
        <Group align="flex-start" grow>
          {depositAccounts.length > 0 &&
            renderTable("Deposit Accounts (INR)", renderRows(depositAccounts))}
          {loanAccounts.length > 0 &&
            renderTable("Loan Accounts (INR)", renderRows(loanAccounts))}
        </Group>
      )}

      <Text mt="sm" size="xs" c="dimmed">
        * Book Balance includes uncleared effects.
      </Text>
    </Paper>
  );
}
