"use client";

import { DocumentTextIcon, ArrowDownTrayIcon } from '@heroicons/react/24/outline';
import api from '../../lib/api';

const reports = [
    {
        id: 1,
        name: 'Executive Summary',
        description: 'High-level overview of security posture, trends, and key risks for management.',
        date: '2023-10-27',
        format: 'PDF'
    },
    {
        id: 2,
        name: 'Technical Vulnerability Report',
        description: 'Detailed list of all detected vulnerabilities, affected assets, and remediation steps.',
        date: new Date().toISOString().split('T')[0],
        format: 'CSV'
    },
    {
        id: 3,
        name: 'Compliance Audit (ISO 27001)',
        description: 'Audit report mapping current vulnerabilities against ISO 27001 controls.',
        date: '2023-10-26',
        format: 'PDF'
    },
    {
        id: 4,
        name: 'Patching Progress',
        description: 'Track remediation efforts over the last 30 days.',
        date: '2023-10-25',
        format: 'PDF'
    }
];

export default function ReportsPage() {
    const handleDownload = async (report: any) => {
        if (report.id === 2) {
            try {
                const response = await api.get('/api/v1/reports/vulnerabilities/csv', { responseType: 'blob' });
                const url = window.URL.createObjectURL(new Blob([response.data]));
                const link = document.createElement('a');
                link.href = url;
                link.setAttribute('download', `vulnerabilities_report_${new Date().toISOString().split('T')[0]}.csv`);
                document.body.appendChild(link);
                link.click();
                link.remove();
            } catch (e) {
                console.error(e);
                alert("Failed to download report. Please ensure you are logged in.");
            }
        } else if (report.id === 1) {
            try {
                const response = await api.get('/api/v1/reports/executive-summary/pdf', { responseType: 'blob' });
                const url = window.URL.createObjectURL(new Blob([response.data]));
                const link = document.createElement('a');
                link.href = url;
                link.setAttribute('download', `executive_summary_${new Date().toISOString().split('T')[0]}.pdf`);
                document.body.appendChild(link);
                link.click();
                link.remove();
            } catch (e) {
                console.error(e);
                alert("Failed to generate PDF report.");
            }
        } else if (report.id === 3) {
            try {
                const response = await api.get('/api/v1/reports/compliance/iso27001/pdf', { responseType: 'blob' });
                const url = window.URL.createObjectURL(new Blob([response.data]));
                const link = document.createElement('a');
                link.href = url;
                link.setAttribute('download', `compliance_audit_${new Date().toISOString().split('T')[0]}.pdf`);
                document.body.appendChild(link);
                link.click();
                link.remove();
            } catch (e) {
                console.error(e);
                alert("Failed to generate Compliance report.");
            }
        } else if (report.id === 4) {
            try {
                const response = await api.get('/api/v1/reports/patching-progress/pdf', { responseType: 'blob' });
                const url = window.URL.createObjectURL(new Blob([response.data]));
                const link = document.createElement('a');
                link.href = url;
                link.setAttribute('download', `patching_progress_${new Date().toISOString().split('T')[0]}.pdf`);
                document.body.appendChild(link);
                link.click();
                link.remove();
            } catch (e) {
                console.error(e);
                alert("Failed to generate Patching Progress report.");
            }
        } else {
            alert(`Report generation for ${report.name} is coming soon!`);
        }
    };

    return (
        <div className="max-w-7xl mx-auto">
            <div className="mb-8">
                <h2 className="text-3xl font-bold leading-7 text-gray-900 font-mono">
                    Reports & Analytics
                </h2>
                <p className="mt-1 text-sm text-gray-500 font-mono">Generate and download security reports</p>
            </div>

            <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
                {reports.map((report) => (
                    <div key={report.id} className="relative flex flex-col bg-white border border-gray-200 rounded-sm shadow-sm p-6 hover:shadow-md transition-shadow">
                        <div className="flex items-center gap-4 mb-4">
                            <div className="p-3 bg-blue-50 rounded-lg">
                                <DocumentTextIcon className="h-6 w-6 text-vulncheck-blue" />
                            </div>
                            <div>
                                <h3 className="text-base font-bold text-gray-900 font-mono">{report.name}</h3>
                                <p className="text-xs text-gray-500 font-mono">Generated: {report.date}</p>
                            </div>
                        </div>
                        <p className="text-sm text-gray-600 mb-6 flex-grow font-mono">{report.description}</p>
                        <div className="flex items-center justify-between pt-4 border-t border-gray-100">
                            <span className="inline-flex items-center rounded-md bg-gray-50 px-2 py-1 text-xs font-medium text-gray-600 ring-1 ring-inset ring-gray-500/10">
                                {report.format}
                            </span>
                            <button
                                onClick={() => handleDownload(report)}
                                className="flex items-center gap-2 text-sm font-semibold text-vulncheck-blue hover:text-blue-700"
                            >
                                <ArrowDownTrayIcon className="h-4 w-4" />
                                Download
                            </button>
                        </div>
                    </div>
                ))}
            </div>
        </div>
    );
}
