import React, { useEffect, useState } from 'react';
import axios from 'axios';
import {
    Card,
    CardContent,
    CardHeader,
    CardTitle
} from '@/Components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/Components/ui/tabs';
import { Button } from "@/Components/ui/button";
import { Alert, AlertDescription } from '@/Components/ui/alert';
import { ShieldAlert, ChevronLeft, ChevronRight } from 'lucide-react';
import Markdown from 'react-markdown';
import {
    SecuritySummaryReportResultType, SecuritySummaryResponseType,
} from '@/types/security-summary';
import VulnerabilitiesActiveCard from "@/Components/Dashboard/Vulnerabilities/VulnerabilitiesActiveCard";
import VulnerabilitiesPassiveCard from "@/Components/Dashboard/Vulnerabilities/VulnerabilitiesPassiveCard";
import SecurityScoresOverviewBarChart from "@/Components/SecurityScoresOverviewBarChart";
import ServicesPortExposureCard from "@/Components/Dashboard/Services/ServicesPortExposureCard";
import DashboardHeader from "@/Components/Dashboard/DashboardHeader";
import OverviewNetworkAssetsCard from "@/Components/Dashboard/Overview/OverviewNetworkAssetsCard";
import OverviewSimilarDomainsCard from "@/Components/Dashboard/Overview/OverviewSimilarDomainsCard";
import OverviewEmailSecurityCard from "@/Components/Dashboard/Overview/OverviewEmailSecurityCard";
import OverviewCertificatesCard from "@/Components/Dashboard/Overview/OverviewCertificatesCard";
import OverviewDataLeaksCard from "@/Components/Dashboard/Overview/OverviewDataLeaksCard";
import ServicesWafCard from "@/Components/Dashboard/Services/ServicesWafCard";
import ServicesCdnCard from "@/Components/Dashboard/Services/ServicesCdnCard";
import LeaksEnumerationCard from "@/Components/Dashboard/Leaks/LeaksEnumerationCard";
import LeaksResolvedCard from "@/Components/Dashboard/Leaks/LeaksResolvedCard";
import LeaksUnresolvedCard from "@/Components/Dashboard/Leaks/LeaksUnresolvedCard";
import OverviewVulnerabilityScoreCard from "@/Components/Dashboard/Overview/OverviewVulnerabilityScoreCard";

export default function Dashboard({ page }: { page:number }) {
    const [securitySummaryResponse, setSecuritySummaryResponse] = useState<SecuritySummaryResponseType | null>(null);
    const [reportData, setReportData] = useState<SecuritySummaryReportResultType | null>(null);
    const [currentPage, setCurrentPage] = useState<number>(page);


    useEffect(() => {
        axios.get<SecuritySummaryResponseType>('/api/v1/security/summary')
            .then(response => {
                setSecuritySummaryResponse(response.data);
                setReportData(response.data.results[0] ?? null);
            })
            .catch(error => {
                console.error("Error fetching the report data", error);
            });
    }, []);

    useEffect(() => {
        if (securitySummaryResponse) {
            setReportData(securitySummaryResponse.results[currentPage] ?? null);
        }
    }, [currentPage, securitySummaryResponse]);

    const handlePrevPage = () => {
        setCurrentPage(prev => Math.max(0, prev - 1));
    };

    const handleNextPage = () => {
        if (securitySummaryResponse) {
            setCurrentPage(prev => Math.min(securitySummaryResponse.results.length - 1, prev + 1));
        }
    };

    if (!reportData) return <div>Loading...</div>;

    return (
        <div className="container mx-auto p-4">
            <DashboardHeader reportData={reportData}/>

            <Tabs defaultValue="overview">
                <TabsList>
                    <TabsTrigger value="overview">Overview</TabsTrigger>
                    <TabsTrigger value="vulnerabilities">Vulnerabilities</TabsTrigger>
                    <TabsTrigger value="services">Exposed Services</TabsTrigger>
                    <TabsTrigger value="leaks">Data Leaks</TabsTrigger>
                </TabsList>

                <TabsContent value="overview" className="space-y-6">
                    <div>
                        <h3 className="text-xl">Overview</h3>
                    </div>
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                        <OverviewNetworkAssetsCard reportData={reportData}/>
                        <OverviewVulnerabilityScoreCard reportData={reportData}/>
                        <OverviewSimilarDomainsCard reportData={reportData} />
                        <OverviewEmailSecurityCard reportData={reportData}/>
                        <OverviewCertificatesCard reportData={reportData}/>
                        <OverviewDataLeaksCard reportData={reportData}/>
                    </div>

                    <div className="grid grid-cols-1 gap-4 mt-6">
                        <SecurityScoresOverviewBarChart reportData={reportData}/>
                    </div>

                    <Card className="mt-6">
                        <Tabs defaultValue="lang-en">
                            <CardHeader>
                                <CardTitle className="flex items-center gap-2">
                                    <ShieldAlert className="h-5 w-5 text-red-500"/>
                                    Security Summary
                                    <TabsList>
                                        <TabsTrigger value="lang-en">EN</TabsTrigger>
                                        <TabsTrigger value="lang-it">IT</TabsTrigger>
                                    </TabsList>
                                </CardTitle>
                            </CardHeader>
                            <CardContent>
                                <Alert variant="destructive">
                                    <AlertDescription>
                                        <TabsContent value="lang-en">
                                            <Markdown>{reportData.summary_text_en}</Markdown>
                                        </TabsContent>
                                        <TabsContent value="lang-it">
                                            <Markdown>{reportData.summary_text}</Markdown>
                                        </TabsContent>
                                    </AlertDescription>
                                </Alert>
                            </CardContent>
                        </Tabs>
                    </Card>
                </TabsContent>

                <TabsContent value="services">
                    <div>
                        <h3 className="text-xl">Data Leaks Details</h3>
                    </div>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mt-6">
                        <ServicesPortExposureCard reportData={reportData}/>
                        <ServicesWafCard reportData={reportData} />
                        <ServicesCdnCard reportData={reportData} />
                    </div>
                </TabsContent>


                <TabsContent value="vulnerabilities">
                    <div>
                        <h3 className="text-xl">Data Leaks Details</h3>
                    </div>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mt-6">
                        <VulnerabilitiesActiveCard reportData={reportData}/>
                        <VulnerabilitiesPassiveCard reportData={reportData}/>
                    </div>
                </TabsContent>

                <TabsContent value="leaks" className="space-y-6">
                    <div>
                        <h3 className="text-xl">Data Leaks Details</h3>
                    </div>
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                        <LeaksEnumerationCard reportData={reportData} />
                        <LeaksResolvedCard reportData={reportData} />
                        <LeaksUnresolvedCard reportData={reportData} />
                    </div>
                </TabsContent>
            </Tabs>
            <div className="flex items-center justify-center gap-4 mt-6">
                <Button
                    onClick={handlePrevPage}
                    disabled={currentPage === 0}
                    variant="outline"
                    className="flex items-center gap-2"
                >
                    <ChevronLeft className="w-4 h-4"/>
                    Previous
                </Button>

                <div className="text-sm text-muted-foreground">
                    Page {currentPage + 1} of {securitySummaryResponse?.results.length}
                </div>

                <Button
                    onClick={handleNextPage}
                    disabled={!securitySummaryResponse || currentPage === securitySummaryResponse.results.length - 1}
                    variant="outline"
                    className="flex items-center gap-2"
                >
                    Next
                    <ChevronRight className="w-4 h-4"/>
                </Button>
            </div>
        </div>
    );
};
