import { useState } from "react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { toast } from "@/hooks/use-toast";
import { queryClient, apiRequest } from "@/lib/queryClient";
import { Search, Settings2, Shield, Trophy, Users, Calendar, MapPin, ArrowRightLeft } from "lucide-react";

type Module = {
  id: number;
  name: string;
  displayName: string;
  description?: string;
  category: string;
  isActive: boolean;
  requiredTier: string;
  createdAt: string;
  updatedAt: string;
};

export default function ModuleManagement() {
  const [searchQuery, setSearchQuery] = useState("");

  const { data: modules = [], isLoading } = useQuery<Module[]>({
    queryKey: ["/api/modules"],
  });

  const updateModuleMutation = useMutation({
    mutationFn: async ({ id, isActive }: { id: number; isActive: boolean }) => {
      await apiRequest("PUT", `/api/modules/${id}`, { isActive });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/modules"] });
      toast({
        title: "Success",
        description: "Module status updated successfully",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description: error.message || "Failed to update module",
        variant: "destructive",
      });
    },
  });

  const handleToggleModule = (moduleId: number, currentStatus: boolean) => {
    updateModuleMutation.mutate({
      id: moduleId,
      isActive: !currentStatus,
    });
  };

  const filteredModules = modules.filter((module) =>
    module.displayName.toLowerCase().includes(searchQuery.toLowerCase()) ||
    module.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
    module.category.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const getCategoryBadgeVariant = (category: string) => {
    switch (category) {
      case "core":
        return "default";
      case "analytics":
        return "secondary";
      case "communication":
        return "outline";
      case "advanced":
        return "destructive";
      default:
        return "default";
    }
  };

  const getModuleIcon = (moduleName: string) => {
    const name = moduleName.toLowerCase();
    if (name.includes("league") || name.includes("tournament")) return Trophy;
    if (name.includes("fixture") || name.includes("match")) return Calendar;
    if (name.includes("venue")) return MapPin;
    if (name.includes("transfer")) return ArrowRightLeft;
    if (name.includes("team")) return Users;
    if (name.includes("admin")) return Shield;
    return Settings2;
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100 p-4 md:p-8">
      <div className="max-w-7xl mx-auto space-y-6">
        {/* Header */}
        <div className="bg-white rounded-lg shadow-sm p-6 border border-gray-200">
          <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
            <div>
              <h1 className="text-3xl font-bold text-gray-900 flex items-center gap-3">
                <Shield className="h-8 w-8 text-primary" />
                Module Management
              </h1>
              <p className="text-gray-600 mt-2">
                Enable or disable platform modules for all organizations
              </p>
            </div>
          </div>
        </div>

        {/* Search and Filters */}
        <Card>
          <CardHeader>
            <CardTitle>Available Modules</CardTitle>
            <CardDescription>
              Manage which features are available on the platform
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="flex flex-col md:flex-row gap-4 mb-6">
              <div className="relative flex-1">
                <Search className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
                <Input
                  placeholder="Search modules..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-10"
                  data-testid="input-search-modules"
                />
              </div>
            </div>

            {/* Modules Table */}
            {isLoading ? (
              <div className="flex justify-center items-center py-12">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
              </div>
            ) : (
              <div className="border rounded-lg overflow-hidden">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="w-[50px]"></TableHead>
                      <TableHead>Module Name</TableHead>
                      <TableHead>Category</TableHead>
                      <TableHead>Required Tier</TableHead>
                      <TableHead>Status</TableHead>
                      <TableHead className="w-[100px]">Actions</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {filteredModules.length === 0 ? (
                      <TableRow>
                        <TableCell colSpan={6} className="text-center py-8 text-gray-500">
                          No modules found
                        </TableCell>
                      </TableRow>
                    ) : (
                      filteredModules.map((module) => {
                        const Icon = getModuleIcon(module.name);
                        return (
                          <TableRow key={module.id}>
                            <TableCell>
                              <Icon className="h-5 w-5 text-gray-500" />
                            </TableCell>
                            <TableCell>
                              <div>
                                <div className="font-medium">{module.displayName}</div>
                                {module.description && (
                                  <div className="text-sm text-gray-500">{module.description}</div>
                                )}
                              </div>
                            </TableCell>
                            <TableCell>
                              <Badge variant={getCategoryBadgeVariant(module.category)}>
                                {module.category}
                              </Badge>
                            </TableCell>
                            <TableCell>
                              <span className="text-sm capitalize">{module.requiredTier}</span>
                            </TableCell>
                            <TableCell>
                              <Badge variant={module.isActive ? "default" : "secondary"}>
                                {module.isActive ? "Active" : "Inactive"}
                              </Badge>
                            </TableCell>
                            <TableCell>
                              <Switch
                                checked={module.isActive}
                                onCheckedChange={() => handleToggleModule(module.id, module.isActive)}
                                data-testid={`switch-module-${module.id}`}
                              />
                            </TableCell>
                          </TableRow>
                        );
                      })
                    )}
                  </TableBody>
                </Table>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Module Categories Info */}
        <Card>
          <CardHeader>
            <CardTitle>Module Categories</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
              <div className="p-4 bg-blue-50 rounded-lg">
                <Badge variant="default" className="mb-2">Core</Badge>
                <p className="text-sm text-gray-600">Essential platform features</p>
              </div>
              <div className="p-4 bg-purple-50 rounded-lg">
                <Badge variant="secondary" className="mb-2">Analytics</Badge>
                <p className="text-sm text-gray-600">Data analysis and reporting</p>
              </div>
              <div className="p-4 bg-green-50 rounded-lg">
                <Badge variant="outline" className="mb-2">Communication</Badge>
                <p className="text-sm text-gray-600">Messaging and notifications</p>
              </div>
              <div className="p-4 bg-red-50 rounded-lg">
                <Badge variant="destructive" className="mb-2">Advanced</Badge>
                <p className="text-sm text-gray-600">Premium platform features</p>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
