import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { useToast } from "@/hooks/use-toast";
import { apiRequest } from "@/lib/queryClient";
import { Building2, Users, Settings, Shield, Plus, Edit, Mail, Server, Key, FileText, Save, Trash2 } from "lucide-react";

interface Organization {
  id: number;
  name: string;
  type: string;
  sport: string;
  contactEmail: string;
  subscriptionTier: string;
  subscriptionStatus: string;
  createdAt: string;
}

interface Module {
  id: number;
  name: string;
  displayName: string;
  description: string;
  category: string;
  requiredTier: string;
}

interface SubscriptionPlan {
  id: number;
  name: string;
  tier: string;
  price: number;
  interval: string;
  features: string[];
  maxTeams?: number;
  maxUsers?: number;
}

interface ModulePermission {
  id: number;
  organizationId: number;
  moduleId: number;
  isEnabled: boolean;
  enabledBy: string;
  updatedAt: string;
}

interface CmsPage {
  id: number;
  title: string;
  slug: string;
  content: any;
  isPublished: boolean;
  createdAt: string;
  updatedAt: string;
}

interface CmsFeature {
  id: number;
  title: string;
  description: string;
  icon: string;
  features: any;
  color: string;
  isActive: boolean;
}

interface CmsStat {
  id: number;
  label: string;
  value: string;
  description: string;
  isActive: boolean;
}

interface CmsTestimonial {
  id: number;
  name: string;
  position: string;
  company: string;
  content: string;
  rating: number;
  imageUrl?: string;
  isActive: boolean;
}

