"use client";
import React, { useState } from "react";
import {
  TextInput,
  Button,
  Title,
  Stack,
  Group,
  Text,
  Divider,
  LoadingOverlay,
  Box,
  Paper,
  Center,
} from "@mantine/core";
import { notifications } from "@mantine/notifications";

interface UserRights {
  customer_no: string;
  created_at: string;
  last_login: Date;
  is_first_login: boolean;
  ibAccess: "1" | "2" | "0" | null;
  mbAccess: "1" | "2" | "0" | null;
}

export default function ViewUserRights() {
  const [CIFNo, setCIFNo] = useState("");
  const [loading, setLoading] = useState(false);
  const [userData, setUserData] = useState<UserRights | null>(null);
  const [error, setError] = useState<string | null>(null);

  const handleSearch = async () => {
    setError(null);
    if (!CIFNo) {
      notifications.show({
        color: "red",
        title: "CIF Missing",
        message: "Please enter a CIF number to proceed.",
      });
      setUserData(null);
      return;
    }
    setLoading(true);
    setUserData(null);
    try {
      const token = localStorage.getItem("admin_access_token");
      const response = await fetch(`/api/auth/admin/user/rights?CIF=${CIFNo}`, {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
          "X-Login-Type": "Admin",
          Authorization: `Bearer ${token}`,
        },
      });

      const data = await response.json();

      if (response.ok && data) {
        setUserData({
          customer_no: data.customer_no,
          created_at: data.created_at,
          last_login: data.last_login,
          is_first_login: data.is_first_login,
          ibAccess: data.ib_access_level,
          mbAccess: data.mb_access_level,
        });
      } else {
        setError("User not present or invalid CIF number.");
      }
    } catch (err) {
      setError("Error fetching user rights. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <Box>
      <LoadingOverlay visible={loading} zIndex={1000} />
      <Title order={4}>View User Rights</Title>
      <Group mt="sm">
        <TextInput
          placeholder="Enter CIF Number"
          value={CIFNo}
          onInput={(e) => {
            const input = e.currentTarget.value.replace(/\D/g, "");
            if (input.length <= 11) {
              setCIFNo(input);
              setUserData(null);
              setError(null);
            }
          }}
          style={{ flex: 1 }}
        />
        <Button onClick={handleSearch} disabled={loading}>
          Search
        </Button>
      </Group>

      {/* Error message in center */}
      {error && (
        <Center mt="xl">
          <Text c="red" fw={500} size="md">
            {error}
          </Text>
        </Center>
      )}

      {userData && (
        <>
          <Divider size="xs" label="User Info" mt="md" />
          <Paper
            style={{
              border: "1px solid #47C44D",
              borderRadius: 8,
              padding: 12,
              marginTop: 8,
            }}
          >
            <Stack gap="sm">
              <Group justify="space-between">
                <Text size="sm" fw={500} c="dimmed" w={150}>
                  CIF Number:
                </Text>
                <Text size="md">{userData.customer_no}</Text>
              </Group>
              <Group justify="space-between">
                <Text size="sm" fw={500} c="dimmed">
                  User Created :
                </Text>
                <Text size="md">
                  {new Date(userData.created_at).toLocaleString()}
                </Text>
              </Group>
              <Group justify="space-between">
                <Text size="sm" fw={500} c="dimmed">
                  User Status:
                </Text>
                <Text size="md" c="green">
                  Active
                </Text>
              </Group>
              <Group justify="space-between">
                <Text size="sm" fw={500} c="dimmed">
                  User Registered Status:
                </Text>
                <Text
                  size="md"
                  c={userData.is_first_login ? "orange" : "green"}
                >
                  {userData.is_first_login
                    ? "Not Registered"
                    : "Registered"}
                </Text>
              </Group>
            </Stack>
          </Paper>

          <Divider label="Rights" size="xs" mt="md" />
          <Paper
            style={{
              border: "1px solid #47C44D",
              borderRadius: 8,
              padding: 12,
              marginTop: 8,
            }}
          >
            <Stack gap="sm" mt="sm">
              <Group justify="space-between">
                <Text size="sm" fw={500} c="dimmed" w={150}>
                  Internet Banking Rights:
                </Text>
                <Text size="md">
                  {userData.ibAccess === "1"
                    ? "Transaction Mode"
                    : userData.ibAccess === "2"
                      ? "Read Mode"
                      : "Not Declared"}
                </Text>
              </Group>
              <Group justify="space-between">
                <Text size="sm" fw={500} c="dimmed" w={150}>
                  Mobile Banking Rights:
                </Text>
                <Text size="md">
                  {userData.mbAccess === "1"
                    ? "Transaction Mode"
                    : userData.mbAccess === "2"
                      ? "Read Mode"
                      : "Not Declared"}
                </Text>
              </Group>
            </Stack>
          </Paper>
        </>
      )}
    </Box>
  );
}
