"use client";

import React, { useEffect, useState } from "react";
import {
    Group,
    Paper,
    Select,
    Stack,
    Text,
    Title,
} from "@mantine/core";
import { notifications } from "@mantine/notifications";
import { useRouter } from "next/navigation";
import { useSearchParams } from "next/navigation";

interface accountData {
    stAccountNo: string;
    stAccountType: string;
    stAvailableBalance: string;
    custname: string;
    stBookingNumber: string;
    stApprovedAmount?: string; // optional for loan accounts
}

export default function AccountDetails() {
    const router = useRouter();
    const [accountOptions, setAccountOptions] = useState<{ value: string; label: string }[]>([]);
    const [selectedAccNo, setSelectedAccNo] = useState<string | null>(null);
    const [authorized, setAuthorized] = useState<boolean | null>(null);
    const [accountDetails, setAccountDetails] = useState<accountData | null>(null);
    const searchParams = useSearchParams();
    const passedAccNo = searchParams.get("accNo");

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

    useEffect(() => {
        if (authorized) {
            const saved = sessionStorage.getItem("accountData");
            if (saved) {
                const parsed: accountData[] = JSON.parse(saved);
                const options = parsed.map((acc) => ({
                    label: `${acc.stAccountNo} - ${acc.stAccountType}`,
                    value: acc.stAccountNo,
                }));
                setAccountOptions(options);
                if (passedAccNo) {
                    handleAccountSelection(passedAccNo);
                }
            }
        }
    }, [authorized]);

    const handleAccountSelection = async (accNo: string | null) => {
        setSelectedAccNo(accNo);
        setAccountDetails(null);
        if (!accNo) return;
        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: accountData[] = await response.json();
            if (response.ok && Array.isArray(data)) {
                const matched = data.find((acc) => acc.stAccountNo === accNo);
                if (matched) {
                    // Simulate approvedBalance for loan accounts
                    if (matched.stAccountType.toUpperCase().includes("LN")) {
                        matched.stApprovedAmount = (
                            parseFloat(matched.stAvailableBalance) + 20000
                        ).toFixed(2); // dummy logic
                    }
                    setAccountDetails(matched);
                } else {
                    notifications.show({
                        withBorder: true,
                        color: "orange",
                        title: "Account not found",
                        message: "Selected account was not found in the response.",
                    });
                }
            } else {
                throw new Error("Invalid response");
            }
        } catch (err) {
            notifications.show({
                withBorder: true,
                color: "red",
                title: "Fetch failed",
                message: "Could not fetch account details. Try again.",
            });
        }
    };

    if (!authorized) return null;

    return (
        <Paper shadow="sm" radius="md" p="md" withBorder h={400}>
            <Title order={3} mb="md">
                Account Details
            </Title>

            <Stack gap="md">
                <Select
                    label="Select Account Number"
                    placeholder="Choose account number"
                    data={accountOptions}
                    value={selectedAccNo}
                    onChange={handleAccountSelection}
                    searchable
                />

                {accountDetails && (
                    <Paper withBorder p="md" radius="md" bg="gray.0">
                        <Stack gap="sm">
                            <Group p="apart">
                                <Text size="sm" fw={500} c="dimmed">Account Number</Text>
                                <Text size="md">{accountDetails.stAccountNo}</Text>
                            </Group>

                            <Group p="apart">
                                <Text size="sm" fw={500} c="dimmed">Account Type</Text>
                                <Text size="md">{accountDetails.stAccountType}</Text>
                            </Group>

                            <Group p="apart">
                                <Text size="sm" fw={500} c="dimmed">Description</Text>
                                <Text size="md">{accountDetails.stBookingNumber}</Text>
                            </Group>

                            {/* Show Loan-specific fields */}
                            {accountDetails.stAccountType.toUpperCase().includes("LN") ? (
                                <>
                                    <Group p="apart">
                                        <Text size="sm" fw={500} c="dimmed">Approved Balance</Text>
                                        <Text size="md" c="gray.8">
                                            ₹{parseFloat(accountDetails.stApprovedAmount || "0").toLocaleString("en-IN", {
                                                minimumFractionDigits: 2,
                                            })}
                                        </Text>
                                    </Group>
                                    <Group p="apart">
                                        <Text size="sm" fw={500} c="dimmed">Available Balance</Text>
                                        <Text size="md" c="red">
                                            – ₹{parseFloat(accountDetails.stAvailableBalance).toLocaleString("en-IN", {
                                                minimumFractionDigits: 2,
                                            })}
                                        </Text>
                                    </Group>
                                </>
                            ) : (
                                <Group p="apart">
                                    <Text size="sm" fw={500} c="dimmed">Available Balance</Text>
                                    <Text size="md" c="green">
                                        ₹{parseFloat(accountDetails.stAvailableBalance).toLocaleString("en-IN", {
                                            minimumFractionDigits: 2,
                                        })}
                                    </Text>
                                </Group>
                            )}
                        </Stack>
                    </Paper>
                )}
            </Stack>
        </Paper>
    );
}
