import React from "react";

import { Document, Page, Text, View, StyleSheet } from "@react-pdf/renderer";
import { SHOP_INFO } from "@/Utils/constants";
/** ====== A4 exact-ish replica ====== */
const ROWS = 13; // how many empty table rows
const ROW_HEIGHT = 20; // fixed row height to make lines uniform

const styles = StyleSheet.create({
    page: {
        paddingTop: 20,
        paddingHorizontal: 24,
        paddingBottom: 22,
        fontFamily: "Helvetica",
        fontSize: 10,
    },
    dotValue: {
        position: "absolute",
        width: "100%",
        fontSize: 9,
        bottom: 1,
    },

    // Header
    brand: {
        fontSize: 18,
        textAlign: "center",
        fontFamily: "Times-Bold",
        letterSpacing: 0.3,
    },
    formTitle: {
        fontSize: 11,
        textAlign: "center",
        marginTop: 4,
        marginBottom: 12,
        fontFamily: "Helvetica-Bold",
    },

    // Two-column meta (left long list + short right list)
    metaRow: { flexDirection: "row", gap: 10, marginBottom: 2 },
    leftMeta: { flex: 2, paddingRight: 8 },
    rightMeta: { flex: 1, paddingLeft: 10 },

    fieldRow: {
        flexDirection: "row",
        alignItems: "center",
        marginBottom: 5,
    },
    label: { width: 140 },
    rightLabel: { width: 80 },
    colon: { width: 8, textAlign: "center" },
    dotted: {
        flex: 1,
        borderBottomWidth: 1,
        borderStyle: "dashed",
        borderBottomColor: "#000",
        paddingTop: 6,
        position: "relative",
    },
    totalRow: {
        flexDirection: "row",
        alignItems: "center",
        marginTop: 3,
        marginBottom: 8,
    },
    totalLabel: { width: 140, fontFamily: "Helvetica-Bold" },

    // Section caption
    sectionCaption: {
        textAlign: "center",
        marginTop: 4,
        marginBottom: 5,
        fontFamily: "Helvetica-Bold",
    },

    // Main grid + right remark panel
    frame: { borderWidth: 1, borderColor: "#000" },
    splitRow: { flexDirection: "row" },
    leftTable: { flex: 1, borderRightWidth: 1, borderColor: "#000" },

    tableHead: {
        flexDirection: "row",
        backgroundColor: "#f5f5f5",
        borderBottomWidth: 1,
        borderColor: "#000",
        textAlign: "center",
    },
    th: {
        paddingVertical: 5,
        paddingHorizontal: 6,
        fontFamily: "Helvetica-Bold",
        borderRightWidth: 1,
        borderColor: "#000",
    },
    cDate: { width: 76 },
    cTaka: { width: 94 },
    cPaidBy: { flex: 1, borderRightWidth: 0 },

    tr: { flexDirection: "row", borderBottomWidth: 1, borderColor: "#000" },
    td: {
        height: ROW_HEIGHT,
        paddingHorizontal: 6,
        justifyContent: "center",
        borderRightWidth: 1,
        borderColor: "#000",
        textAlign: "center",
        paddingTop: 4,
        fontSize: 9,
    },
    tdLast: { borderRightWidth: 0 },

    // Right vertical remark block
    rightPanel: { width: 166 }, // slightly wider to match photo
    rightHead: {
        padding: 5,
        fontFamily: "Helvetica-Bold",
        backgroundColor: "#f5f5f5",
        borderBottomWidth: 1,
        borderColor: "#000",
        textAlign: "center",
    },
    rItem: {
        flexDirection: "row",
        alignItems: "center",
        borderBottomWidth: 1,
        borderColor: "#000",
    },
    rKey: { width: 92, padding: 6 },
    rVal: {
        flex: 1,
        paddingHorizontal: 6,
        height: 26,
        justifyContent: "center",
    },
    rDotted: {
        borderBottomWidth: 1,
        borderStyle: "dashed",
        borderBottomColor: "#000",
    },

    opinionHead: {
        padding: 6,
        fontFamily: "Helvetica-Bold",

        borderBottomWidth: 1,
        borderColor: "#000",
    },
    opinionBox: { height: 130, borderBottomWidth: 1, borderColor: "#000" },

    // Footer signatures
    footer: {
        marginTop: 18,
        flexDirection: "row",
        justifyContent: "space-between",
    },
    foot: { width: "31%", alignItems: "center" },
    footLine: {
        marginTop: 24,
        width: "100%",
        borderTopWidth: 1,
        borderColor: "#000",
        paddingTop: 3,
        textAlign: "center",
    },
});

