'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { Header } from '@/components/header';
import { AppLayout } from '@/components/layout';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { apiClient } from '@/lib/api';
import { ProtectedRoute } from '@/components/auth/protected-route';
import { useAuth } from '@/lib/auth-context';
import { ImagePlus, Image, Sparkles, Settings, Activity, ArrowRight, CheckCircle2, XCircle, User, LogOut } from 'lucide-react';

const features = [
  {
    title: 'Text to Image',
    description: 'Generate stunning images from text descriptions using Stable Diffusion',
    icon: ImagePlus,
    href: '/text2img',
    color: 'text-blue-500',
  },
  {
    title: 'Image to Image',
    description: 'Transform existing images with AI-powered modifications',
    icon: Image,
    href: '/img2img',
    color: 'text-purple-500',
  },
  {
    title: 'Upscaler',
    description: 'Enhance and upscale your images for higher quality results',
    icon: Sparkles,
    href: '/upscaler',
    color: 'text-green-500',
  },
  {
    title: 'Model Management',
    description: 'Load, unload, and manage your AI models efficiently',
    icon: Settings,
    href: '/models',
    color: 'text-orange-500',
  },
  {
    title: 'Queue Monitor',
    description: 'Track and manage your generation jobs in real-time',
    icon: Activity,
    href: '/queue',
    color: 'text-pink-500',
  },
];

