"use client";

import React, { useEffect, useState } from "react";
import { Center, Group, Loader, Paper, ScrollArea, Table, Text, Title } from "@mantine/core";
import { notifications } from "@mantine/notifications";
import { useRouter } from "next/navigation";
import Image from "next/image";
import { getBankLogo } from "@/app/_util/getBankLogo";
import { IconTrash } from "@tabler/icons-react";

interface Beneficiary {
    accountNo: string;
    name: string;
    accountType: string;
    ifscCode: string;
    bankName: string;
    branchName: string;
}

export default function ViewBeneficiary() {
    const router = useRouter();
    const [authorized, setAuthorized] = useState<boolean | null>(null);
    const [beneficiaries, setBeneficiaries] = useState<Beneficiary[]>([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        const token = localStorage.getItem("access_token");
        if (!token) {
            setAuthorized(false);
            router.push("/login");
        } else {
            setAuthorized(true);
        }
    }, []);
    useEffect(() => {
        const fetchBeneficiaries = async () => {
            try {
                const token = localStorage.getItem("access_token");
                const response = await fetch(`/api/beneficiary`, {
                    method: "GET",
                    headers: {
                        "Content-Type": "application/json",
                        Authorization: `Bearer ${token}`,
                    },
                });
                if (!response.ok) throw new Error("Failed to fetch beneficiaries");
                const data = await response.json();
                setBeneficiaries(data);
            } catch (error) {
                notifications.show({
                    title: "Error",
                    message: "Unable to fetch beneficiaries. Please try again later.",
                    color: "red",
                });
            } finally {
                setLoading(false);
            }
        };
        fetchBeneficiaries();
    }, []);

    if (loading) {
        return (
            <Center h="60vh">
                <Loader size="lg" color="green" />
            </Center>
        );
    }

    if (!authorized) return null;
    return (
        <Paper shadow="sm" radius="md" p="md" withBorder h={400}>
            <Title order={3} mb="md">My Beneficiaries</Title>
            {beneficiaries.length === 0 ? (
                <Text>No beneficiaries found.</Text>
            ) : (
                <ScrollArea h={300} type="always">
                    <Table highlightOnHover withTableBorder stickyHeader style={{ borderCollapse: "collapse", width: "100%" }}>
                        <Table.Thead>
                            <Table.Tr style={{ backgroundColor: "#3385ff" }}>
                                <Table.Th>Bank</Table.Th>
                                <Table.Th style={{ textAlign: "right" }}>Account No</Table.Th>
                                <Table.Th>Name</Table.Th>
                                <Table.Th>Type</Table.Th>
                                <Table.Th style={{ textAlign: "center" }}>IFSC</Table.Th>
                                <Table.Th style={{ textAlign: "center" }}>Action Icon</Table.Th>
                            </Table.Tr>
                        </Table.Thead>
                        <Table.Tbody>
                            {beneficiaries.map((b, i) => (
                                <Table.Tr key={i}>
                                    <Table.Td>
                                        <Group gap='sm'>
                                            <Image
                                                // src={getBankLogo(b.bankName) ??logo}
                                                src={getBankLogo(b.bankName)}
                                                alt={b.bankName}
                                                width={20}
                                                height={15}
                                            />
                                            {b.bankName}
                                        </Group>
                                    </Table.Td>
                                    <Table.Td style={{ textAlign: "right" }}>{b.accountNo}</Table.Td>
                                    <Table.Td>{b.name}</Table.Td>
                                    <Table.Td>{b.accountType}</Table.Td>
                                    <Table.Td style={{ textAlign: "center" }}>{b.ifscCode}</Table.Td>
                                    <Table.Td style={{ textAlign: "center" }}><IconTrash color="red" /></Table.Td>
                                </Table.Tr>
                            ))}
                        </Table.Tbody>
                    </Table>
                </ScrollArea>
            )}
        </Paper >
    );
}
