'use client'

import { useState } from 'react'
import { useSession, signOut } from 'next-auth/react'
import { useRouter } from 'next/navigation'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import {
  Users,
  Package,
  Truck,
  ShoppingCart,
  FileText,
  BarChart3,
  Eye,
  LayoutDashboard,
  Wrench,
  LogOut,
  User
} from 'lucide-react'
import POSModule from '@/components/pos/POSModule'
import { ProduitListe } from '@/components/products/ProduitListe'
import { ClientList } from '@/components/clients/client-list'
import AtelierModule from '@/components/atelier/AtelierModule'
import { SupplierList } from '@/components/suppliers/SupplierList'
import PurchaseModule from '@/components/purchases/PurchaseModule'
import ReportsModule from '@/components/reports/ReportsModule'

type Module = 'HOME' | 'CLIENTS' | 'PRODUITS' | 'FOURNISSEURS' | 'ACHATS' | 'VENTE' | 'RAPPORTS' | 'ATELIER'

interface ModuleCard {
  id: Module
  title: string
  description: string
  icon: React.ReactNode
  badge?: string
  color: string
}

const modules: ModuleCard[] = [
  {
    id: 'CLIENTS',
    title: 'Gestion Clients',
    description: 'Fiches clients, mesures de vision, ordonnances',
    icon: <Users className="h-8 w-8" />,
    color: 'bg-blue-500'
  },
  {
    id: 'PRODUITS',
    title: 'Gestion Produits',
    description: 'Catalogue, stock, images, QR codes',
    icon: <Package className="h-8 w-8" />,
    badge: 'Alertes',
    color: 'bg-emerald-500'
  },
  {
    id: 'FOURNISSEURS',
    title: 'Fournisseurs',
    description: 'Gestion des fournisseurs et contacts',
    icon: <Truck className="h-8 w-8" />,
    color: 'bg-orange-500'
  },
  {
    id: 'ACHATS',
    title: 'Achats & Stock',
    description: 'Réception, factures fournisseurs, entrées stock',
    icon: <ShoppingCart className="h-8 w-8" />,
    color: 'bg-purple-500'
  },
  {
    id: 'VENTE',
    title: 'Point de Vente',
    description: 'Encaissement, facturation, POS',
    icon: <ShoppingCart className="h-8 w-8" />,
    badge: 'Actif',
    color: 'bg-green-500'
  },
  {
    id: 'ATELIER',
    title: 'Atelier',
    description: 'Montage de lunettes, commandes en cours',
    icon: <Wrench className="h-8 w-8" />,
    badge: 'En cours',
    color: 'bg-amber-500'
  },
  {
    id: 'RAPPORTS',
    title: 'Rapports',
    description: 'Statistiques, exports Excel/CSV/PDF',
    icon: <BarChart3 className="h-8 w-8" />,
    color: 'bg-cyan-500'
  }
]