export default function SalesPersonSalaryStatementPDF({ searchData }) {

    const headerStyles = StyleSheet.create({
        wrap: { alignItems: "center", marginBottom: 8 },
        title: {
            fontSize: 16, // adjust to 19–20 if you want larger
            fontFamily: "Helvetica-Bold", // or "Times-Bold" if you prefer serif
            textTransform: "uppercase",
            marginBottom: 2, // tight gap like the sample
        },
        subline: {
            fontSize: 10,
            lineHeight: 1.25, // compact lines
        },
        hr: { height: 1, backgroundColor: "#000", width: "100%", marginTop: 6 },
    });
    let preparedMoveLeftNameAndMonth = {
        Name:
            searchData?.salesPerson?.name +
            " (" +
            searchData?.salesPerson?.code +
            ")",
        Month: searchData?.startMonth,
    };
    let preparedMoveLeftOther = searchData?.expenseByCategory?.reduce(
        (acc, item) => {
            acc[item.category_name] = item.total_amount;
            return acc;
        },
        {}
    );
    let preparedMoveRight = {
        ...preparedMoveLeftNameAndMonth,
        ...preparedMoveLeftOther,
    };

    let totalExpanse = searchData?.expenseByCategory?.reduce((acc, item) => {
        return acc + Number(item.total_amount || 0);
    }, 0);

    let totalCollection = searchData?.customerPaymentCollection?.reduce(
        (acc, item) => {
            return acc + Number(item.payment || 0);
        },
        0
    );
    let finalPreparedCollection = {
        "Target Amount": "",
        "Sales amount": `${searchData?.salesTotal ?? 0}`,
        "Collection Amount": totalCollection,
        "Achievement %": "",
    };

    /* ------- Parts ------- */
    const MetaLeft = () => (
        <View>
            {Object.entries(preparedMoveRight).map((t, i) => (
                <View style={styles.fieldRow} key={i}>
                    <Text style={styles.label}>{t[0]}</Text>
                    <Text style={styles.colon}>:</Text>
                    <View style={styles.dotted}>
                        <Text style={styles.dotValue}>{t[1]}</Text>
                    </View>
                </View>
            ))}
            <View style={styles.totalRow}>
                <Text style={[styles.totalLabel]}>Total</Text>
                <Text style={styles.colon}>:</Text>
                <View style={styles.dotted}>
                    <Text
                        style={[
                            styles.dotValue,
                            { fontFamily: "Helvetica-Bold" },
                        ]}
                    >
                        {totalExpanse}
                    </Text>
                </View>
            </View>
        </View>
    );

    const MetaRight = () => (
        <View>
            {["Meeting Date", "Area"].map((t, i) => (
                <View style={styles.fieldRow} key={i}>
                    <Text style={styles.rightLabel}>{t}</Text>
                    <Text style={styles.colon}>:</Text>

                    <View style={styles.dotted} />
                </View>
            ))}
        </View>
    );

    const EmptyRows = ({ count = ROWS }) => (
        <>
            {searchData?.customerPaymentCollection?.map((item, i) => (
                <View style={styles.tr} key={i}>
                    <Text style={[styles.td, styles.cDate]}>
                        {" "}
                        {new Date(item.date).toLocaleDateString("en-US")}{" "}
                    </Text>
                    <Text style={[styles.td, styles.cTaka]}>
                        {item.payment}
                    </Text>

                    <Text style={[styles.td, styles.cPaidBy, styles.tdLast]}>
                        {item.payment_type}
                    </Text>
                </View>
            ))}
        </>
    );

    const ReportHeading = () => (
        <View style={headerStyles.wrap}>
            <Text style={headerStyles.title}>{SHOP_INFO.name}</Text>
            <Text style={headerStyles.subline}>{SHOP_INFO.address}</Text>
            <Text style={headerStyles.subline}>
                {SHOP_INFO.phone ? `Phone: ${SHOP_INFO.phone}  |` : ""}
                {SHOP_INFO.email ? ` Email: ${SHOP_INFO.email}` : ""}
            </Text>
            {/* optional divider under the header */}
            <View style={headerStyles.hr} />
        </View>
    );
    return (
        <Document>
            <Page size="A4" style={styles.page}>
                <View>
                    <ReportHeading />
                    <Text style={styles.formTitle}>
                        Sales Person Salary Statement
                    </Text>
                </View>

                <View style={styles.metaRow}>
                    <View style={styles.leftMeta}>
                        <MetaLeft />
                    </View>
                    <View style={styles.rightMeta}>
                        <MetaRight />
                    </View>
                </View>

                <Text style={styles.sectionCaption}>
                    Collection and Paid Date
                </Text>

                <View style={styles.frame}>
                    <View style={styles.splitRow}>
                        {/* Left grid */}
                        <View style={styles.leftTable}>
                            <View style={styles.tableHead}>
                                <Text style={[styles.th, styles.cDate]}>
                                    Date
                                </Text>
                                <Text style={[styles.th, styles.cTaka]}>
                                    Taka
                                </Text>
                                <Text style={[styles.th, styles.cPaidBy]}>
                                    Paid By
                                </Text>
                            </View>
                            <EmptyRows />
                        </View>

                        {/* Right panel */}
                        <View style={styles.rightPanel}>
                            <Text style={styles.rightHead}>Remark</Text>
                            {Object.entries(finalPreparedCollection).map(
                                (k, i) => (
                                    <View style={styles.rItem} key={i}>
                                        <Text style={styles.rKey}>{k[0]}</Text>
                                        <Text style={styles.colon}>:</Text>
                                        <View>
                                            <Text>{k[1]}</Text>
                                        </View>
                                    </View>
                                )
                            )}
                            <Text style={styles.opinionHead}>Any Opinion</Text>
                            <View style={styles.opinionBox} />
                        </View>
                    </View>
                </View>

                {/* Footer */}
                <View style={styles.footer}>
                    <View style={styles.foot}>
                        <Text style={styles.footLine}>Prepare By</Text>
                    </View>
                    <View style={styles.foot}>
                        <Text style={styles.footLine}>Checked By Accounts</Text>
                    </View>
                    <View style={styles.foot}>
                        <Text style={styles.footLine}>Marketing Manager</Text>
                    </View>
                </View>
            </Page>
        </Document>
    );
}
