'use client'

import { useState } from 'react'
import { useRouter, useParams } from 'next/navigation'
import { useQuery } from '@tanstack/react-query'
import { monitorAPI } from '@/lib/api'
import { DashboardLayout } from '@/components/layout/dashboard-layout'
import { Button } from '@/components/ui/button'
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import ReactDiffViewer, { DiffMethod } from 'react-diff-viewer-continued'

export default function SnapshotDetailsPage() {
    const router = useRouter()
    const params = useParams()
    const monitorId = params?.id as string
    const snapshotId = params?.snapshotId as string
    const [showHtml, setShowHtml] = useState(false)

    const { data: monitorData } = useQuery({
        queryKey: ['monitor', monitorId],
        queryFn: async () => {
            const response = await monitorAPI.get(monitorId)
            return response.monitor
        },
    })

    const { data: snapshotData, isLoading } = useQuery({
        queryKey: ['snapshot', monitorId, snapshotId],
        queryFn: async () => {
            const response = await monitorAPI.snapshot(monitorId, snapshotId)
            return response.snapshot
        },
    })

    const { data: historyData } = useQuery({
        queryKey: ['history', monitorId],
        queryFn: async () => {
            const response = await monitorAPI.history(monitorId, 2)
            return response.snapshots
        }
    })

    if (isLoading) {
        return (
            <DashboardLayout>
                <div className="flex items-center justify-center py-12">
                    <div className="flex flex-col items-center gap-3">
                        <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
                        <p className="text-muted-foreground">Loading snapshot...</p>
                    </div>
                </div>
            </DashboardLayout>
        )
    }

    const snapshot = snapshotData
    const monitor = monitorData
    const previousSnapshot = historyData?.find((s: any) =>
        new Date(s.createdAt) < new Date(snapshot?.createdAt)
    )

    if (!snapshot) {
        return (
            <DashboardLayout>
                <div className="flex flex-col items-center justify-center py-12 gap-4">
                    <div className="flex h-16 w-16 items-center justify-center rounded-full bg-destructive/10">
                        <svg className="h-8 w-8 text-destructive" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                        </svg>
                    </div>
                    <p className="text-lg font-medium">Snapshot not found</p>
                    <Button variant="outline" onClick={() => router.push(`/monitors/${monitorId}`)}>
                        Back to History
                    </Button>
                </div>
            </DashboardLayout>
        )
    }

    return (
        <DashboardLayout>
            {/* Page Header */}
            <div className="mb-6">
                <div className="flex items-center gap-4 mb-4">
                    <Button variant="ghost" size="sm" onClick={() => router.push(`/monitors/${monitorId}`)} className="gap-2">
                        <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                        </svg>
                        Back to History
                    </Button>
                </div>
                <h1 className="text-2xl font-bold">Snapshot Details</h1>
                {monitor && (
                    <p className="text-sm text-muted-foreground mt-1">{monitor.name}</p>
                )}
            </div>

            {/* Snapshot Info Card */}
            <Card className="mb-6">
                <CardHeader>
                    <CardTitle>Snapshot Information</CardTitle>
                </CardHeader>
                <CardContent>
                    <div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-4">
                        <div className="space-y-1">
                            <p className="text-sm text-muted-foreground">Status</p>
                            {snapshot.changed ? (
                                <Badge variant="default">Changed</Badge>
                            ) : (
                                <Badge variant="secondary">No Change</Badge>
                            )}
                        </div>

                        <div className="space-y-1">
                            <p className="text-sm text-muted-foreground">Created At</p>
                            <p className="font-medium">
                                {new Date(snapshot.createdAt).toLocaleString(undefined, {
                                    year: 'numeric',
                                    month: 'short',
                                    day: 'numeric',
                                    hour: '2-digit',
                                    minute: '2-digit',
                                })}
                            </p>
                        </div>

                        <div className="space-y-1">
                            <p className="text-sm text-muted-foreground">HTTP Status</p>
                            <Badge variant={snapshot.httpStatus >= 400 ? 'destructive' : 'success'}>
                                {snapshot.httpStatus || 'N/A'}
                            </Badge>
                        </div>

                        <div className="space-y-1">
                            <p className="text-sm text-muted-foreground">Response Time</p>
                            <p className="font-medium">{snapshot.responseTime}ms</p>
                        </div>

                        {snapshot.changePercentage && (
                            <div className="space-y-1">
                                <p className="text-sm text-muted-foreground">Change Percentage</p>
                                <p className="font-medium text-primary">
                                    {Number(snapshot.changePercentage).toFixed(2)}%
                                </p>
                            </div>
                        )}
                    </div>

                    {snapshot.errorMessage && (
                        <div className="mt-6 rounded-lg bg-destructive/10 p-4">
                            <p className="text-sm font-medium text-destructive">Error</p>
                            <p className="text-sm text-destructive/80 mt-1">{snapshot.errorMessage}</p>
                        </div>
                    )}

                    {/* Change Summary */}
                    {snapshot.summary && (
                        <div className="mt-6 rounded-lg bg-blue-50 border border-blue-200 p-4">
                            <p className="text-sm font-medium text-blue-900">Change Summary</p>
                            <p className="text-sm text-blue-700 mt-1">{snapshot.summary}</p>
                        </div>
                    )}
                </CardContent>
            </Card>

            {/* Diff Viewer */}
            {snapshot.changed && previousSnapshot && (
                <Card className="mb-6">
                    <CardHeader>
                        <CardTitle>Changes Detected</CardTitle>
                    </CardHeader>
                    <CardContent>
                        <div className="max-h-[500px] overflow-auto rounded-lg border border-border">
                            <ReactDiffViewer
                                oldValue={previousSnapshot.textContent || ''}
                                newValue={snapshot.textContent || ''}
                                splitView={true}
                                compareMethod={DiffMethod.WORDS}
                                useDarkTheme={false}
                                styles={{
                                    variables: {
                                        light: {
                                            diffViewerBackground: 'hsl(40 14% 97%)',
                                            addedBackground: 'rgba(34, 197, 94, 0.1)',
                                            addedGutterBackground: 'rgba(34, 197, 94, 0.2)',
                                            removedBackground: 'rgba(239, 68, 68, 0.1)',
                                            removedGutterBackground: 'rgba(239, 68, 68, 0.2)',
                                            wordAddedBackground: 'rgba(34, 197, 94, 0.3)',
                                            wordRemovedBackground: 'rgba(239, 68, 68, 0.3)',
                                            addedGutterColor: '#166534',
                                            removedGutterColor: '#991b1b',
                                            gutterBackground: 'hsl(35 18% 88%)',
                                            gutterBackgroundDark: 'hsl(35 18% 85%)',
                                            codeFoldBackground: 'hsl(35 15% 82%)',
                                            codeFoldGutterBackground: 'hsl(35 15% 80%)',
                                        },
                                    },
                                }}
                            />
                        </div>
                    </CardContent>
                </Card>
            )}

            {/* Text Content when no change */}
            {!snapshot.changed && snapshot.textContent && (
                <Card className="mb-6">
                    <CardHeader>
                        <CardTitle>Text Content</CardTitle>
                    </CardHeader>
                    <CardContent>
                        <pre className="max-h-96 overflow-auto rounded-lg bg-muted p-4 text-sm whitespace-pre-wrap scrollbar-thin">
                            {snapshot.textContent}
                        </pre>
                    </CardContent>
                </Card>
            )}

            {/* HTML Content Toggle */}
            {snapshot.htmlContent && (
                <Card>
                    <CardHeader className="flex-row items-center justify-between space-y-0">
                        <CardTitle>HTML Content</CardTitle>
                        <Button variant="outline" size="sm" onClick={() => setShowHtml(!showHtml)}>
                            {showHtml ? 'Hide HTML' : 'Show HTML'}
                        </Button>
                    </CardHeader>
                    {showHtml && (
                        <CardContent>
                            <pre className="max-h-96 overflow-auto rounded-lg bg-foreground p-4 text-sm text-green-400 whitespace-pre-wrap scrollbar-thin">
                                {snapshot.htmlContent}
                            </pre>
                        </CardContent>
                    )}
                </Card>
            )}
        </DashboardLayout>
    )
}
