import React from 'react';
import superagent from 'superagent';

import { Segment, Header, Message, Icon, Table } from 'semantic-ui-react'
import ApiButtonModal from '../../../CloudApi/ApiButtonModal.jsx';

export default class AccountGDPRScanDeletion extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            dryRunResults: null,
            deletionResults: null,
            error: null
        };
    }

    async onDryRunDeletion() {
        this.setState({ loading: true, error: null, dryRunResults: null });
        try {
            const res = await superagent
                .delete(`/api/admin/fabricator/account/${this.props.account.id}/scan_data?dryRun=1`)
                .accept('json');

            console.log('Dry run results:', res.body);
            this.setState({
                dryRunResults: res.body,
                loading: false
            });
        } catch (e) {
            console.error('Dry run error:', e);
            this.setState({
                error: e.response?.body?.message || 'Failed to perform dry run',
                loading: false
            });
        }
    }

    async onDeleteScanData() {
        this.setState({ loading: true, error: null, deletionResults: null });
        try {
            const res = await superagent
                .delete(`/api/admin/fabricator/account/${this.props.account.id}/scan_data`)
                .accept('json');

            console.log('Deletion results:', res.body);
            this.setState({
                deletionResults: res.body,
                loading: false,
                dryRunResults: null
            });
        } catch (e) {
            console.error('Deletion error:', e);
            this.setState({
                error: e.response?.body?.message || 'Failed to delete scan data',
                loading: false
            });
        }
    }

    renderResultsTable(results, title) {
        if (!results) return null;

        const { scanRequests, scans } = results;

        return (
            <Segment>
                <Header as="h4">{title}</Header>

                {scanRequests && (
                    <div style={{ marginBottom: '20px' }}>
                        <Header as="h5">
                            Scan Requests: {scanRequests.items.length || 0} found
                        </Header>
                        {scanRequests.items && scanRequests.items.length > 0 && (
                            <Table celled compact>
                                <Table.Header>
                                    <Table.Row>
                                        <Table.HeaderCell>ID</Table.HeaderCell>
                                        <Table.HeaderCell>Created</Table.HeaderCell>
                                        <Table.HeaderCell>Status</Table.HeaderCell>
                                    </Table.Row>
                                </Table.Header>
                                <Table.Body>
                                    {scanRequests.items.slice(0, 25).map((item, idx) => (
                                        <Table.Row key={idx}>
                                            <Table.Cell>{item.id}</Table.Cell>
                                            <Table.Cell>{item.createdAt ? new Date(item.createdAt).toLocaleString() : 'N/A'}</Table.Cell>
                                            <Table.Cell>{item.scanRequestState || 'N/A'}</Table.Cell>
                                        </Table.Row>
                                    ))}
                                </Table.Body>
                            </Table>
                        )}
                        {scanRequests.items && scanRequests.items.length > 25 && (
                            <Message info>Showing first 25 of {scanRequests.items.length} scan requests</Message>
                        )}
                    </div>
                )}

                {scans && (
                    <div>
                        <Header as="h5">
                            Scans: {scans.items.length || 0} found
                        </Header>
                        {scans.items && scans.items.length > 0 && (
                            <Table celled compact>
                                <Table.Header>
                                    <Table.Row>
                                        <Table.HeaderCell>ID</Table.HeaderCell>
                                        <Table.HeaderCell>Created</Table.HeaderCell>
                                        <Table.HeaderCell>Status</Table.HeaderCell>
                                    </Table.Row>
                                </Table.Header>
                                <Table.Body>
                                    {scans.items.slice(0, 25).map((item, idx) => (
                                        <Table.Row key={idx}>
                                            <Table.Cell>{item.id}</Table.Cell>
                                            <Table.Cell>{item.createdAt ? new Date(item.createdAt).toLocaleString() : 'N/A'}</Table.Cell>
                                            <Table.Cell>{item.status || 'N/A'}</Table.Cell>
                                        </Table.Row>
                                    ))}
                                </Table.Body>
                            </Table>
                        )}
                        {scans.items && scans.items.length > 25 && (
                            <Message info>Showing first 25 of {scans.items.length} scans</Message>
                        )}
                    </div>
                )}
            </Segment>
        );
    }

    render() {
        return (
            <div>
                <Header as="h2">
                    GDPR Scan Data Deletion
                    <Header.Subheader>Permanently delete all scan data for this customer account</Header.Subheader>
                </Header>

                {this.state.error && (
                    <Message negative>
                        <Message.Header>Error</Message.Header>
                        <p>{this.state.error}</p>
                    </Message>
                )}

                <Segment>
                    <Header as="h3">
                        <Icon name="search" />
                        Step 1: Dry Run
                    </Header>
                    <p>
                        First, perform a dry run to see what scan data will be deleted without actually deleting it.
                        This will show you all scan requests and scans that would be affected.
                    </p>

                    <ApiButtonModal
                        color="blue"
                        icon="search"
                        text="Delete All Customer Scan Data (Dry Run)"
                        modalIcon="info circle"
                        modalButtonText="Start Dry Run of Scan Deletion"
                        onConfirm={this.onDryRunDeletion.bind(this)}>
                        <Message warning icon>
                            <Icon name="info circle" />
                            <Message.Content>
                                <Message.Header>Dry Run Mode</Message.Header>
                                This will query all scan data for account <strong>{this.props.account.username || this.props.account.id}</strong> without deleting anything.
                                You will see a preview of what would be deleted.
                            </Message.Content>
                        </Message>
                    </ApiButtonModal>

                    {this.state.dryRunResults && this.renderResultsTable(
                        this.state.dryRunResults,
                        'Dry Run Results - Data that would be deleted:'
                    )}
                </Segment>

                <Segment>
                    <Header as="h3">
                        <Icon name="warning sign" color="red" />
                        Step 2: Permanent Deletion
                    </Header>
                    <Message warning icon>
                        <Icon name="warning sign" />
                        <Message.Content>
                            <Message.Header>Warning: This action is permanent</Message.Header>
                            This will permanently delete all scan data for this customer. This action cannot be undone.
                        </Message.Content>
                    </Message>

                    <ApiButtonModal
                        color="red"
                        icon="trash"
                        text="Delete All Customer Scan Data"
                        modalIcon="warning sign"
                        modalButtonText="Start Scan Deletion"
                        onConfirm={this.onDeleteScanData.bind(this)}>
                        <Message error icon>
                            <Icon name="warning sign" />
                            <Message.Content>
                                <Message.Header>Permanent Deletion Warning</Message.Header>
                                Are you absolutely sure you want to permanently delete all scan data for account <strong>{this.props.account.username || this.props.account.id}</strong>?
                                <br /><br />
                                This will delete:
                                <ul>
                                    <li>All scan requests</li>
                                    <li>All scan data files</li>
                                    <li>All associated metadata</li>
                                </ul>
                                <br />
                                <strong>This action cannot be undone.</strong>
                            </Message.Content>
                        </Message>
                    </ApiButtonModal>

                    {this.state.deletionResults && (
                        <Message success icon>
                            <Icon name="check circle" />
                            <Message.Content>
                                <Message.Header>Deletion Completed Successfully</Message.Header>
                                {this.renderResultsTable(
                                    this.state.deletionResults,
                                    'Deleted Data Summary:'
                                )}
                            </Message.Content>
                        </Message>
                    )}
                </Segment>
            </div>
        );
    }
}