export default function SuperAdminPage() {
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const [selectedOrganization, setSelectedOrganization] = useState<Organization | null>(null);
  const [showCreateOrgDialog, setShowCreateOrgDialog] = useState(false);
  const [showCreateModuleDialog, setShowCreateModuleDialog] = useState(false);

  // Fetch organizations with caching
  const { data: organizations = [], isLoading: orgsLoading } = useQuery({
    queryKey: ["/api/superadmin/organizations"],
    staleTime: 2 * 60 * 1000, // 2 minutes
    gcTime: 5 * 60 * 1000, // 5 minutes
  });

  // Fetch modules with caching
  const { data: modules = [], isLoading: modulesLoading } = useQuery({
    queryKey: ["/api/superadmin/modules"],
    staleTime: 5 * 60 * 1000, // 5 minutes
    gcTime: 10 * 60 * 1000, // 10 minutes
  });

  // Fetch subscription plans with caching
  const { data: subscriptionPlans = [], isLoading: plansLoading } = useQuery({
    queryKey: ["/api/superadmin/plans"],
    staleTime: 60 * 60 * 1000, // 1 hour
    gcTime: 2 * 60 * 60 * 1000, // 2 hours
  });

  // Fetch organization module permissions
  const { data: orgPermissions = [], isLoading: permissionsLoading } = useQuery({
    queryKey: ["/api/superadmin/organizations", selectedOrganization?.id, "modules"],
    enabled: !!selectedOrganization,
  });

  // CMS Queries
  const { data: cmsFeatures = [], isLoading: featuresLoading } = useQuery({
    queryKey: ["/api/cms/features"],
    staleTime: 5 * 60 * 1000, // 5 minutes
    gcTime: 10 * 60 * 1000, // 10 minutes
  });

  const { data: cmsStats = [], isLoading: statsLoading } = useQuery({
    queryKey: ["/api/cms/stats"],
    staleTime: 5 * 60 * 1000,
    gcTime: 10 * 60 * 1000,
  });

  const { data: cmsTestimonials = [], isLoading: testimonialsLoading } = useQuery({
    queryKey: ["/api/cms/testimonials"],
    staleTime: 5 * 60 * 1000,
    gcTime: 10 * 60 * 1000,
  });

  const { data: cmsPages = [], isLoading: pagesLoading } = useQuery({
    queryKey: ["/api/cms/pages"],
    staleTime: 5 * 60 * 1000,
    gcTime: 10 * 60 * 1000,
  });

  // CMS State
  const [editingFeature, setEditingFeature] = useState<CmsFeature | null>(null);
  const [editingStat, setEditingStat] = useState<CmsStat | null>(null);
  const [editingTestimonial, setEditingTestimonial] = useState<CmsTestimonial | null>(null);
  const [showFeatureDialog, setShowFeatureDialog] = useState(false);
  const [showStatDialog, setShowStatDialog] = useState(false);
  const [showTestimonialDialog, setShowTestimonialDialog] = useState(false);

  // Update organization subscription
  const updateSubscriptionMutation = useMutation({
    mutationFn: async ({ orgId, data }: { orgId: number; data: any }) => {
      const response = await apiRequest("PUT", `/api/superadmin/organizations/${orgId}/subscription`, data);
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/superadmin/organizations"] });
      toast({ title: "Subscription updated successfully" });
    },
    onError: () => {
      toast({ title: "Failed to update subscription", variant: "destructive" });
    },
  });

  // Toggle module permission
  const toggleModuleMutation = useMutation({
    mutationFn: async ({ orgId, moduleId, enabled }: { orgId: number; moduleId: number; enabled: boolean }) => {
      const response = await apiRequest("PUT", `/api/superadmin/organizations/${orgId}/modules/${moduleId}`, { enabled });
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/superadmin/organizations", selectedOrganization?.id, "modules"] });
      toast({ title: "Module permission updated" });
    },
    onError: () => {
      toast({ title: "Failed to update module permission", variant: "destructive" });
    },
  });

  // Create organization
  const createOrgMutation = useMutation({
    mutationFn: async (data: any) => {
      const response = await apiRequest("POST", "/api/superadmin/organizations", data);
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/superadmin/organizations"] });
      setShowCreateOrgDialog(false);
      toast({ title: "Organization created successfully" });
    },
    onError: () => {
      toast({ title: "Failed to create organization", variant: "destructive" });
    },
  });

  // Create module
  const createModuleMutation = useMutation({
    mutationFn: async (data: any) => {
      const response = await apiRequest("POST", "/api/superadmin/modules", data);
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/superadmin/modules"] });
      setShowCreateModuleDialog(false);
      toast({ title: "Module created successfully" });
    },
    onError: () => {
      toast({ title: "Failed to create module", variant: "destructive" });
    },
  });

  // CMS Mutations
  const createFeatureMutation = useMutation({
    mutationFn: async (data: any) => {
      const response = await apiRequest("POST", "/api/cms/features", data);
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/cms/features"] });
      setShowFeatureDialog(false);
      setEditingFeature(null);
      toast({ title: "Feature saved successfully" });
    },
    onError: () => {
      toast({ title: "Failed to save feature", variant: "destructive" });
    },
  });

  const updateFeatureMutation = useMutation({
    mutationFn: async ({ id, data }: { id: number; data: any }) => {
      const response = await apiRequest("PUT", `/api/cms/features/${id}`, data);
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/cms/features"] });
      setShowFeatureDialog(false);
      setEditingFeature(null);
      toast({ title: "Feature updated successfully" });
    },
    onError: () => {
      toast({ title: "Failed to update feature", variant: "destructive" });
    },
  });

  const deleteFeatureMutation = useMutation({
    mutationFn: async (id: number) => {
      await apiRequest("DELETE", `/api/cms/features/${id}`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/cms/features"] });
      toast({ title: "Feature deleted successfully" });
    },
    onError: () => {
      toast({ title: "Failed to delete feature", variant: "destructive" });
    },
  });

  const createStatMutation = useMutation({
    mutationFn: async (data: any) => {
      const response = await apiRequest("POST", "/api/cms/stats", data);
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/cms/stats"] });
      setShowStatDialog(false);
      setEditingStat(null);
      toast({ title: "Statistic saved successfully" });
    },
    onError: () => {
      toast({ title: "Failed to save statistic", variant: "destructive" });
    },
  });

  const updateStatMutation = useMutation({
    mutationFn: async ({ id, data }: { id: number; data: any }) => {
      const response = await apiRequest("PUT", `/api/cms/stats/${id}`, data);
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/cms/stats"] });
      setShowStatDialog(false);
      setEditingStat(null);
      toast({ title: "Statistic updated successfully" });
    },
    onError: () => {
      toast({ title: "Failed to update statistic", variant: "destructive" });
    },
  });

  const createTestimonialMutation = useMutation({
    mutationFn: async (data: any) => {
      const response = await apiRequest("POST", "/api/cms/testimonials", data);
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/cms/testimonials"] });
      setShowTestimonialDialog(false);
      setEditingTestimonial(null);
      toast({ title: "Testimonial saved successfully" });
    },
    onError: () => {
      toast({ title: "Failed to save testimonial", variant: "destructive" });
    },
  });

  const updateTestimonialMutation = useMutation({
    mutationFn: async ({ id, data }: { id: number; data: any }) => {
      const response = await apiRequest("PUT", `/api/cms/testimonials/${id}`, data);
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/cms/testimonials"] });
      setShowTestimonialDialog(false);
      setEditingTestimonial(null);
      toast({ title: "Testimonial updated successfully" });
    },
    onError: () => {
      toast({ title: "Failed to update testimonial", variant: "destructive" });
    },
  });

  const deleteTestimonialMutation = useMutation({
    mutationFn: async (id: number) => {
      await apiRequest("DELETE", `/api/cms/testimonials/${id}`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/cms/testimonials"] });
      toast({ title: "Testimonial deleted successfully" });
    },
    onError: () => {
      toast({ title: "Failed to delete testimonial", variant: "destructive" });
    },
  });

  const handleUpdateSubscription = (orgId: number, tier: string, status: string) => {
    updateSubscriptionMutation.mutate({
      orgId,
      data: { subscriptionTier: tier, subscriptionStatus: status },
    });
  };

  const handleToggleModule = (moduleId: number, enabled: boolean) => {
    if (!selectedOrganization) return;
    toggleModuleMutation.mutate({
      orgId: selectedOrganization.id,
      moduleId,
      enabled,
    });
  };

  const isModuleEnabled = (moduleId: number) => {
    return orgPermissions.some((p: ModulePermission) => p.moduleId === moduleId && p.isEnabled);
  };

  const getStatusBadgeVariant = (status: string) => {
    switch (status) {
      case "active": return "default";
      case "trial": return "secondary";
      case "suspended": return "destructive";
      case "cancelled": return "outline";
      default: return "secondary";
    }
  };

  const getTierBadgeVariant = (tier: string) => {
    return tier === "premium" ? "default" : "secondary";
  };

  if (orgsLoading || modulesLoading || plansLoading) {
    return (
      <div className="flex items-center justify-center h-96">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
      </div>
    );
  }

  return (
    <div className="container mx-auto p-6">
      <div className="flex items-center justify-between mb-8">
        <div>
          <h1 className="text-3xl font-bold flex items-center gap-2">
            <Shield className="h-8 w-8" />
            Super Admin Dashboard
          </h1>
          <p className="text-muted-foreground mt-2">
            Manage organizations, subscriptions, and module permissions
          </p>
        </div>
      </div>

      <Tabs defaultValue="organizations" className="space-y-6">
        <TabsList className="grid w-full grid-cols-6">
          <TabsTrigger value="organizations">Organizations</TabsTrigger>
          <TabsTrigger value="modules">Modules</TabsTrigger>
          <TabsTrigger value="plans">Subscription Plans</TabsTrigger>
          <TabsTrigger value="permissions">Permissions</TabsTrigger>
          <TabsTrigger value="smtp">SMTP Settings</TabsTrigger>
          <TabsTrigger value="cms">CMS Management</TabsTrigger>
        </TabsList>

        <TabsContent value="organizations">
          <div className="space-y-6">
            <div className="flex justify-between items-center">
              <h2 className="text-2xl font-semibold">Organizations</h2>
              <Dialog open={showCreateOrgDialog} onOpenChange={setShowCreateOrgDialog}>
                <DialogTrigger asChild>
                  <Button>
                    <Plus className="h-4 w-4 mr-2" />
                    Add Organization
                  </Button>
                </DialogTrigger>
                <DialogContent>
                  <DialogHeader>
                    <DialogTitle>Create New Organization</DialogTitle>
                    <DialogDescription>
                      Add a new organization to the platform
                    </DialogDescription>
                  </DialogHeader>
                  <form onSubmit={(e) => {
                    e.preventDefault();
                    const formData = new FormData(e.currentTarget);
                    createOrgMutation.mutate({
                      name: formData.get("name"),
                      type: formData.get("type"),
                      sport: formData.get("sport"),
                      contactEmail: formData.get("contactEmail"),
                      subscriptionTier: formData.get("subscriptionTier"),
                      subscriptionStatus: "trial",
                    });
                  }}>
                    <div className="grid gap-4 py-4">
                      <div className="grid grid-cols-4 items-center gap-4">
                        <Label htmlFor="name" className="text-right">Name</Label>
                        <Input id="name" name="name" className="col-span-3" required />
                      </div>
                      <div className="grid grid-cols-4 items-center gap-4">
                        <Label htmlFor="type" className="text-right">Type</Label>
                        <Select name="type" required>
                          <SelectTrigger className="col-span-3">
                            <SelectValue placeholder="Select type" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="club">Club</SelectItem>
                            <SelectItem value="association">Association</SelectItem>
                            <SelectItem value="league">League</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                      <div className="grid grid-cols-4 items-center gap-4">
                        <Label htmlFor="sport" className="text-right">Sport</Label>
                        <Input id="sport" name="sport" className="col-span-3" required />
                      </div>
                      <div className="grid grid-cols-4 items-center gap-4">
                        <Label htmlFor="contactEmail" className="text-right">Contact Email</Label>
                        <Input id="contactEmail" name="contactEmail" type="email" className="col-span-3" required />
                      </div>
                      <div className="grid grid-cols-4 items-center gap-4">
                        <Label htmlFor="subscriptionTier" className="text-right">Tier</Label>
                        <Select name="subscriptionTier" required>
                          <SelectTrigger className="col-span-3">
                            <SelectValue placeholder="Select tier" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="regular">Regular</SelectItem>
                            <SelectItem value="premium">Premium</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                    </div>
                    <DialogFooter>
                      <Button type="submit" disabled={createOrgMutation.isPending}>
                        {createOrgMutation.isPending ? "Creating..." : "Create Organization"}
                      </Button>
                    </DialogFooter>
                  </form>
                </DialogContent>
              </Dialog>
            </div>

            <div className="grid gap-4">
              {organizations.map((org: Organization) => (
                <Card key={org.id} className="p-6">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-4">
                      <Building2 className="h-8 w-8 text-primary" />
                      <div>
                        <h3 className="font-semibold text-lg">{org.name}</h3>
                        <p className="text-sm text-muted-foreground">
                          {org.type} • {org.sport} • {org.contactEmail}
                        </p>
                      </div>
                    </div>
                    <div className="flex items-center gap-3">
                      <Badge variant={getTierBadgeVariant(org.subscriptionTier)}>
                        {org.subscriptionTier}
                      </Badge>
                      <Badge variant={getStatusBadgeVariant(org.subscriptionStatus)}>
                        {org.subscriptionStatus}
                      </Badge>
                      <div className="flex gap-2">
                        <Select
                          value={org.subscriptionTier}
                          onValueChange={(tier) => handleUpdateSubscription(org.id, tier, org.subscriptionStatus)}
                        >
                          <SelectTrigger className="w-32">
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="regular">Regular</SelectItem>
                            <SelectItem value="premium">Premium</SelectItem>
                          </SelectContent>
                        </Select>
                        <Select
                          value={org.subscriptionStatus}
                          onValueChange={(status) => handleUpdateSubscription(org.id, org.subscriptionTier, status)}
                        >
                          <SelectTrigger className="w-32">
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="active">Active</SelectItem>
                            <SelectItem value="trial">Trial</SelectItem>
                            <SelectItem value="suspended">Suspended</SelectItem>
                            <SelectItem value="cancelled">Cancelled</SelectItem>
                          </SelectContent>
                        </Select>
                        <Button
                          variant="outline"
                          onClick={() => setSelectedOrganization(org)}
                        >
                          <Settings className="h-4 w-4 mr-2" />
                          Manage
                        </Button>
                      </div>
                    </div>
                  </div>
                </Card>
              ))}
            </div>
          </div>
        </TabsContent>

        <TabsContent value="modules">
          <div className="space-y-6">
            <div className="flex justify-between items-center">
              <h2 className="text-2xl font-semibold">Platform Modules</h2>
              <Dialog open={showCreateModuleDialog} onOpenChange={setShowCreateModuleDialog}>
                <DialogTrigger asChild>
                  <Button>
                    <Plus className="h-4 w-4 mr-2" />
                    Add Module
                  </Button>
                </DialogTrigger>
                <DialogContent>
                  <DialogHeader>
                    <DialogTitle>Create New Module</DialogTitle>
                    <DialogDescription>
                      Add a new feature module to the platform
                    </DialogDescription>
                  </DialogHeader>
                  <form onSubmit={(e) => {
                    e.preventDefault();
                    const formData = new FormData(e.currentTarget);
                    createModuleMutation.mutate({
                      name: formData.get("name"),
                      displayName: formData.get("displayName"),
                      description: formData.get("description"),
                      category: formData.get("category"),
                      requiredTier: formData.get("requiredTier"),
                    });
                  }}>
                    <div className="grid gap-4 py-4">
                      <div className="grid grid-cols-4 items-center gap-4">
                        <Label htmlFor="name" className="text-right">Name</Label>
                        <Input id="name" name="name" className="col-span-3" required />
                      </div>
                      <div className="grid grid-cols-4 items-center gap-4">
                        <Label htmlFor="displayName" className="text-right">Display Name</Label>
                        <Input id="displayName" name="displayName" className="col-span-3" required />
                      </div>
                      <div className="grid grid-cols-4 items-center gap-4">
                        <Label htmlFor="description" className="text-right">Description</Label>
                        <Textarea id="description" name="description" className="col-span-3" required />
                      </div>
                      <div className="grid grid-cols-4 items-center gap-4">
                        <Label htmlFor="category" className="text-right">Category</Label>
                        <Select name="category" required>
                          <SelectTrigger className="col-span-3">
                            <SelectValue placeholder="Select category" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="core">Core</SelectItem>
                            <SelectItem value="analytics">Analytics</SelectItem>
                            <SelectItem value="advanced">Advanced</SelectItem>
                            <SelectItem value="communication">Communication</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                      <div className="grid grid-cols-4 items-center gap-4">
                        <Label htmlFor="requiredTier" className="text-right">Required Tier</Label>
                        <Select name="requiredTier" required>
                          <SelectTrigger className="col-span-3">
                            <SelectValue placeholder="Select tier" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="regular">Regular</SelectItem>
                            <SelectItem value="premium">Premium</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                    </div>
                    <DialogFooter>
                      <Button type="submit" disabled={createModuleMutation.isPending}>
                        {createModuleMutation.isPending ? "Creating..." : "Create Module"}
                      </Button>
                    </DialogFooter>
                  </form>
                </DialogContent>
              </Dialog>
            </div>

            <div className="grid gap-4">
              {modules.map((module: Module) => (
                <Card key={module.id} className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <h3 className="font-semibold text-lg">{module.displayName}</h3>
                      <p className="text-sm text-muted-foreground mb-2">{module.description}</p>
                      <div className="flex gap-2">
                        <Badge variant="outline">{module.category}</Badge>
                        <Badge variant={module.requiredTier === "premium" ? "default" : "secondary"}>
                          {module.requiredTier}
                        </Badge>
                      </div>
                    </div>
                  </div>
                </Card>
              ))}
            </div>
          </div>
        </TabsContent>

        <TabsContent value="plans">
          <div className="space-y-6">
            <h2 className="text-2xl font-semibold">Subscription Plans</h2>
            <div className="grid gap-4">
              {subscriptionPlans.map((plan: SubscriptionPlan) => (
                <Card key={plan.id} className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <h3 className="font-semibold text-lg">{plan.name}</h3>
                      <p className="text-2xl font-bold text-primary">
                        ${(plan.price / 100).toFixed(2)} / {plan.interval}
                      </p>
                      <div className="flex gap-2 mt-2">
                        <Badge variant={plan.tier === "premium" ? "default" : "secondary"}>
                          {plan.tier}
                        </Badge>
                        {plan.maxTeams && (
                          <Badge variant="outline">Max {plan.maxTeams} teams</Badge>
                        )}
                        {plan.maxUsers && (
                          <Badge variant="outline">Max {plan.maxUsers} users</Badge>
                        )}
                      </div>
                    </div>
                    <div className="text-right">
                      <p className="text-sm text-muted-foreground mb-2">
                        {plan.features.length} features included
                      </p>
                    </div>
                  </div>
                </Card>
              ))}
            </div>
          </div>
        </TabsContent>

        <TabsContent value="permissions">
          <div className="space-y-6">
            <h2 className="text-2xl font-semibold">Module Permissions</h2>
            
            {!selectedOrganization ? (
              <Card className="p-8 text-center">
                <Users className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
                <h3 className="text-lg font-semibold mb-2">Select an Organization</h3>
                <p className="text-muted-foreground">
                  Choose an organization from the Organizations tab to manage its module permissions.
                </p>
              </Card>
            ) : (
              <div className="space-y-4">
                <Card className="p-4">
                  <div className="flex items-center justify-between">
                    <div>
                      <h3 className="font-semibold">{selectedOrganization.name}</h3>
                      <p className="text-sm text-muted-foreground">
                        {selectedOrganization.subscriptionTier} tier • {selectedOrganization.subscriptionStatus}
                      </p>
                    </div>
                    <Button variant="outline" onClick={() => setSelectedOrganization(null)}>
                      Change Organization
                    </Button>
                  </div>
                </Card>

                {permissionsLoading ? (
                  <div className="flex items-center justify-center py-8">
                    <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
                  </div>
                ) : (
                  <div className="grid gap-4">
                    {modules.map((module: Module) => {
                      const enabled = isModuleEnabled(module.id);
                      const canAccess = selectedOrganization.subscriptionTier === "premium" || 
                                       module.requiredTier === "regular";
                      
                      return (
                        <Card key={module.id} className="p-4">
                          <div className="flex items-center justify-between">
                            <div className="flex-1">
                              <div className="flex items-center gap-3">
                                <h4 className="font-semibold">{module.displayName}</h4>
                                <Badge variant="outline">{module.category}</Badge>
                                <Badge variant={module.requiredTier === "premium" ? "default" : "secondary"}>
                                  {module.requiredTier}
                                </Badge>
                              </div>
                              <p className="text-sm text-muted-foreground mt-1">
                                {module.description}
                              </p>
                              {!canAccess && (
                                <p className="text-sm text-amber-600 mt-1">
                                  Premium tier required for this module
                                </p>
                              )}
                            </div>
                            <Switch
                              checked={enabled}
                              disabled={!canAccess}
                              onCheckedChange={(checked) => handleToggleModule(module.id, checked)}
                            />
                          </div>
                        </Card>
                      );
                    })}
                  </div>
                )}
              </div>
            )}
          </div>
        </TabsContent>

        <TabsContent value="smtp">
          <div className="space-y-6">
            <div className="flex justify-between items-center">
              <h2 className="text-2xl font-semibold">SMTP Configuration</h2>
              <Badge variant="outline" className="bg-blue-50 text-blue-700 border-blue-200">
                <Server className="h-3 w-3 mr-1" />
                Email Settings
              </Badge>
            </div>

            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <Mail className="h-5 w-5 text-blue-600" />
                  <span>Email Service Configuration</span>
                </CardTitle>
                <CardDescription>
                  Configure SMTP settings for system emails, notifications, and user communications
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div className="space-y-4">
                    <div>
                      <Label htmlFor="smtp-host">SMTP Host</Label>
                      <Input 
                        id="smtp-host" 
                        placeholder="smtp.gmail.com" 
                        defaultValue={import.meta.env.VITE_SMTP_HOST || ""}
                      />
                    </div>
                    <div>
                      <Label htmlFor="smtp-port">SMTP Port</Label>
                      <Input 
                        id="smtp-port" 
                        type="number" 
                        placeholder="587" 
                        defaultValue={import.meta.env.VITE_SMTP_PORT || "587"}
                      />
                    </div>
                    <div>
                      <Label htmlFor="smtp-username">Username</Label>
                      <Input 
                        id="smtp-username" 
                        placeholder="your-email@gmail.com"
                        defaultValue={import.meta.env.VITE_SMTP_USERNAME || ""}
                      />
                    </div>
                    <div>
                      <Label htmlFor="smtp-password">Password / App Password</Label>
                      <Input 
                        id="smtp-password" 
                        type="password" 
                        placeholder="Enter SMTP password"
                      />
                    </div>
                  </div>

                  <div className="space-y-4">
                    <div className="flex items-center space-x-2">
                      <Switch id="smtp-secure" defaultChecked />
                      <Label htmlFor="smtp-secure">Use TLS/SSL</Label>
                    </div>
                    
                    <div>
                      <Label htmlFor="from-email">From Email Address</Label>
                      <Input 
                        id="from-email" 
                        placeholder="noreply@sportspro.com"
                        defaultValue={import.meta.env.VITE_FROM_EMAIL || ""}
                      />
                    </div>
                    
                    <div>
                      <Label htmlFor="from-name">From Name</Label>
                      <Input 
                        id="from-name" 
                        placeholder="SportsPro Platform"
                        defaultValue={import.meta.env.VITE_FROM_NAME || "SportsPro"}
                      />
                    </div>

                    <div>
                      <Label htmlFor="reply-to">Reply-To Email</Label>
                      <Input 
                        id="reply-to" 
                        placeholder="support@sportspro.com"
                        defaultValue={import.meta.env.VITE_REPLY_TO_EMAIL || ""}
                      />
                    </div>
                  </div>
                </div>

                <div className="border-t pt-6">
                  <h3 className="text-lg font-semibold mb-4">Email Templates & Settings</h3>
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div className="flex items-center space-x-2">
                      <Switch id="welcome-emails" defaultChecked />
                      <Label htmlFor="welcome-emails">Welcome Emails</Label>
                    </div>
                    <div className="flex items-center space-x-2">
                      <Switch id="notification-emails" defaultChecked />
                      <Label htmlFor="notification-emails">Notifications</Label>
                    </div>
                    <div className="flex items-center space-x-2">
                      <Switch id="attendance-emails" defaultChecked />
                      <Label htmlFor="attendance-emails">Attendance Alerts</Label>
                    </div>
                  </div>
                </div>

                <div className="flex space-x-3">
                  <Button className="bg-blue-600 hover:bg-blue-700">
                    <Key className="h-4 w-4 mr-2" />
                    Save Configuration
                  </Button>
                  <Button variant="outline">
                    <Mail className="h-4 w-4 mr-2" />
                    Test Email Connection
                  </Button>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>Alternative Email Providers</CardTitle>
                <CardDescription>
                  Quick setup guides for popular email services
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <div className="p-4 border rounded-lg">
                    <h4 className="font-semibold mb-2">Gmail</h4>
                    <p className="text-sm text-gray-600 mb-2">Use App Passwords for secure authentication</p>
                    <ul className="text-xs space-y-1 text-gray-500">
                      <li>• Host: smtp.gmail.com</li>
                      <li>• Port: 587 (TLS)</li>
                      <li>• Enable 2FA first</li>
                    </ul>
                  </div>
                  <div className="p-4 border rounded-lg">
                    <h4 className="font-semibold mb-2">SendGrid</h4>
                    <p className="text-sm text-gray-600 mb-2">High deliverability for transactional emails</p>
                    <ul className="text-xs space-y-1 text-gray-500">
                      <li>• Host: smtp.sendgrid.net</li>
                      <li>• Port: 587</li>
                      <li>• Use API key as password</li>
                    </ul>
                  </div>
                  <div className="p-4 border rounded-lg">
                    <h4 className="font-semibold mb-2">AWS SES</h4>
                    <p className="text-sm text-gray-600 mb-2">Scalable email service from Amazon</p>
                    <ul className="text-xs space-y-1 text-gray-500">
                      <li>• Host: email-smtp.region.amazonaws.com</li>
                      <li>• Port: 587</li>
                      <li>• Use IAM credentials</li>
                    </ul>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        {/* CMS Management Tab */}
        <TabsContent value="cms" className="space-y-6">
          {/* Landing Page Content Overview */}
          <Card className="mb-6">
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <FileText className="h-5 w-5" />
                Landing Page Content Management
              </CardTitle>
              <CardDescription>
                Edit all content that appears on the public landing page. Changes are reflected immediately.
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4 text-center">
                <div className="p-4 border rounded-lg">
                  <h3 className="font-semibold text-lg">{cmsFeatures?.length || 0}</h3>
                  <p className="text-sm text-gray-600">Features</p>
                </div>
                <div className="p-4 border rounded-lg">
                  <h3 className="font-semibold text-lg">{cmsStats?.length || 0}</h3>
                  <p className="text-sm text-gray-600">Statistics</p>
                </div>
                <div className="p-4 border rounded-lg">
                  <h3 className="font-semibold text-lg">{cmsTestimonials?.length || 0}</h3>
                  <p className="text-sm text-gray-600">Testimonials</p>
                </div>
              </div>
            </CardContent>
          </Card>

          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            
            {/* Features Management */}
            <Card className="col-span-full">
              <CardHeader>
                <div className="flex items-center justify-between">
                  <div>
                    <CardTitle className="flex items-center gap-2">
                      <FileText className="h-5 w-5" />
                      Features Management
                    </CardTitle>
                    <CardDescription>Manage landing page features section</CardDescription>
                  </div>
                  <Button 
                    onClick={() => {
                      setEditingFeature(null);
                      setShowFeatureDialog(true);
                    }}
                    size="sm"
                  >
                    <Plus className="h-4 w-4 mr-2" />
                    Add Feature
                  </Button>
                </div>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                  {cmsFeatures.map((feature: CmsFeature) => (
                    <div key={feature.id} className="border rounded-lg p-4 space-y-3">
                      <div className="flex items-start justify-between">
                        <div className="flex-1">
                          <h4 className="font-medium text-sm">{feature.title}</h4>
                          <p className="text-xs text-gray-600 mt-1">{feature.description}</p>
                          <Badge variant={feature.isActive ? "default" : "secondary"} className="mt-2 text-xs">
                            {feature.isActive ? "Active" : "Inactive"}
                          </Badge>
                        </div>
                        <div className="flex gap-1">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => {
                              setEditingFeature(feature);
                              setShowFeatureDialog(true);
                            }}
                          >
                            <Edit className="h-3 w-3" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => {
                              if (confirm("Are you sure you want to delete this feature?")) {
                                deleteFeatureMutation.mutate(feature.id);
                              }
                            }}
                          >
                            <Trash2 className="h-3 w-3" />
                          </Button>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>

            {/* Statistics Management */}
            <Card>
              <CardHeader>
                <div className="flex items-center justify-between">
                  <div>
                    <CardTitle className="text-base">Statistics</CardTitle>
                    <CardDescription className="text-sm">Social proof numbers</CardDescription>
                  </div>
                  <Button 
                    onClick={() => {
                      setEditingStat(null);
                      setShowStatDialog(true);
                    }}
                    size="sm"
                  >
                    <Plus className="h-4 w-4" />
                  </Button>
                </div>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  {cmsStats.map((stat: CmsStat) => (
                    <div key={stat.id} className="flex items-center justify-between p-3 border rounded">
                      <div>
                        <div className="font-medium text-sm">{stat.value}</div>
                        <div className="text-xs text-gray-600">{stat.label}</div>
                      </div>
                      <div className="flex gap-1">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => {
                            setEditingStat(stat);
                            setShowStatDialog(true);
                          }}
                        >
                          <Edit className="h-3 w-3" />
                        </Button>
                      </div>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>

            {/* Testimonials Management */}
            <Card className="col-span-full md:col-span-2">
              <CardHeader>
                <div className="flex items-center justify-between">
                  <div>
                    <CardTitle className="text-base">Testimonials</CardTitle>
                    <CardDescription className="text-sm">Customer reviews and feedback</CardDescription>
                  </div>
                  <Button 
                    onClick={() => {
                      setEditingTestimonial(null);
                      setShowTestimonialDialog(true);
                    }}
                    size="sm"
                  >
                    <Plus className="h-4 w-4 mr-2" />
                    Add Testimonial
                  </Button>
                </div>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  {cmsTestimonials.map((testimonial: CmsTestimonial) => (
                    <div key={testimonial.id} className="border rounded-lg p-4 space-y-3">
                      <div className="flex items-start justify-between">
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-2">
                            <h4 className="font-medium text-sm">{testimonial.name}</h4>
                            <Badge variant={testimonial.isActive ? "default" : "secondary"} className="text-xs">
                              {testimonial.isActive ? "Active" : "Inactive"}
                            </Badge>
                          </div>
                          <p className="text-xs text-gray-600">{testimonial.position} at {testimonial.company}</p>
                          <p className="text-xs mt-2 line-clamp-3">{testimonial.content}</p>
                          <div className="flex items-center mt-2">
                            {[...Array(5)].map((_, i) => (
                              <span key={i} className={`text-xs ${i < testimonial.rating ? 'text-yellow-400' : 'text-gray-300'}`}>★</span>
                            ))}
                          </div>
                        </div>
                        <div className="flex gap-1">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => {
                              setEditingTestimonial(testimonial);
                              setShowTestimonialDialog(true);
                            }}
                          >
                            <Edit className="h-3 w-3" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => {
                              if (confirm("Are you sure you want to delete this testimonial?")) {
                                deleteTestimonialMutation.mutate(testimonial.id);
                              }
                            }}
                          >
                            <Trash2 className="h-3 w-3" />
                          </Button>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          </div>

          {/* Feature Dialog */}
          <Dialog open={showFeatureDialog} onOpenChange={setShowFeatureDialog}>
            <DialogContent className="max-w-md">
              <DialogHeader>
                <DialogTitle>{editingFeature ? 'Edit Feature' : 'Add New Feature'}</DialogTitle>
                <DialogDescription>
                  {editingFeature ? 'Update this feature information' : 'Add a new feature to the landing page'}
                </DialogDescription>
              </DialogHeader>
              <form onSubmit={(e) => {
                e.preventDefault();
                const formData = new FormData(e.target as HTMLFormElement);
                const data = {
                  title: formData.get('title'),
                  description: formData.get('description'),
                  icon: formData.get('icon'),
                  features: JSON.parse(formData.get('features') as string || '[]'),
                  color: formData.get('color'),
                  isActive: formData.get('isActive') === 'on'
                };
                
                if (editingFeature) {
                  updateFeatureMutation.mutate({ id: editingFeature.id, data });
                } else {
                  createFeatureMutation.mutate(data);
                }
              }}>
                <div className="space-y-4 py-4">
                  <div>
                    <Label htmlFor="title">Title</Label>
                    <Input 
                      id="title" 
                      name="title" 
                      defaultValue={editingFeature?.title || ''}
                      required 
                    />
                  </div>
                  <div>
                    <Label htmlFor="description">Description</Label>
                    <Textarea 
                      id="description" 
                      name="description" 
                      defaultValue={editingFeature?.description || ''}
                      required 
                    />
                  </div>
                  <div>
                    <Label htmlFor="icon">Icon</Label>
                    <Select name="icon" defaultValue={editingFeature?.icon || 'BarChart3'}>
                      <SelectTrigger>
                        <SelectValue placeholder="Select an icon" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="Video">Video</SelectItem>
                        <SelectItem value="Brain">Brain</SelectItem>
                        <SelectItem value="Fingerprint">Fingerprint</SelectItem>
                        <SelectItem value="Users">Users</SelectItem>
                        <SelectItem value="BarChart3">BarChart3</SelectItem>
                        <SelectItem value="Calendar">Calendar</SelectItem>
                        <SelectItem value="Shield">Shield</SelectItem>
                        <SelectItem value="Settings">Settings</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div>
                    <Label htmlFor="features">Features (JSON array)</Label>
                    <Textarea 
                      id="features" 
                      name="features" 
                      placeholder='["Feature 1", "Feature 2", "Feature 3"]'
                      defaultValue={editingFeature?.features ? JSON.stringify(editingFeature.features) : ''}
                    />
                  </div>
                  <div>
                    <Label htmlFor="color">Color Gradient</Label>
                    <Input 
                      id="color" 
                      name="color" 
                      placeholder="from-blue-500 to-cyan-500"
                      defaultValue={editingFeature?.color || ''}
                    />
                  </div>
                  <div className="flex items-center space-x-2">
                    <Switch 
                      id="isActive" 
                      name="isActive"
                      defaultChecked={editingFeature?.isActive ?? true}
                    />
                    <Label htmlFor="isActive">Active</Label>
                  </div>
                </div>
                <DialogFooter>
                  <Button type="submit">
                    <Save className="h-4 w-4 mr-2" />
                    {editingFeature ? 'Update' : 'Create'}
                  </Button>
                </DialogFooter>
              </form>
            </DialogContent>
          </Dialog>

          {/* Stat Dialog */}
          <Dialog open={showStatDialog} onOpenChange={setShowStatDialog}>
            <DialogContent className="max-w-md">
              <DialogHeader>
                <DialogTitle>{editingStat ? 'Edit Statistic' : 'Add New Statistic'}</DialogTitle>
                <DialogDescription>
                  {editingStat ? 'Update this statistic' : 'Add a new social proof statistic'}
                </DialogDescription>
              </DialogHeader>
              <form onSubmit={(e) => {
                e.preventDefault();
                const formData = new FormData(e.target as HTMLFormElement);
                const data = {
                  label: formData.get('label'),
                  value: formData.get('value'),
                  description: formData.get('description'),
                  isActive: formData.get('isActive') === 'on'
                };
                
                if (editingStat) {
                  updateStatMutation.mutate({ id: editingStat.id, data });
                } else {
                  createStatMutation.mutate(data);
                }
              }}>
                <div className="space-y-4 py-4">
                  <div>
                    <Label htmlFor="label">Label</Label>
                    <Input 
                      id="label" 
                      name="label" 
                      defaultValue={editingStat?.label || ''}
                      required 
                    />
                  </div>
                  <div>
                    <Label htmlFor="value">Value</Label>
                    <Input 
                      id="value" 
                      name="value" 
                      defaultValue={editingStat?.value || ''}
                      required 
                    />
                  </div>
                  <div>
                    <Label htmlFor="description">Description</Label>
                    <Textarea 
                      id="description" 
                      name="description" 
                      defaultValue={editingStat?.description || ''}
                    />
                  </div>
                  <div className="flex items-center space-x-2">
                    <Switch 
                      id="isActive" 
                      name="isActive"
                      defaultChecked={editingStat?.isActive ?? true}
                    />
                    <Label htmlFor="isActive">Active</Label>
                  </div>
                </div>
                <DialogFooter>
                  <Button type="submit">
                    <Save className="h-4 w-4 mr-2" />
                    {editingStat ? 'Update' : 'Create'}
                  </Button>
                </DialogFooter>
              </form>
            </DialogContent>
          </Dialog>

          {/* Testimonial Dialog */}
          <Dialog open={showTestimonialDialog} onOpenChange={setShowTestimonialDialog}>
            <DialogContent className="max-w-md">
              <DialogHeader>
                <DialogTitle>{editingTestimonial ? 'Edit Testimonial' : 'Add New Testimonial'}</DialogTitle>
                <DialogDescription>
                  {editingTestimonial ? 'Update this testimonial' : 'Add a new customer testimonial'}
                </DialogDescription>
              </DialogHeader>
              <form onSubmit={(e) => {
                e.preventDefault();
                const formData = new FormData(e.target as HTMLFormElement);
                const data = {
                  name: formData.get('name'),
                  position: formData.get('position'),
                  company: formData.get('company'),
                  content: formData.get('content'),
                  rating: parseInt(formData.get('rating') as string),
                  imageUrl: formData.get('imageUrl'),
                  isActive: formData.get('isActive') === 'on'
                };
                
                if (editingTestimonial) {
                  updateTestimonialMutation.mutate({ id: editingTestimonial.id, data });
                } else {
                  createTestimonialMutation.mutate(data);
                }
              }}>
                <div className="space-y-4 py-4">
                  <div>
                    <Label htmlFor="name">Name</Label>
                    <Input 
                      id="name" 
                      name="name" 
                      defaultValue={editingTestimonial?.name || ''}
                      required 
                    />
                  </div>
                  <div>
                    <Label htmlFor="position">Position</Label>
                    <Input 
                      id="position" 
                      name="position" 
                      defaultValue={editingTestimonial?.position || ''}
                      required 
                    />
                  </div>
                  <div>
                    <Label htmlFor="company">Company</Label>
                    <Input 
                      id="company" 
                      name="company" 
                      defaultValue={editingTestimonial?.company || ''}
                      required 
                    />
                  </div>
                  <div>
                    <Label htmlFor="content">Content</Label>
                    <Textarea 
                      id="content" 
                      name="content" 
                      defaultValue={editingTestimonial?.content || ''}
                      required 
                    />
                  </div>
                  <div>
                    <Label htmlFor="rating">Rating</Label>
                    <Select name="rating" defaultValue={editingTestimonial?.rating?.toString() || '5'}>
                      <SelectTrigger>
                        <SelectValue placeholder="Select rating" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="1">1 Star</SelectItem>
                        <SelectItem value="2">2 Stars</SelectItem>
                        <SelectItem value="3">3 Stars</SelectItem>
                        <SelectItem value="4">4 Stars</SelectItem>
                        <SelectItem value="5">5 Stars</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div>
                    <Label htmlFor="imageUrl">Image URL (optional)</Label>
                    <Input 
                      id="imageUrl" 
                      name="imageUrl" 
                      defaultValue={editingTestimonial?.imageUrl || ''}
                    />
                  </div>
                  <div className="flex items-center space-x-2">
                    <Switch 
                      id="isActive" 
                      name="isActive"
                      defaultChecked={editingTestimonial?.isActive ?? true}
                    />
                    <Label htmlFor="isActive">Active</Label>
                  </div>
                </div>
                <DialogFooter>
                  <Button type="submit">
                    <Save className="h-4 w-4 mr-2" />
                    {editingTestimonial ? 'Update' : 'Create'}
                  </Button>
                </DialogFooter>
              </form>
            </DialogContent>
          </Dialog>
        </TabsContent>
      </Tabs>
    </div>
  );
}