"use client";

import React, { useEffect, useState } from "react";
import {
    Paper,
    Title,
    Grid,
    Text,
    Anchor,
    Divider,
    Loader,
    Center,
} from "@mantine/core";
import { notifications } from "@mantine/notifications";
import { useRouter } from "next/navigation";

// Response structure from backend
interface ProfileData {
    custname: string;
    cifNumber: string;
    stBranchNo: string;
    custdob: string;
    mobileno: string;
    id: string;
    custaddress: string;
    pincode: string;

}

export default function ViewProfile() {
    const router = useRouter();
    const [profileData, setProfileData] = useState<ProfileData | null>(null);
    const [loading, setLoading] = useState(true);

    // Fetch API with same style as RootLayout
    async function handleFetchProfile() {
        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}`,
                },
            });

            if (!response.ok) {
                notifications.show({
                    withBorder: true,
                    color: "red",
                    title: "Error",
                    message: "Unable to fetch profile details",
                    autoClose: 5000,
                });
                return;
            }

            const data = await response.json();

            // If backend returns array → take first record
            if (Array.isArray(data) && data.length > 0) {
                setProfileData(data[0]);
            }
        } catch (err) {
            notifications.show({
                withBorder: true,
                color: "red",
                title: "Please try again later",
                message: "Something went wrong while fetching profile",
                autoClose: 5000,
            });
        } finally {
            setLoading(false);
        }
    }

    useEffect(() => {
        handleFetchProfile();
    }, []);

    const Row = ({
        label,
        value,
        link,
    }: {
        label: string;
        value: string;
        link?: string;
    }) => (
        <Grid align="flex-start" gutter="xs" mb={6}>
            <Grid.Col span={3}>
                <Text c="dimmed" size="sm" fw={500}>
                    {label}
                </Text>
            </Grid.Col>
            <Grid.Col span={9}>
                {link ? (
                    <Anchor size="sm" href={link} target="_blank" rel="noopener noreferrer">
                        {value}
                    </Anchor>
                ) : (
                    <Text size="sm">{value}</Text>
                )}
            </Grid.Col>
        </Grid>
    );

    return (
        <Paper shadow="xs" radius="md" p="md" withBorder h={400}>
            <Title order={4} mb="sm">
                View Profile
            </Title>
            <Divider mb="sm" />

            {loading ? (
                <Center>
                    <Loader size="sm" />
                </Center>
            ) : profileData ? (
                <>
                    <Row label="Customer ID (CIF)" value={profileData.cifNumber} />
                    <Row label="Customer Name" value={profileData.custname} />
                    <Row label="ID" value={profileData.id} />
                    <Row label="Branch No" value={profileData.stBranchNo} />
                    <Row label="Date of Birth" value={profileData.custdob} />
                    <Row label="Mobile Number" value={profileData.mobileno} />

                    <Row
                        label="Address"
                        value={profileData.custaddress}
                    // link={`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(
                    //     profileData.custaddress
                    // )}`}
                    />
                    <Row label="Pincode" value={profileData.pincode} />

                </>
            ) : (
                <Text c="red" size="sm">
                    No profile data found.
                </Text>
            )}
        </Paper>
    );
}
