"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, { StaticImageData } from "next/image";
import BOI from '@/app/image/bank_logo/BOI.jpg';
import hdfc from '@/app/image/bank_logo/hdfc.jpg';
import sbi from '@/app/image/bank_logo/sbi.jpg';
import icici from '@/app/image/bank_logo/icici.jpg'
import pnb from '@/app/image/bank_logo/pnb.jpg'
import axis from '@/app/image/bank_logo/axis.jpg'
import kccb from '@/app/image/bank_logo/kccb.jpg'
import logo from '@/app/image/bank_logo/bank.jpg';

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

const bankLogo: Record<string, StaticImageData> = {
    "BANK OF INDIA": BOI,
    "HDFC BANK LTD": hdfc,
    "STATE BANK OF INDIA": sbi,
    "ICICI BANK LTD": icici,
    "PUNJAB NATIONAL BANK": pnb,
    "AXIS BANK": axis,
    "THE KANGRA CENTRAL CO-OP BANK LIMITED": kccb
}

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>Account No</Table.Th>
                                <Table.Th>Name</Table.Th>
                                <Table.Th>Type</Table.Th>
                                <Table.Th>IFSC</Table.Th>
                                {/* <Table.Th>Branch</Table.Th> */}
                            </Table.Tr>
                        </Table.Thead>
                        <Table.Tbody>
                            {beneficiaries.map((b, i) => (
                                <Table.Tr key={i}>
                                    <Table.Td>
                                        <Group gap='sm'>
                                            <Image
                                                src={bankLogo[b.bankName] || logo}
                                                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>{b.branchName}</Table.Td> */}
                                </Table.Tr>
                            ))}
                        </Table.Tbody>
                    </Table>
                </ScrollArea>
            )}
        </Paper >
    );
}
