import * as React from "react";
import * as HttpUtils from "utils/HttpUtils";
import * as DateUtils from "utils/DateUtils";
import * as UrlUtils from "utils/ApiPathConst";

import {
    Grid, Typography, Button,
    Stack, Box, CircularProgress,
} from '@mui/material';
import { notifyActionError } from 'utils/CommonFunction';

import titleBackgroundImg from 'assets/images/dashboard/gazette-bar.png'

const formatEncryptLog = (responData) => {
    if (responData?.msg && !responData?.log) {
        return <>{DateUtils.datetimeStr(new Date())}<br/><span style={{ color: "red" }}>Error</span><br/>{responData.msg}</>;
    }
    const statusColor = responData?.success ? "green" : "red";
    const statusText = responData?.success ? "Success" : "Completed with errors";
    const logText = (responData?.log || []).join("\n");
    return (
        <>
            {DateUtils.datetimeStr(new Date())}<br/>
            <span style={{ color: statusColor }}>{responData?.dryRun ? "Dry-run " : ""}{statusText}</span><br/>
            Total: {responData?.total ?? 0}, OK: {responData?.successCount ?? 0}, Skipped: {responData?.skipped ?? 0}, Failed: {responData?.failed ?? 0}<br/>
            <span style={{ whiteSpace: "pre-line" }}>{logText}</span>
        </>
    );
};

const formatVerifyLog = (responData) => {
    const tests = responData?.tests || [];
    const logText = tests.map(t => `${t.passed ? "PASS" : "FAIL"} - ${t.name}: ${t.message}`).join("\n");
    const statusColor = responData?.success ? "green" : "red";
    return (
        <>
            {DateUtils.datetimeStr(new Date())}<br/>
            <span style={{ color: statusColor }}>{responData?.success ? "All tests passed" : "Some tests failed"}</span><br/>
            Passed: {responData?.passed ?? 0}, Failed: {responData?.failed ?? 0}<br/>
            <span style={{ whiteSpace: "pre-line" }}>{logText}</span>
        </>
    );
};

const UserPiiEncryption = () => {
    const [resultStr, setResultStr] = React.useState("");
    const [wait, setWait] = React.useState(false);

    const BackgroundHead = {
        backgroundImage: `url(${titleBackgroundImg})`,
        width: 'auto',
        height: 'auto',
        backgroundSize: 'contain',
        backgroundRepeat: 'no-repeat',
        backgroundColor: '#0C489E',
        backgroundPosition: 'right'
    };

    const runEncrypt = (dryRun) => {
        setWait(true);
        HttpUtils.post({
            url: `${UrlUtils.USER_PII_ENCRYPT_MIGRATION}?dryRun=${dryRun}&batchSize=100`,
            params: {},
            onSuccess: function (responData) {
                setWait(false);
                setResultStr(formatEncryptLog(responData));
            },
            onError: function () {
                setWait(false);
                notifyActionError("User PII encryption failed");
            }
        });
    };

    const runVerify = () => {
        setWait(true);
        HttpUtils.post({
            url: UrlUtils.USER_PII_VERIFY_MIGRATION,
            params: {},
            onSuccess: function (responData) {
                setWait(false);
                setResultStr(formatVerifyLog(responData));
            },
            onError: function () {
                setWait(false);
                notifyActionError("User PII verification failed");
            }
        });
    };

    return (
        <Grid container sx={{ minHeight: '87vh', backgroundColor: "backgroundColor.default" }} direction="column">
            <Grid item xs={12}>
                <div style={BackgroundHead}>
                    <Stack direction="row" height='70px' justifyContent="space-between" alignItems="center">
                        <Typography ml={15} color='#FFF' variant="h4" sx={{ textShadow: "0px 0px 25px #0C489E" }}>
                            User Fields Encryption
                        </Typography>
                    </Stack>
                </div>
            </Grid>

            <Grid item xs={12} sx={{ backgroundColor: '#ffffff', ml: 2, mt: 1 }} width="98%">
                <Box sx={{ borderRadius: '10px', backgroundColor: '#fff', p: 4 }}>
                    <Typography variant="body1" sx={{ mb: 2 }}>
                        Encrypt enName, chName, mobileNumber, and address for existing user records, then verify data retrieval.
                    </Typography>
                    <Stack direction="row" spacing={2} flexWrap="wrap">
                        <Button variant="outlined" size="large" disabled={wait} onClick={() => runEncrypt(true)}>
                            Dry Run Encrypt
                        </Button>
                        <Button variant="contained" size="large" disabled={wait} onClick={() => runEncrypt(false)}>
                            Run Encrypt
                        </Button>
                        <Button variant="contained" color="secondary" size="large" disabled={wait} onClick={runVerify}>
                            Verify Retrieval
                        </Button>
                        {wait ? <CircularProgress size={32} /> : null}
                    </Stack>
                </Box>
            </Grid>

            <Grid item xs={12} sx={{ backgroundColor: '#ffffff', ml: 2, mt: 1, mb: 2 }} width="98%">
                <Box sx={{ borderRadius: '10px', backgroundColor: '#fff', p: 4 }}>
                    <Typography variant="h4">Result:</Typography>
                    <Box sx={{ pl: 2, pt: 2 }}>{resultStr}</Box>
                </Box>
            </Grid>
        </Grid>
    );
};

export default UserPiiEncryption;
