import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import Link from 'next/link';
import RegisterDetail from '@/app/registers/RegisterDetail';
import {Container, Row} from "react-bootstrap";
import { getRegisters } from '@/services/register.service';
import {env} from "@/env";
import { buildRegisterSummary } from "@/utils/register_helpers";

export async function generateMetadata({ params }: { params: Promise<{ hex: string }> }): Promise<Metadata> {
    const registers = await getRegisters();
    const { hex } = await params;
    const targetHex = decodeURIComponent(hex).toLowerCase();
    const register = registers.find(r => r.hex_address.toLowerCase() === targetHex);

    if (!register) {
        return {
            title: 'Register Not Found | Spectrum Next Explorer',
            robots: { index: false, follow: false },
        };
    }

    const summary = buildRegisterSummary(register);
    const title = `${register.hex_address} ${register.name} | Spectrum Next Explorer`;
    const imageUrl = `${env.PROTO}://${env.HOSTNAME}/registers/${register.hex_address}/opengraph-image`;

    return {
        title,
        description: summary,
        openGraph: {
            title,
            description: summary,
            type: 'article',
            url: `${env.PROTO}://${env.HOSTNAME}/registers/${register.hex_address}`,
            images: [
                {
                    url: imageUrl,
                    width: 1200,
                    height: 630,
                    alt: `${register.hex_address} ${register.name}`,
                },
            ],
        },
        twitter: {
            card: 'summary_large_image',
            title,
            description: summary,
            images: [imageUrl],
        },
    };
}

export default async function RegisterDetailPage({ params }: { params: Promise<{ hex: string }> }) {
    const registers = await getRegisters();
    const { hex } = await params;
    const targetHex = decodeURIComponent(hex).toLowerCase();

    const register = registers.find(r => r.hex_address.toLowerCase() === targetHex);

    if (!register) return notFound();


    return (
        <Container fluid className="py-4">
            <div className="mb-3">
                <Link href="/registers" className="btn btn-secondary">← Back to Registers</Link>
            </div>
            <Row>
                <RegisterDetail register={register} />
            </Row>
        </Container>
    );
}
