'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { 
  Building2, 
  Package, 
  Users, 
  Star, 
  Settings, 
  LogOut, 
  Plus,
  Eye,
  Edit,
  Image,
  BarChart3,
  Shield,
  Globe,
  FileText,
  Images
} from 'lucide-react';

interface DashboardStats {
  products: number;
  features: number;
  testimonials: number;
  projects: number;
}

export default function AdminDashboard() {
  const [stats, setStats] = useState<DashboardStats>({
    products: 0,
    features: 0,
    testimonials: 0,
    projects: 0
  });
  const [loading, setLoading] = useState(true);
  const router = useRouter();

  useEffect(() => {
    fetchStats();
  }, []);

  const fetchStats = async () => {
    try {
      // Fetch stats from API endpoints
      const [productsRes, featuresRes, testimonialsRes, projectsRes] = await Promise.all([
        fetch('/api/admin/products'),
        fetch('/api/admin/features'),
        fetch('/api/admin/testimonials'),
        fetch('/api/admin/projects')
      ]);

      const [products, features, testimonials, projects] = await Promise.all([
        productsRes.json(),
        featuresRes.json(),
        testimonialsRes.json(),
        projectsRes.json()
      ]);

      setStats({
        products: products.data?.length || 0,
        features: features.data?.length || 0,
        testimonials: testimonials.data?.length || 0,
        projects: projects.data?.length || 0
      });
    } catch (error) {
      console.error('Error fetching stats:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleLogout = async () => {
    try {
      await fetch('/api/auth', { method: 'DELETE' });
      router.push('/admin/login');
    } catch (error) {
      console.error('Logout error:', error);
    }
  };

  const menuItems = [
    {
      title: 'Company Info',
      description: 'Manage company details, contact info, and branding',
      href: '/admin/company',
      icon: Building2,
      color: 'bg-blue-500',
      stats: '1 entry'
    },
    {
      title: 'Products',
      description: 'Manage porta cabin products and specifications',
      href: '/admin/products',
      icon: Package,
      color: 'bg-green-500',
      stats: `${stats.products} products`
    },
    {
      title: 'Features',
      description: 'Manage homepage features and selling points',
      href: '/admin/features',
      icon: Star,
      color: 'bg-yellow-500',
      stats: `${stats.features} features`
    },
    {
      title: 'Testimonials',
      description: 'Manage customer reviews and testimonials',
      href: '/admin/testimonials',
      icon: Users,
      color: 'bg-purple-500',
      stats: `${stats.testimonials} reviews`
    },
    {
      title: 'Projects',
      description: 'Manage project portfolio and case studies',
      href: '/admin/projects',
      icon: BarChart3,
      color: 'bg-orange-500',
      stats: `${stats.projects} projects`
    },
    {
      title: 'Pages',
      description: 'Create and manage website pages and content',
      href: '/admin/pages',
      icon: FileText,
      color: 'bg-indigo-500',
      stats: 'Manage pages'
    },
    {
      title: 'Sliders',
      description: 'Manage image sliders and carousel content',
      href: '/admin/sliders',
      icon: Images,
      color: 'bg-cyan-500',
      stats: 'Manage sliders'
    },
    {
      title: 'Media Library',
      description: 'Manage uploaded images and media files',
      href: '/admin/media',
      icon: Image,
      color: 'bg-pink-500',
      stats: 'View uploads'
    }
  ];

  const quickActions = [
    { label: 'Add New Product', href: '/admin/products/new', icon: Package },
    { label: 'Add Testimonial', href: '/admin/testimonials/new', icon: Users },
    { label: 'Upload Images', href: '/admin/media/upload', icon: Image },
    { label: 'View Website', href: '/', icon: Globe, external: true }
  ];

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <header className="bg-white shadow-sm border-b">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center h-16">
            <div className="flex items-center gap-3">
              <Building2 className="h-8 w-8 text-blue-600" />
              <div>
                <h1 className="text-xl font-bold text-gray-900">SAAM Cabins</h1>
                <p className="text-sm text-gray-500">Admin Panel</p>
              </div>
            </div>
            
            <div className="flex items-center gap-4">
              <Badge variant="outline" className="hidden sm:inline-flex">
                <Shield className="h-3 w-3 mr-1" />
                Admin Access
              </Badge>
              
              <Button variant="outline" size="sm" asChild>
                <Link href="/" target="_blank">
                  <Eye className="h-4 w-4 mr-2" />
                  View Site
                </Link>
              </Button>
              
              <Button variant="outline" size="sm" onClick={handleLogout}>
                <LogOut className="h-4 w-4 mr-2" />
                Logout
              </Button>
            </div>
          </div>
        </div>
      </header>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Welcome Section */}
        <div className="mb-8">
          <h2 className="text-3xl font-bold text-gray-900 mb-2">
            Welcome to Admin Panel
          </h2>
          <p className="text-gray-600">
            Manage your SAAM Cabins website content, products, and media files.
          </p>
        </div>

        {/* Quick Stats */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-gray-500 mb-1">Total Products</p>
                  <p className="text-2xl font-bold text-gray-900">{stats.products}</p>
                </div>
                <Package className="h-8 w-8 text-blue-600" />
              </div>
            </CardContent>
          </Card>
          
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-gray-500 mb-1">Features</p>
                  <p className="text-2xl font-bold text-gray-900">{stats.features}</p>
                </div>
                <Star className="h-8 w-8 text-yellow-600" />
              </div>
            </CardContent>
          </Card>
          
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-gray-500 mb-1">Testimonials</p>
                  <p className="text-2xl font-bold text-gray-900">{stats.testimonials}</p>
                </div>
                <Users className="h-8 w-8 text-green-600" />
              </div>
            </CardContent>
          </Card>
          
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-gray-500 mb-1">Projects</p>
                  <p className="text-2xl font-bold text-gray-900">{stats.projects}</p>
                </div>
                <BarChart3 className="h-8 w-8 text-purple-600" />
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Quick Actions */}
        <div className="mb-8">
          <h3 className="text-lg font-semibold text-gray-900 mb-4">Quick Actions</h3>
          <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-4">
            {quickActions.map((action, index) => {
              const IconComponent = action.icon;
              return (
                <Button
                  key={index}
                  variant="outline"
                  className="h-auto p-4 justify-start"
                  asChild
                >
                  <Link href={action.href} {...(action.external ? { target: '_blank' } : {})}>
                    <IconComponent className="h-5 w-5 mr-3" />
                    <span>{action.label}</span>
                  </Link>
                </Button>
              );
            })}
          </div>
        </div>

        {/* Main Management Menu */}
        <div>
          <h3 className="text-lg font-semibold text-gray-900 mb-4">Content Management</h3>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {menuItems.map((item, index) => {
              const IconComponent = item.icon;
              return (
                <Card key={index} className="hover:shadow-md transition-shadow cursor-pointer group">
                  <CardHeader>
                    <div className="flex items-center justify-between">
                      <div className={`${item.color} w-10 h-10 rounded-lg flex items-center justify-center`}>
                        <IconComponent className="h-5 w-5 text-white" />
                      </div>
                      <Badge variant="secondary">{item.stats}</Badge>
                    </div>
                    <CardTitle className="text-lg">{item.title}</CardTitle>
                    <CardDescription>{item.description}</CardDescription>
                  </CardHeader>
                  
                  <CardContent>
                    <Button className="w-full group-hover:bg-gray-900" asChild>
                      <Link href={item.href}>
                        <Edit className="h-4 w-4 mr-2" />
                        Manage
                      </Link>
                    </Button>
                  </CardContent>
                </Card>
              );
            })}
          </div>
        </div>

        {/* Help Section */}
        <div className="mt-12 bg-blue-50 rounded-lg p-6">
          <div className="flex items-start gap-4">
            <div className="bg-blue-100 p-3 rounded-lg">
              <Settings className="h-6 w-6 text-blue-600" />
            </div>
            <div className="flex-1">
              <h4 className="text-lg font-semibold text-gray-900 mb-2">
                Need Help?
              </h4>
              <p className="text-gray-600 mb-4">
                This admin panel allows you to manage all content on your website without touching code. 
                Add products, update company information, manage testimonials, and upload images easily.
              </p>
              <div className="flex flex-wrap gap-2">
                <Badge>User Friendly</Badge>
                <Badge>No Code Required</Badge>
                <Badge>Image Management</Badge>
                <Badge>SEO Optimized</Badge>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}