'use client'

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, CardContent } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'

export default function MonitorHistoryPage() {
  const router = useRouter()
  const params = useParams()
  const id = params?.id as string

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

  const { data: historyData, isLoading } = useQuery({
    queryKey: ['history', id],
    queryFn: async () => {
      const response = await monitorAPI.history(id)
      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 history...</p>
          </div>
        </div>
      </DashboardLayout>
    )
  }

  const snapshots = historyData || []
  const monitor = monitorData

  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')} 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
          </Button>
        </div>
        <div className="flex items-center justify-between gap-4">
          <div>
            <h1 className="text-2xl font-bold">{monitor?.name || 'Monitor History'}</h1>
            {monitor && (
              <p className="text-sm text-muted-foreground mt-1 truncate max-w-lg">{monitor.url}</p>
            )}
          </div>
          {monitor && (
            <div className="flex gap-2">
              <Button
                variant="outline"
                size="sm"
                onClick={async () => {
                  try {
                    await monitorAPI.exportAuditTrail(id, 'json');
                  } catch (e) {
                    console.error('Export failed:', e);
                  }
                }}
                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="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                </svg>
                JSON
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={async () => {
                  try {
                    await monitorAPI.exportAuditTrail(id, 'csv');
                  } catch (e) {
                    console.error('Export failed:', e);
                  }
                }}
                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="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                </svg>
                CSV
              </Button>
            </div>
          )}
        </div>
      </div>

      {/* History List */}
      <div>
        <h2 className="mb-4 text-lg font-semibold">Check History</h2>

        {snapshots.length === 0 ? (
          <Card className="text-center">
            <CardContent className="py-12">
              <div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-primary/10">
                <svg className="h-8 w-8 text-primary" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
              </div>
              <h3 className="mb-2 text-lg font-semibold">No history yet</h3>
              <p className="text-muted-foreground">The first check will happen soon</p>
            </CardContent>
          </Card>
        ) : (
          <div className="space-y-3">
            {snapshots.map((snapshot: any) => {
              // Determine border color based on HTTP status
              const getBorderColor = () => {
                if (snapshot.httpStatus >= 400 || snapshot.errorMessage) {
                  return 'border-l-4 border-l-red-500' // Error (4xx, 5xx)
                }
                if (snapshot.httpStatus >= 200 && snapshot.httpStatus < 300) {
                  if (snapshot.changed) {
                    return 'border-l-4 border-l-green-500' // Success with change
                  }
                  return 'border-l-4 border-l-blue-400' // Success no change (neutral)
                }
                return 'border-l-4 border-l-blue-400' // Default neutral
              }

              return (
                <Card
                  key={snapshot.id}
                  className={`transition-all ${getBorderColor()}`}
                >
                  <CardContent className="p-4">
                    <div className="flex items-center justify-between gap-4">
                      <div className="min-w-0 flex-1">
                        <div className="flex flex-wrap items-center gap-2">
                          {snapshot.changed ? (
                            <Badge variant="default">Changed</Badge>
                          ) : (
                            <Badge variant="secondary">No Change</Badge>
                          )}
                          {snapshot.errorMessage && (
                            <Badge variant="destructive">Error</Badge>
                          )}
                          <span className="text-sm text-muted-foreground">
                            {new Date(snapshot.createdAt).toLocaleString(undefined, {
                              year: 'numeric',
                              month: 'short',
                              day: 'numeric',
                              hour: '2-digit',
                              minute: '2-digit',
                            })}
                          </span>
                        </div>

                        <div className="mt-2 flex flex-wrap gap-4 text-sm text-muted-foreground">
                          <span>HTTP {snapshot.httpStatus}</span>
                          <span>{snapshot.responseTime}ms</span>
                          {snapshot.changePercentage && (
                            <span>{Number(snapshot.changePercentage).toFixed(2)}% changed</span>
                          )}
                        </div>

                        {snapshot.errorMessage && (
                          <p className="mt-2 text-sm text-destructive">{snapshot.errorMessage}</p>
                        )}

                        {snapshot.summary && (
                          <div className="mt-3 p-3 bg-muted/50 rounded-md text-sm">
                            <p className="font-medium text-foreground mb-1">Summary</p>
                            <p>{snapshot.summary}</p>
                          </div>
                        )}
                      </div>

                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => router.push(`/monitors/${id}/snapshot/${snapshot.id}`)}
                      >
                        {snapshot.errorMessage ? 'View Error' : 'View Details'}
                      </Button>
                    </div>
                  </CardContent>
                </Card>
              )
            })}
          </div>
        )}
      </div>
    </DashboardLayout>
  )
}
