'use client';

import { useRouter } from 'next/navigation';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { FileText, Layout, Upload, BookOpen } from 'lucide-react';
import Image from 'next/image';
import { useKindeBrowserClient } from "@kinde-oss/kinde-auth-nextjs";

interface AppTile {
  id: string;
  title: string;
  description: string;
  icon: React.ReactNode;
  href: string;
  color: string;
}

export default function DashboardPage() {
  const router = useRouter();
  const { isAuthenticated, accessToken } = useKindeBrowserClient();
  const roles = accessToken?.roles || [];
  const permissions = accessToken?.permissions || [];

  // Extract role keys for easier checking
  const roleKeys = roles.map(role => role.key);

  // Check if user has admin role
  const hasAdminRole = isAuthenticated && roleKeys.includes('admin');

  // Check if user has customer role and cintas_access permission
  const hasCustomerRole = isAuthenticated && roleKeys.includes('customer');
  const hasCintasAccess = permissions.includes('cintas_access');

  // Check if user can access Cintas summary
  const canAccessCintasSummary = hasAdminRole || (hasCustomerRole && hasCintasAccess);

  const allApps: AppTile[] = [
    {
      id: 'files',
      title: 'Files',
      description: 'Manage and organize your uploaded files',
      icon: <FileText className="w-8 h-8" />,
      href: '/files',
      color: 'bg-blue-500'
    },
    {
      id: 'layout-configurations',
      title: 'Layout Configurations',
      description: 'Create and manage layout configurations',
      icon: <Layout className="w-8 h-8" />,
      href: '/layout-configurations',
      color: 'bg-green-500'
    },
    {
      id: 'imports',
      title: 'Imports',
      description: 'Import and manage data from external sources',
      icon: <Upload className="w-8 h-8" />,
      href: '/imports',
      color: 'bg-purple-500'
    },
    {
      id: 'api-docs',
      title: 'API Documentation',
      description: 'Explore API endpoints and documentation',
      icon: <BookOpen className="w-8 h-8" />,
      href: '/api-docs',
      color: 'bg-orange-500'
    },
    {
      id: 'cintas-calendar-summary',
      title: 'Cintas Install Calendar Summary',
      description: 'View installation calendar summary and statistics',
      icon: (
        <div className="w-8 h-8 relative">
          <Image
            src="/Cintas-Blue.svg"
            alt="Cintas"
            fill
            className="object-contain"
          />
        </div>
      ),
      href: '/cintas-calendar-summary',
      color: 'bg-blue-600'
    }
  ];

  // Filter apps based on authentication and authorization
  const filteredApps = allApps.filter(app => {
    // All apps except Cintas require admin role
    if (app.id !== 'cintas-calendar-summary') {
      return hasAdminRole;
    }

    // Cintas summary has special access rules
    return canAccessCintasSummary;
  });

  const handleAppClick = (href: string) => {
    router.push(href);
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100 dark:from-gray-900 dark:to-gray-800">
      <div className="container mx-auto px-4 py-8">
        <div className="text-center mb-12">
          <h1 className="text-4xl font-bold text-gray-900 dark:text-white mb-4">
            Welcome to Vtorio Dashboard
          </h1>
          <p className="text-lg text-gray-600 dark:text-gray-300">
            Select an application to get started
          </p>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 max-w-6xl mx-auto">
          {filteredApps.map((app) => (
            <Card
              key={app.id}
              className="group cursor-pointer transition-all duration-300 hover:shadow-lg hover:scale-105 dark:bg-gray-800 dark:border-gray-700"
              onClick={() => handleAppClick(app.href)}
            >
              <CardHeader className="text-center">
                <div className={`${app.id === 'cintas-calendar-summary' ? 'bg-white border-2 border-blue-500' : app.color} w-16 h-16 rounded-full flex items-center justify-center ${app.id === 'cintas-calendar-summary' ? '' : 'text-white'} mx-auto mb-4 group-hover:scale-110 transition-transform duration-300`}>
                  {app.icon}
                </div>
                <CardTitle className="text-xl font-semibold text-gray-900 dark:text-white">
                  {app.title}
                </CardTitle>
              </CardHeader>
              <CardContent>
                <CardDescription className="text-center text-gray-600 dark:text-gray-300">
                  {app.description}
                </CardDescription>
              </CardContent>
            </Card>
          ))}
        </div>

        <div className="mt-12 text-center">
          <p className="text-sm text-gray-500 dark:text-gray-400">
            Click on any application to access its features
          </p>
        </div>
      </div>
    </div>
  );
}