export default function HomePage() {
  const { user, logout, isAuthenticated, isLoading } = useAuth();
  const [health, setHealth] = useState<'checking' | 'healthy' | 'error'>('checking');
  const [systemInfo, setSystemInfo] = useState<{ version?: string; cuda_available?: boolean } | null>(null);

  const checkHealth = async () => {
    try {
      await apiClient.getHealth();
      setTimeout(() => setHealth('healthy'), 0);
    } catch (err) {
      console.error('Health check failed:', err);
      setTimeout(() => setHealth('error'), 0);
    }
  };

  const loadSystemInfo = async () => {
    try {
      const info = await apiClient.getSystemInfo();
      setTimeout(() => setSystemInfo(info), 0);
    } catch (err) {
      console.error('Failed to load system info:', err);
    }
  };

  useEffect(() => {
    // Check health and system info regardless of authentication status
    checkHealth();
    loadSystemInfo();

    // Set up periodic health checks
    const healthInterval = setInterval(checkHealth, 30000); // Check every 30 seconds
    const systemInfoInterval = setInterval(loadSystemInfo, 60000); // Check every minute

    return () => {
      clearInterval(healthInterval);
      clearInterval(systemInfoInterval);
    };
  }, []);

  // Show loading state while checking authentication
  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"></div>
          <p className="text-muted-foreground">Loading...</p>
        </div>
      </div>
    );
  }

  return (
    <ProtectedRoute>
      <AppLayout>
        <Header
          title="Stable Diffusion REST"
          description="Modern web interface for AI image generation"
          actions={
            <div className="flex items-center gap-4">
              <div className="flex items-center gap-2 text-sm">
                <User className="h-4 w-4" />
                <span>{user?.username}</span>
                <span className="text-muted-foreground">({user?.role})</span>
              </div>
              <Button variant="outline" size="sm" onClick={logout}>
                <LogOut className="h-4 w-4 mr-2" />
                Sign Out
              </Button>
              <Link href="/settings">
                <Button variant="outline" size="sm">
                  <Settings className="h-4 w-4 mr-2" />
                  Settings
                </Button>
              </Link>
            </div>
          }
        />
      <div className="container mx-auto p-6">
        <div className="space-y-8">
          {/* Status Banner */}
          <Card>
            <CardContent className="flex items-center justify-between p-6">
              <div className="flex items-center gap-3">
                {health === 'checking' ? (
                  <>
                    <div className="h-3 w-3 animate-pulse rounded-full bg-yellow-500" />
                    <span className="text-sm">Checking API status...</span>
                  </>
                ) : health === 'healthy' ? (
                  <>
                    <CheckCircle2 className="h-5 w-5 text-green-500" />
                    <span className="text-sm font-medium">API is running</span>
                  </>
                ) : (
                  <>
                    <XCircle className="h-5 w-5 text-red-500" />
                    <span className="text-sm font-medium text-destructive">
                      Cannot connect to API
                    </span>
                  </>
                )}
              </div>
              {systemInfo && (
                <div className="flex gap-4 text-sm text-muted-foreground">
                  {systemInfo.version && <span>v{systemInfo.version}</span>}
                  {systemInfo.cuda_available !== undefined && (
                    <span>CUDA: {systemInfo.cuda_available ? 'Available' : 'Not Available'}</span>
                  )}
                </div>
              )}
            </CardContent>
          </Card>

          {/* Welcome Section */}
          <div className="text-center">
            <h1 className="text-4xl font-bold tracking-tight">Welcome to SD REST UI</h1>
            <p className="mt-4 text-lg text-muted-foreground">
              A modern, intuitive interface for Stable Diffusion image generation
            </p>
          </div>

          {/* Features Grid */}
          <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
            {features.map((feature) => (
              <Card key={feature.href} className="group relative overflow-hidden transition-all hover:shadow-lg">
                <CardHeader>
                  <div className="flex items-center gap-3">
                    <div className={`rounded-lg bg-muted p-2 ${feature.color}`}>
                      <feature.icon className="h-6 w-6" />
                    </div>
                    <CardTitle className="text-xl">{feature.title}</CardTitle>
                  </div>
                  <CardDescription className="mt-2">{feature.description}</CardDescription>
                </CardHeader>
                <CardContent>
                  <Link href={feature.href}>
                    <Button variant="ghost" className="w-full justify-between group-hover:bg-accent">
                      Get Started
                      <ArrowRight className="h-4 w-4 transition-transform group-hover:translate-x-1" />
                    </Button>
                  </Link>
                </CardContent>
              </Card>
            ))}
          </div>

          {/* Quick Start Guide */}
          <Card>
            <CardHeader>
              <CardTitle>Quick Start Guide</CardTitle>
              <CardDescription>Get started with image generation in a few simple steps</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="flex gap-4">
                <div className="flex h-8 w-8 items-center justify-center rounded-full bg-primary text-primary-foreground font-semibold">
                  1
                </div>
                <div className="flex-1">
                  <h4 className="font-medium">Load a Model</h4>
                  <p className="text-sm text-muted-foreground">
                    Navigate to <Link href="/models" className="text-primary hover:underline">Model Management</Link> and load your preferred checkpoint
                  </p>
                </div>
              </div>
              <div className="flex gap-4">
                <div className="flex h-8 w-8 items-center justify-center rounded-full bg-primary text-primary-foreground font-semibold">
                  2
                </div>
                <div className="flex-1">
                  <h4 className="font-medium">Choose Generation Type</h4>
                  <p className="text-sm text-muted-foreground">
                    Select <Link href="/text2img" className="text-primary hover:underline">Text to Image</Link>, <Link href="/img2img" className="text-primary hover:underline">Image to Image</Link>, or <Link href="/upscaler" className="text-primary hover:underline">Upscaler</Link>
                  </p>
                </div>
              </div>
              <div className="flex gap-4">
                <div className="flex h-8 w-8 items-center justify-center rounded-full bg-primary text-primary-foreground font-semibold">
                  3
                </div>
                <div className="flex-1">
                  <h4 className="font-medium">Generate & Monitor</h4>
                  <p className="text-sm text-muted-foreground">
                    Start generation and track progress in the <Link href="/queue" className="text-primary hover:underline">Queue Monitor</Link>
                  </p>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* API Info */}
          <Card>
            <CardHeader>
              <CardTitle>API Configuration</CardTitle>
              <CardDescription>Backend API connection details</CardDescription>
            </CardHeader>
            <CardContent>
              <dl className="grid gap-3 text-sm">
                <div className="flex justify-between">
                  <dt className="text-muted-foreground">API URL:</dt>
                  <dd className="font-mono">{process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8080'}</dd>
                </div>
                <div className="flex justify-between">
                  <dt className="text-muted-foreground">Base Path:</dt>
                  <dd className="font-mono">{process.env.NEXT_PUBLIC_API_BASE_PATH || '/api/v1'}</dd>
                </div>
                <div className="flex justify-between">
                  <dt className="text-muted-foreground">Status:</dt>
                  <dd>
                    {health === 'healthy' ? (
                      <span className="text-green-600 dark:text-green-400">Connected</span>
                    ) : health === 'error' ? (
                      <span className="text-destructive">Disconnected</span>
                    ) : (
                      <span className="text-yellow-600 dark:text-yellow-400">Checking...</span>
                    )}
                  </dd>
                </div>
              </dl>
            </CardContent>
          </Card>
        </div>
      </div>
    </AppLayout>
    </ProtectedRoute>
  );
}
