import { Col, Row, Spin } from "antd";
import { observer } from "mobx-react";
import { useEffect, useState } from "react";

import { ConsentTableRecordCookiePolicy } from "./cookiePolicy.js";
import { ConsentTableRecordExport } from "./export.js";
import { ConsentTableRecordPreview } from "./preview.js";
import { ConsentTableRecordSettings } from "./settings.js";
import { __ } from "../../../../utils/i18n.js";

import type { Consent } from "../../../../models/consent.js";
import type { ComponentProps, FC } from "react";

const ConsentTableRecordExpand: FC<{
    record: Consent;
    onPreview: ComponentProps<typeof ConsentTableRecordPreview>["onPreview"];
}> = observer(({ record, onPreview }) => {
    const [loaded, setLoaded] = useState(false);
    const { referer, context, viewport_width, viewport_height, forwarded } = record;

    // Ensure to load the revisions of this entry
    useEffect(() => {
        record.fetchRevisions().then(() => {
            setLoaded(true);
        });
    }, [record]);

    return loaded ? (
        <div>
            <div>
                <strong>{__("Viewport (px)")}:</strong> {viewport_width} x {viewport_height}
            </div>
            <div>
                <strong>{__("Viewed page")}:</strong>{" "}
                <a href={referer} rel="noopener noreferrer" target="_blank">
                    {referer}
                </a>
            </div>
            {!!context && (
                <div>
                    <strong>{__("Context")}:</strong> <code>{context}</code>
                </div>
            )}
            <ConsentTableRecordSettings record={record} />
            <Row>
                <Col md={forwarded ? undefined : 12} sm={forwarded ? undefined : 24} span={forwarded ? 24 : undefined}>
                    <div style={{ padding: 10 }}>
                        <ConsentTableRecordPreview record={record} onPreview={onPreview} />
                    </div>
                </Col>
                {!forwarded && (
                    <Col md={12} sm={24}>
                        <div style={{ padding: 10 }}>
                            <ConsentTableRecordExport record={record} />
                        </div>
                        <div style={{ padding: 10 }}>
                            <ConsentTableRecordCookiePolicy record={record} />
                        </div>
                    </Col>
                )}
            </Row>
        </div>
    ) : (
        <Spin spinning />
    );
});

export { ConsentTableRecordExpand };
