import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import { Head, router } from '@inertiajs/react';
import { AlertTriangle, ShieldAlert } from 'lucide-react';
import { useState } from 'react';
import { Badge } from '@/Components/ui/badge';
import { Button } from '@/Components/ui/button';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/Components/ui/card';

const CATEGORY_LABELS = {
    sql_injection: 'SQL Injection', xss: 'XSS', csrf: 'CSRF', directory_traversal: 'Directory Traversal',
    clickjacking: 'Clickjacking', open_redirect: 'Open Redirect', cors_misconfiguration: 'CORS Misconfiguration',
    security_headers: 'Security Headers', sensitive_file_exposure: 'Sensitive File Exposure',
    cve_detection: 'Known CVE Detection', tech_vulnerability_matching: 'Tech Vulnerability Matching',
    tls_config: 'TLS Configuration', cookie_security: 'Cookie Security', rate_limit_detection: 'Rate Limiting',
    subdomain_discovery: 'Subdomain Discovery',
};

export default function Show({ website, availableOnPlan, categories, authorization, reports = [] }) {
    const [selected, setSelected] = useState(authorization?.scope ?? []);
    const [confirmed, setConfirmed] = useState(false);

    if (website.status !== 'verified' || !availableOnPlan) {
        return (
            <AuthenticatedLayout header={<h2 className="text-xl font-semibold">Pen Testing</h2>}>
                <Head title="Pen Testing" />
                <Card className="mx-auto max-w-lg">
                    <CardContent className="flex flex-col items-center gap-3 p-10 text-center">
                        <ShieldAlert className="h-8 w-8 text-muted-foreground" />
                        <p className="text-sm text-muted-foreground">
                            {website.status !== 'verified'
                                ? 'Verify this website to unlock penetration testing.'
                                : 'Penetration testing is not included in your current plan.'}
                        </p>
                    </CardContent>
                </Card>
            </AuthenticatedLayout>
        );
    }

    function toggle(cat) {
        setSelected((s) => (s.includes(cat) ? s.filter((c) => c !== cat) : [...s, cat]));
    }

    function authorize() {
        router.post(route('pentest.authorize', website.id), { scope: selected }, { preserveScroll: true });
    }

    function runTest() {
        router.post(route('pentest.store', website.id), { categories: selected }, { preserveScroll: true });
    }

    const covered = authorization && selected.every((c) => authorization.scope.includes(c));

    return (
        <AuthenticatedLayout header={<h2 className="text-xl font-semibold">Pen Testing — {website.domain}</h2>}>
            <Head title={`Pen Testing — ${website.domain}`} />

            <div className="mb-6 flex items-start gap-3 rounded-lg border border-score-warn/30 bg-score-warn/10 p-4 text-sm">
                <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
                <div>
                    Active penetration testing is a legal/liability boundary, not just a UX one. Every run requires an
                    explicit authorization of scope, and every attempt is written to the audit log with who ran it and when.
                </div>
            </div>

            <div className="grid gap-6 lg:grid-cols-2">
                <Card>
                    <CardHeader>
                        <CardTitle className="text-foreground">Authorized scope</CardTitle>
                        <CardDescription>
                            {authorization
                                ? `Authorized ${new Date(authorization.authorized_at).toLocaleString()}`
                                : 'Select which categories to authorize, then confirm.'}
                        </CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-3">
                        <div className="grid grid-cols-2 gap-2">
                            {categories.map((cat) => (
                                <label key={cat} className="flex items-center gap-2 text-sm">
                                    <input
                                        type="checkbox"
                                        checked={selected.includes(cat)}
                                        onChange={() => toggle(cat)}
                                        className="rounded border-input"
                                    />
                                    {CATEGORY_LABELS[cat] ?? cat}
                                </label>
                            ))}
                        </div>

                        {!authorization || !covered ? (
                            <div className="space-y-2 border-t border-border pt-3">
                                <label className="flex items-start gap-2 text-sm">
                                    <input
                                        type="checkbox"
                                        checked={confirmed}
                                        onChange={(e) => setConfirmed(e.target.checked)}
                                        className="mt-0.5 rounded border-input"
                                    />
                                    I confirm I am authorized to run these tests against {website.domain} and accept
                                    responsibility for this scope.
                                </label>
                                <Button onClick={authorize} disabled={selected.length === 0 || !confirmed}>
                                    Authorize scope
                                </Button>
                            </div>
                        ) : (
                            <Button onClick={runTest} disabled={selected.length === 0}>
                                Run Pen Test
                            </Button>
                        )}
                    </CardContent>
                </Card>

                <Card>
                    <CardHeader><CardTitle>Recent runs</CardTitle></CardHeader>
                    <CardContent>
                        {reports.length === 0 ? (
                            <p className="text-sm text-muted-foreground">No pen tests run yet.</p>
                        ) : (
                            <ul className="space-y-3 text-sm">
                                {reports.map((r) => (
                                    <li key={r.id} className="border-b border-border pb-2 last:border-0">
                                        <div className="flex items-center justify-between">
                                            <span>{new Date(r.created_at).toLocaleString()}</span>
                                            <Badge variant={r.risk_level === 'critical' || r.risk_level === 'high' ? 'critical' : r.risk_level === 'medium' ? 'warn' : 'good'}>
                                                {r.risk_level} {r.cvss_score ? `(CVSS ${r.cvss_score})` : ''}
                                            </Badge>
                                        </div>
                                        <p className="mt-1 text-xs text-muted-foreground">
                                            {(r.categories_tested ?? []).map((c) => CATEGORY_LABELS[c] ?? c).join(', ')}
                                        </p>
                                    </li>
                                ))}
                            </ul>
                        )}
                    </CardContent>
                </Card>
            </div>
        </AuthenticatedLayout>
    );
}