export default function Home() {
  const { data: session } = useSession()
  const router = useRouter()
  const [currentModule, setCurrentModule] = useState<Module>('HOME')

  if (!session) {
    router.push('/login')
    return null
  }

  const renderModule = () => {
    if (currentModule === 'HOME') {
      return (
        <div className="space-y-8">
          <div className="text-center space-y-2">
            <h1 className="text-4xl font-bold text-gray-900">OptiqueStock</h1>
            <p className="text-lg text-gray-600">Système de Gestion de Magasin d'Optique</p>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
            {modules.map((module) => (
              <Card
                key={module.id}
                className="group cursor-pointer transition-all duration-200 hover:shadow-lg hover:scale-105 border-2 hover:border-primary"
                onClick={() => setCurrentModule(module.id)}
              >
                <CardHeader>
                  <div className={`flex items-center justify-between mb-2`}>
                    <div className={`p-3 rounded-lg ${module.color} text-white`}>
                      {module.icon}
                    </div>
                    {module.badge && (
                      <Badge variant="secondary" className="text-xs">
                        {module.badge}
                      </Badge>
                    )}
                  </div>
                  <CardTitle className="text-lg">{module.title}</CardTitle>
                  <CardDescription className="text-sm">
                    {module.description}
                  </CardDescription>
                </CardHeader>
              </Card>
            ))}
          </div>
        </div>
      )
    }

    const moduleInfo = modules.find(m => m.id === currentModule)

    // Render Client Management module if selected
    if (currentModule === 'CLIENTS') {
      return (
        <div className="space-y-6">
          <div className="flex items-center gap-4">
            <Button
              variant="outline"
              onClick={() => setCurrentModule('HOME')}
              className="flex items-center gap-2"
            >
              <LayoutDashboard className="h-4 w-4" />
              Retour à l'accueil
            </Button>
            <div className={`flex items-center gap-3 p-4 rounded-lg ${moduleInfo?.color} text-white`}>
              {moduleInfo?.icon}
              <h2 className="text-2xl font-bold">{moduleInfo?.title}</h2>
            </div>
          </div>
          <ClientList />
        </div>
      )
    }

    // Render POS module if selected
    if (currentModule === 'VENTE') {
      return (
        <div className="space-y-6">
          <div className="flex items-center gap-4">
            <Button
              variant="outline"
              onClick={() => setCurrentModule('HOME')}
              className="flex items-center gap-2"
            >
              <LayoutDashboard className="h-4 w-4" />
              Retour à l'accueil
            </Button>
            <div className={`flex items-center gap-3 p-4 rounded-lg ${moduleInfo?.color} text-white`}>
              {moduleInfo?.icon}
              <h2 className="text-2xl font-bold">{moduleInfo?.title}</h2>
            </div>
          </div>
          <POSModule />
        </div>
      )
    }

    // Render Products module if selected
    if (currentModule === 'PRODUITS') {
      return (
        <div className="space-y-6">
          <div className="flex items-center gap-4">
            <Button
              variant="outline"
              onClick={() => setCurrentModule('HOME')}
              className="flex items-center gap-2"
            >
              <LayoutDashboard className="h-4 w-4" />
              Retour à l'accueil
            </Button>
            <div className={`flex items-center gap-3 p-4 rounded-lg ${moduleInfo?.color} text-white`}>
              {moduleInfo?.icon}
              <h2 className="text-2xl font-bold">{moduleInfo?.title}</h2>
            </div>
          </div>
          <ProduitListe />
        </div>
      )
    }

    // Render Atelier module if selected
    if (currentModule === 'ATELIER') {
      return (
        <div className="space-y-6">
          <div className="flex items-center gap-4">
            <Button
              variant="outline"
              onClick={() => setCurrentModule('HOME')}
              className="flex items-center gap-2"
            >
              <LayoutDashboard className="h-4 w-4" />
              Retour à l'accueil
            </Button>
            <div className={`flex items-center gap-3 p-4 rounded-lg ${moduleInfo?.color} text-white`}>
              {moduleInfo?.icon}
              <h2 className="text-2xl font-bold">{moduleInfo?.title}</h2>
            </div>
          </div>
          <AtelierModule />
        </div>
      )
    }

    // Render Suppliers module if selected
    if (currentModule === 'FOURNISSEURS') {
      return (
        <div className="space-y-6">
          <div className="flex items-center gap-4">
            <Button
              variant="outline"
              onClick={() => setCurrentModule('HOME')}
              className="flex items-center gap-2"
            >
              <LayoutDashboard className="h-4 w-4" />
              Retour à l'accueil
            </Button>
            <div className={`flex items-center gap-3 p-4 rounded-lg ${moduleInfo?.color} text-white`}>
              {moduleInfo?.icon}
              <h2 className="text-2xl font-bold">{moduleInfo?.title}</h2>
            </div>
          </div>
          <SupplierList />
        </div>
      )
    }

    // Render Purchases module if selected
    if (currentModule === 'ACHATS') {
      return (
        <div className="space-y-6">
          <div className="flex items-center gap-4">
            <Button
              variant="outline"
              onClick={() => setCurrentModule('HOME')}
              className="flex items-center gap-2"
            >
              <LayoutDashboard className="h-4 w-4" />
              Retour à l'accueil
            </Button>
            <div className={`flex items-center gap-3 p-4 rounded-lg ${moduleInfo?.color} text-white`}>
              {moduleInfo?.icon}
              <h2 className="text-2xl font-bold">{moduleInfo?.title}</h2>
            </div>
          </div>
          <PurchaseModule />
        </div>
      )
    }

    // Render Reports module if selected
    if (currentModule === 'RAPPORTS') {
      return (
        <div className="space-y-6">
          <div className="flex items-center gap-4">
            <Button
              variant="outline"
              onClick={() => setCurrentModule('HOME')}
              className="flex items-center gap-2"
            >
              <LayoutDashboard className="h-4 w-4" />
              Retour à l'accueil
            </Button>
            <div className={`flex items-center gap-3 p-4 rounded-lg ${moduleInfo?.color} text-white`}>
              {moduleInfo?.icon}
              <h2 className="text-2xl font-bold">{moduleInfo?.title}</h2>
            </div>
          </div>
          <ReportsModule />
        </div>
      )
    }

    return (
      <div className="space-y-6">
        <div className="flex items-center gap-4">
          <Button
            variant="outline"
            onClick={() => setCurrentModule('HOME')}
            className="flex items-center gap-2"
          >
            <LayoutDashboard className="h-4 w-4" />
            Retour à l'accueil
          </Button>
          <div className={`flex items-center gap-3 p-4 rounded-lg ${moduleInfo?.color} text-white`}>
            {moduleInfo?.icon}
            <h2 className="text-2xl font-bold">{moduleInfo?.title}</h2>
          </div>
        </div>

        <Card className="border-2 border-dashed">
          <CardContent className="flex flex-col items-center justify-center py-16">
            <div className={`p-6 rounded-full ${moduleInfo?.color} bg-opacity-10 mb-4`}>
              <Eye className="h-16 w-16 text-gray-400" />
            </div>
            <h3 className="text-xl font-semibold text-gray-700 mb-2">
              Module en développement
            </h3>
            <p className="text-gray-500 text-center max-w-md">
              Le module <strong>{moduleInfo?.title}</strong> est actuellement en cours de développement.
              Veuillez revenir ultérieurement.
            </p>
          </CardContent>
        </Card>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100">
      <header className="bg-white border-b shadow-sm">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="p-2 bg-primary rounded-lg">
                <Eye className="h-6 w-6 text-primary-foreground" />
              </div>
              <div>
                <h1 className="text-xl font-bold text-gray-900">OptiqueStock</h1>
                <p className="text-xs text-gray-500">Gestion de Magasin d'Optique</p>
              </div>
            </div>
            <div className="flex items-center gap-4">
              <Badge variant="outline" className="text-sm">
                v1.0.0
              </Badge>
              <div className="flex items-center gap-2 text-sm text-gray-600">
                <User className="h-4 w-4" />
                <span className="hidden sm:inline">{session?.user?.name}</span>
              </div>
              <Button
                variant="ghost"
                size="icon"
                onClick={() => signOut({ callbackUrl: '/login' })}
                title="Se déconnecter"
              >
                <LogOut className="h-4 w-4" />
              </Button>
            </div>
          </div>
        </div>
      </header>

      <main className="container mx-auto px-4 py-8">
        {renderModule()}
      </main>

      <footer className="bg-white border-t mt-auto">
        <div className="container mx-auto px-4 py-4">
          <div className="flex flex-col md:flex-row items-center justify-between gap-4">
            <p className="text-sm text-gray-500">
              © 2024 OptiqueStock. Tous droits réservés.
            </p>
            <div className="flex items-center gap-4 text-sm text-gray-500">
              <span>Support: support@optiquestock.com</span>
              <span>•</span>
              <span>Version 1.0.0</span>
            </div>
          </div>
        </div>
      </footer>
    </div>
  )
}
