import { useQuery } from '@tanstack/react-query';
import { apiClient } from '@/lib/api-client';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Loader2, Globe, Scan, AlertCircle, CheckCircle2, TrendingUp, TrendingDown } from 'lucide-react';
import { Link } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { LineChart, Line, AreaChart, Area, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';
import { format } from 'date-fns';

export function DashboardPage() {
  const { data: stats, isLoading: statsLoading } = useQuery({
    queryKey: ['stats'],
    queryFn: () => apiClient.getStats(),
  });

  const { data: recentScans } = useQuery({
    queryKey: ['recent-scans'],
    queryFn: () => apiClient.getScans({ limit: 5 }),
  });

  const { data: websites } = useQuery({
    queryKey: ['websites-summary'],
    queryFn: () => apiClient.getWebsites({ limit: 5 }),
  });

  if (statsLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="h-8 w-8 animate-spin text-primary" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Stats Grid */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Total Websites</CardTitle>
            <Globe className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats?.database?.websites || 0}</div>
            <p className="text-xs text-muted-foreground">
              Active websites being monitored
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Total Scans</CardTitle>
            <Scan className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats?.database?.scanResults || 0}</div>
            <p className="text-xs text-muted-foreground">
              Accessibility scans performed
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Queue Status</CardTitle>
            <AlertCircle className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats?.queue?.active || 0}</div>
            <p className="text-xs text-muted-foreground">
              Active scans in progress
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Success Rate</CardTitle>
            <CheckCircle2 className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {stats?.queue?.completed && stats?.queue?.failed
                ? Math.round((stats.queue.completed / (stats.queue.completed + stats.queue.failed)) * 100)
                : 100}%
            </div>
            <p className="text-xs text-muted-foreground">
              Scan completion rate
            </p>
          </CardContent>
        </Card>
      </div>

      {/* Charts Row */}
      <div className="grid gap-4 md:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle>Compliance Trends</CardTitle>
            <CardDescription>Average compliance scores over time</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="h-[300px]">
              <ResponsiveContainer width="100%" height="100%">
                <LineChart
                  data={[
                    { date: 'Mon', score: 85 },
                    { date: 'Tue', score: 87 },
                    { date: 'Wed', score: 86 },
                    { date: 'Thu', score: 89 },
                    { date: 'Fri', score: 91 },
                    { date: 'Sat', score: 90 },
                    { date: 'Sun', score: 92 },
                  ]}
                >
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="date" />
                  <YAxis domain={[0, 100]} />
                  <Tooltip />
                  <Line
                    type="monotone"
                    dataKey="score"
                    stroke="hsl(var(--primary))"
                    strokeWidth={2}
                  />
                </LineChart>
              </ResponsiveContainer>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Issue Distribution</CardTitle>
            <CardDescription>Violations by severity level</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="h-[300px]">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart
                  data={[
                    { severity: 'Critical', count: 5, fill: 'hsl(var(--destructive))' },
                    { severity: 'Serious', count: 12, fill: 'hsl(var(--warning))' },
                    { severity: 'Moderate', count: 25, fill: 'hsl(var(--primary))' },
                    { severity: 'Minor', count: 45, fill: 'hsl(var(--muted))' },
                  ]}
                >
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="severity" />
                  <YAxis />
                  <Tooltip />
                  <Bar dataKey="count" />
                </BarChart>
              </ResponsiveContainer>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Recent Activity */}
      <div className="grid gap-4 md:grid-cols-2">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between">
            <div>
              <CardTitle>Recent Scans</CardTitle>
              <CardDescription>Latest accessibility scan results</CardDescription>
            </div>
            <Button variant="outline" size="sm" asChild>
              <Link to="/scans">View all</Link>
            </Button>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {recentScans?.scans?.map((scan: any) => (
                <div key={scan.id} className="flex items-center justify-between">
                  <div className="flex-1">
                    <p className="text-sm font-medium">{scan.website?.name}</p>
                    <p className="text-xs text-muted-foreground">
                      {format(new Date(scan.createdAt), 'MMM d, h:mm a')}
                    </p>
                  </div>
                  <div className="flex items-center gap-2">
                    {scan.status === 'COMPLETED' ? (
                      <div className="flex items-center gap-1">
                        <span className="text-sm font-medium">
                          {scan.result?.summary?.score || 0}%
                        </span>
                        {scan.result?.summary?.score > 90 ? (
                          <TrendingUp className="h-4 w-4 text-success" />
                        ) : (
                          <TrendingDown className="h-4 w-4 text-destructive" />
                        )}
                      </div>
                    ) : (
                      <span className="text-xs text-muted-foreground">
                        {scan.status}
                      </span>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between">
            <div>
              <CardTitle>Websites</CardTitle>
              <CardDescription>Your monitored websites</CardDescription>
            </div>
            <Button variant="outline" size="sm" asChild>
              <Link to="/websites">Manage</Link>
            </Button>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {websites?.websites?.map((website: any) => (
                <div key={website.id} className="flex items-center justify-between">
                  <div className="flex-1">
                    <p className="text-sm font-medium">{website.name}</p>
                    <p className="text-xs text-muted-foreground">{website.url}</p>
                  </div>
                  <div className="flex items-center gap-2">
                    {website.complianceScore !== null ? (
                      <span className="text-sm font-medium">
                        {Math.round(website.complianceScore)}%
                      </span>
                    ) : (
                      <span className="text-xs text-muted-foreground">
                        No scans yet
                      </span>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}