import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@/lib/queryClient";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useToast } from "@/hooks/use-toast";
import { format } from "date-fns";
import { Calendar, CreditCard, Users, TrendingUp, AlertTriangle, CheckCircle, XCircle, Clock } from "lucide-react";

interface MembershipPlan {
  id: number;
  name: string;
  tier: string;
  price: number;
  currency: string;
  interval: string;
  features: any;
  isActive: boolean;
  maxUsers?: number;
  createdAt: Date;
}

interface Subscription {
  id: number;
  userId: string;
  planId: number;
  status: string;
  startDate: Date;
  endDate?: Date;
  nextBillingDate?: Date;
  autoRenew: boolean;
  trialEndDate?: Date;
  cancelledAt?: Date;
  cancelReason?: string;
  plan: MembershipPlan;
  user: any;
}

interface Payment {
  id: number;
  userId: string;
  subscriptionId: number;
  amount: number;
  currency: string;
  status: string;
  paidAt?: Date;
  createdAt?: Date;
  failureReason?: string;
  stripePaymentId?: string;
  subscription: Subscription;
  user: any;
}

const getStatusColor = (status: string | undefined | null) => {
  if (!status) return 'bg-gray-500';
  switch (status.toLowerCase()) {
    case 'active': return 'bg-green-500';
    case 'trial': return 'bg-blue-500';
    case 'cancelled': return 'bg-red-500';
    case 'suspended': return 'bg-orange-500';
    case 'expired': return 'bg-gray-500';
    case 'completed': return 'bg-green-500';
    case 'pending': return 'bg-yellow-500';
    case 'failed': return 'bg-red-500';
    default: return 'bg-gray-500';
  }
};

const getStatusIcon = (status: string | undefined | null) => {
  if (!status) return <AlertTriangle className="h-4 w-4" />;
  switch (status.toLowerCase()) {
    case 'active':
    case 'completed':
      return <CheckCircle className="h-4 w-4" />;
    case 'cancelled':
    case 'failed':
      return <XCircle className="h-4 w-4" />;
    case 'pending':
    case 'trial':
      return <Clock className="h-4 w-4" />;
    default:
      return <AlertTriangle className="h-4 w-4" />;
  }
};

export default function Subscriptions() {
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const [selectedTab, setSelectedTab] = useState("overview");
  const [newPlanDialog, setNewPlanDialog] = useState(false);
  const [editPlanDialog, setEditPlanDialog] = useState(false);
  const [deletePlanDialog, setDeletePlanDialog] = useState(false);
  const [editingPlan, setEditingPlan] = useState<MembershipPlan | null>(null);
  const [deletingPlan, setDeletingPlan] = useState<MembershipPlan | null>(null);
  const [planFeatures, setPlanFeatures] = useState<string[]>([]);
  const [currentFeature, setCurrentFeature] = useState("");
  const [selectedSubscription, setSelectedSubscription] = useState<Subscription | null>(null);

  // Queries
  const { data: subscriptionStats }: { data: any } = useQuery({
    queryKey: ["/api/subscription-stats"],
  });

  const { data: subscriptions = [] }: { data: Subscription[] } = useQuery({
    queryKey: ["/api/subscriptions"],
  });

  const { data: membershipPlans = [] }: { data: MembershipPlan[] } = useQuery({
    queryKey: ["/api/membership-plans"],
  });

  const { data: payments = [] }: { data: Payment[] } = useQuery({
    queryKey: ["/api/payments"],
  });

  const { data: overdueSubscriptions = [] }: { data: Subscription[] } = useQuery({
    queryKey: ["/api/subscriptions/overdue"],
  });

  const { data: expiringSubscriptions = [] }: { data: Subscription[] } = useQuery({
    queryKey: ["/api/subscriptions/expiring/7"],
  });

  // Mutations
  const createPlanMutation = useMutation({
    mutationFn: (planData: any) => apiRequest("POST", "/api/membership-plans", planData),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/membership-plans"] });
      setNewPlanDialog(false);
      setPlanFeatures([]);
      setCurrentFeature("");
      toast({ title: "Success", description: "Membership plan created successfully" });
    },
    onError: () => {
      toast({ title: "Error", description: "Failed to create membership plan", variant: "destructive" });
    },
  });

  const updatePlanMutation = useMutation({
    mutationFn: ({ id, planData }: { id: number; planData: any }) => 
      apiRequest("PUT", `/api/membership-plans/${id}`, planData),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/membership-plans"] });
      setEditPlanDialog(false);
      setEditingPlan(null);
      setPlanFeatures([]);
      setCurrentFeature("");
      toast({ title: "Success", description: "Membership plan updated successfully" });
    },
    onError: () => {
      toast({ title: "Error", description: "Failed to update membership plan", variant: "destructive" });
    },
  });

  const deletePlanMutation = useMutation({
    mutationFn: (id: number) => apiRequest("DELETE", `/api/membership-plans/${id}`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/membership-plans"] });
      queryClient.invalidateQueries({ queryKey: ["/api/subscription-stats"] });
      setDeletePlanDialog(false);
      setDeletingPlan(null);
      toast({ title: "Success", description: "Membership plan deleted successfully" });
    },
    onError: () => {
      toast({ title: "Error", description: "Failed to delete membership plan", variant: "destructive" });
    },
  });

  const cancelSubscriptionMutation = useMutation({
    mutationFn: ({ id, reason }: { id: number; reason?: string }) => 
      apiRequest("POST", `/api/subscriptions/${id}/cancel`, { reason }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/subscriptions"] });
      queryClient.invalidateQueries({ queryKey: ["/api/subscription-stats"] });
      toast({ title: "Success", description: "Subscription cancelled successfully" });
    },
    onError: () => {
      toast({ title: "Error", description: "Failed to cancel subscription", variant: "destructive" });
    },
  });

  const suspendSubscriptionMutation = useMutation({
    mutationFn: ({ id, reason }: { id: number; reason: string }) => 
      apiRequest("POST", `/api/subscriptions/${id}/suspend`, { reason }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/subscriptions"] });
      queryClient.invalidateQueries({ queryKey: ["/api/subscription-stats"] });
      toast({ title: "Success", description: "Subscription suspended successfully" });
    },
    onError: () => {
      toast({ title: "Error", description: "Failed to suspend subscription", variant: "destructive" });
    },
  });

  const reactivateSubscriptionMutation = useMutation({
    mutationFn: (id: number) => apiRequest("POST", `/api/subscriptions/${id}/reactivate`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/subscriptions"] });
      queryClient.invalidateQueries({ queryKey: ["/api/subscription-stats"] });
      toast({ title: "Success", description: "Subscription reactivated successfully" });
    },
    onError: () => {
      toast({ title: "Error", description: "Failed to reactivate subscription", variant: "destructive" });
    },
  });

  // Feature management functions
  const addFeature = () => {
    if (currentFeature.trim() && !planFeatures.includes(currentFeature.trim())) {
      setPlanFeatures([...planFeatures, currentFeature.trim()]);
      setCurrentFeature("");
    }
  };

  const removeFeature = (featureToRemove: string) => {
    setPlanFeatures(planFeatures.filter(feature => feature !== featureToRemove));
  };

  const openEditPlan = (plan: MembershipPlan) => {
    setEditingPlan(plan);
    // Parse existing features
    const existingFeatures = plan.features?.items || 
      (plan.features?.description ? [plan.features.description] : []);
    setPlanFeatures(existingFeatures);
    setEditPlanDialog(true);
  };

  const openDeletePlan = (plan: MembershipPlan) => {
    setDeletingPlan(plan);
    setDeletePlanDialog(true);
  };

  const handleDeletePlan = () => {
    if (deletingPlan) {
      deletePlanMutation.mutate(deletingPlan.id);
    }
  };

  const handleCreatePlan = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const formData = new FormData(e.currentTarget);
    
    const billingInterval = formData.get("billingInterval") as string;
    const tier = billingInterval === "yearly" ? "premium" : "regular";
    
    const planData = {
      name: formData.get("name") as string,
      tier: tier,
      price: parseFloat(formData.get("price") as string) * 100, // Convert to cents
      currency: "USD",
      interval: billingInterval === "quarterly" ? "month" : billingInterval, // Map quarterly to month for now
      features: {
        description: planFeatures.length > 0 ? planFeatures.join(", ") : "Basic features",
        items: planFeatures,
      },
      isActive: true,
      maxUsers: formData.get("maxMembers") ? parseInt(formData.get("maxMembers") as string) : null,
    };

    createPlanMutation.mutate(planData);
  };

  const handleUpdatePlan = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    if (!editingPlan) return;
    
    const formData = new FormData(e.currentTarget);
    const billingInterval = formData.get("billingInterval") as string;
    const tier = billingInterval === "yearly" ? "premium" : "regular";
    
    const planData = {
      name: formData.get("name") as string,
      tier: tier,
      price: parseFloat(formData.get("price") as string) * 100, // Convert to cents
      currency: "USD",
      interval: billingInterval === "quarterly" ? "month" : billingInterval,
      features: {
        description: planFeatures.length > 0 ? planFeatures.join(", ") : "Basic features",
        items: planFeatures,
      },
      isActive: formData.get("isActive") === "on",
      maxUsers: formData.get("maxMembers") ? parseInt(formData.get("maxMembers") as string) : null,
    };

    updatePlanMutation.mutate({ id: editingPlan.id, planData });
  };

  return (
    <div className="container mx-auto py-8 space-y-8">
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold">Subscription Management</h1>
          <p className="text-muted-foreground">Manage membership plans, subscriptions, and payments</p>
        </div>
        <Dialog open={newPlanDialog} onOpenChange={setNewPlanDialog}>
          <DialogTrigger asChild>
            <Button>
              <CreditCard className="h-4 w-4 mr-2" />
              New Plan
            </Button>
          </DialogTrigger>
          <DialogContent className="sm:max-w-[425px]">
            <DialogHeader>
              <DialogTitle>Create Membership Plan</DialogTitle>
              <DialogDescription>
                Create a new membership plan for your sports club.
              </DialogDescription>
            </DialogHeader>
            <form onSubmit={handleCreatePlan} className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="name">Plan Name</Label>
                <Input id="name" name="name" placeholder="e.g., Premium Membership" required />
              </div>
              <div className="space-y-2">
                <Label htmlFor="description">Description</Label>
                <Input id="description" name="description" placeholder="Plan description" required />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="price">Price ($)</Label>
                  <Input id="price" name="price" type="number" placeholder="29.99" step="0.01" required />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="billingInterval">Billing</Label>
                  <Select name="billingInterval" required>
                    <SelectTrigger>
                      <SelectValue placeholder="Select interval" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="monthly">Monthly</SelectItem>
                      <SelectItem value="quarterly">Quarterly</SelectItem>
                      <SelectItem value="yearly">Yearly</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
              <div className="space-y-2">
                <Label>Features</Label>
                <div className="flex space-x-2">
                  <Input 
                    value={currentFeature}
                    onChange={(e) => setCurrentFeature(e.target.value)}
                    placeholder="Add a feature" 
                    onKeyPress={(e) => e.key === 'Enter' && (e.preventDefault(), addFeature())}
                  />
                  <Button type="button" onClick={addFeature} size="sm">Add</Button>
                </div>
                {planFeatures.length > 0 && (
                  <div className="space-y-2">
                    <p className="text-sm text-muted-foreground">Plan Features:</p>
                    <div className="space-y-1">
                      {planFeatures.map((feature, index) => (
                        <div key={index} className="flex items-center justify-between p-2 bg-muted rounded">
                          <span className="text-sm">• {feature}</span>
                          <Button 
                            type="button" 
                            variant="ghost" 
                            size="sm" 
                            onClick={() => removeFeature(feature)}
                            className="h-6 w-6 p-0"
                          >
                            ×
                          </Button>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </div>
              <div className="space-y-2">
                <Label htmlFor="maxMembers">Max Members (optional)</Label>
                <Input id="maxMembers" name="maxMembers" type="number" placeholder="Unlimited if empty" />
              </div>
              <div className="flex justify-end space-x-2">
                <Button type="button" variant="outline" onClick={() => setNewPlanDialog(false)}>
                  Cancel
                </Button>
                <Button type="submit" disabled={createPlanMutation.isPending}>
                  {createPlanMutation.isPending ? "Creating..." : "Create Plan"}
                </Button>
              </div>
            </form>
          </DialogContent>
        </Dialog>

        {/* Edit Plan Dialog */}
        <Dialog open={editPlanDialog} onOpenChange={setEditPlanDialog}>
          <DialogContent className="sm:max-w-[500px] max-h-[80vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>Edit Membership Plan</DialogTitle>
              <DialogDescription>
                Update the membership plan details and features.
              </DialogDescription>
            </DialogHeader>
            {editingPlan && (
              <form onSubmit={handleUpdatePlan} className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="edit-name">Plan Name</Label>
                  <Input 
                    id="edit-name" 
                    name="name" 
                    defaultValue={editingPlan.name} 
                    required 
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="edit-description">Description</Label>
                  <Input 
                    id="edit-description" 
                    name="description" 
                    defaultValue={editingPlan.description} 
                    required 
                  />
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="edit-price">Price ($)</Label>
                    <Input 
                      id="edit-price" 
                      name="price" 
                      type="number" 
                      step="0.01" 
                      defaultValue={(editingPlan.price / 100).toFixed(2)} 
                      required 
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="edit-billing">Billing</Label>
                    <Select name="billingInterval" defaultValue={editingPlan.interval}>
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="monthly">Monthly</SelectItem>
                        <SelectItem value="quarterly">Quarterly</SelectItem>
                        <SelectItem value="yearly">Yearly</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
                <div className="space-y-2">
                  <Label>Features</Label>
                  <div className="flex space-x-2">
                    <Input 
                      value={currentFeature}
                      onChange={(e) => setCurrentFeature(e.target.value)}
                      placeholder="Add a feature" 
                      onKeyPress={(e) => e.key === 'Enter' && (e.preventDefault(), addFeature())}
                    />
                    <Button type="button" onClick={addFeature} size="sm">Add</Button>
                  </div>
                  {planFeatures.length > 0 && (
                    <div className="space-y-2">
                      <p className="text-sm text-muted-foreground">Plan Features:</p>
                      <div className="space-y-1">
                        {planFeatures.map((feature, index) => (
                          <div key={index} className="flex items-center justify-between p-2 bg-muted rounded">
                            <span className="text-sm">• {feature}</span>
                            <Button 
                              type="button" 
                              variant="ghost" 
                              size="sm" 
                              onClick={() => removeFeature(feature)}
                              className="h-6 w-6 p-0"
                            >
                              ×
                            </Button>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}
                </div>
                <div className="space-y-2">
                  <Label htmlFor="edit-maxMembers">Max Members (optional)</Label>
                  <Input 
                    id="edit-maxMembers" 
                    name="maxMembers" 
                    type="number" 
                    defaultValue={editingPlan.maxUsers || ""} 
                    placeholder="Unlimited if empty" 
                  />
                </div>
                <div className="flex items-center space-x-2">
                  <input
                    type="checkbox"
                    id="edit-isActive"
                    name="isActive"
                    defaultChecked={editingPlan.isActive}
                    className="rounded"
                  />
                  <Label htmlFor="edit-isActive">Plan is active</Label>
                </div>
                <div className="flex justify-end space-x-2">
                  <Button 
                    type="button" 
                    variant="outline" 
                    onClick={() => {
                      setEditPlanDialog(false);
                      setEditingPlan(null);
                      setPlanFeatures([]);
                      setCurrentFeature("");
                    }}
                  >
                    Cancel
                  </Button>
                  <Button type="submit" disabled={updatePlanMutation.isPending}>
                    {updatePlanMutation.isPending ? "Updating..." : "Update Plan"}
                  </Button>
                </div>
              </form>
            )}
          </DialogContent>
        </Dialog>

        {/* Delete Plan Confirmation Dialog */}
        <Dialog open={deletePlanDialog} onOpenChange={setDeletePlanDialog}>
          <DialogContent className="sm:max-w-[400px]">
            <DialogHeader>
              <DialogTitle>Delete Membership Plan</DialogTitle>
              <DialogDescription>
                Are you sure you want to delete this membership plan? This action cannot be undone.
              </DialogDescription>
            </DialogHeader>
            {deletingPlan && (
              <div className="space-y-4">
                <div className="p-4 border rounded-lg bg-red-50 border-red-200">
                  <h4 className="font-medium text-red-800">{deletingPlan.name}</h4>
                  <p className="text-sm text-red-600">${(deletingPlan.price / 100).toFixed(2)} per {deletingPlan.interval}</p>
                  <p className="text-sm text-red-600 mt-1">{deletingPlan.description}</p>
                </div>
                <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-3">
                  <p className="text-sm text-yellow-800">
                    <strong>Warning:</strong> Deleting this plan will affect existing subscriptions using this plan. 
                    Make sure no active subscriptions are using this plan before deletion.
                  </p>
                </div>
                <div className="flex justify-end space-x-2">
                  <Button 
                    variant="outline" 
                    onClick={() => {
                      setDeletePlanDialog(false);
                      setDeletingPlan(null);
                    }}
                  >
                    Cancel
                  </Button>
                  <Button 
                    variant="destructive" 
                    onClick={handleDeletePlan}
                    disabled={deletePlanMutation.isPending}
                  >
                    {deletePlanMutation.isPending ? "Deleting..." : "Delete Plan"}
                  </Button>
                </div>
              </div>
            )}
          </DialogContent>
        </Dialog>
      </div>

      {/* Statistics Cards */}
      {subscriptionStats && (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Total Subscriptions</CardTitle>
              <Users className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{subscriptionStats.totalSubscriptions || 0}</div>
              <p className="text-xs text-muted-foreground">
                {subscriptionStats.activeSubscriptions || 0} active
              </p>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Monthly Revenue</CardTitle>
              <TrendingUp className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">${(subscriptionStats.monthlyRevenue || 0).toFixed(2)}</div>
              <p className="text-xs text-muted-foreground">
                ${(subscriptionStats.totalRevenue || 0).toFixed(2)} total
              </p>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Churn Rate</CardTitle>
              <AlertTriangle className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{(subscriptionStats.churnRate || 0).toFixed(1)}%</div>
              <p className="text-xs text-muted-foreground">
                {subscriptionStats.cancelledSubscriptions || 0} cancelled
              </p>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Avg. Value</CardTitle>
              <CreditCard className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">${(subscriptionStats.avgSubscriptionValue || 0).toFixed(2)}</div>
              <p className="text-xs text-muted-foreground">
                {subscriptionStats.trialSubscriptions || 0} on trial
              </p>
            </CardContent>
          </Card>
        </div>
      )}

      {/* Alerts for overdue and expiring subscriptions */}
      {(overdueSubscriptions.length > 0 || expiringSubscriptions.length > 0) && (
        <div className="space-y-4">
          {overdueSubscriptions.length > 0 && (
            <Alert className="border-red-200 bg-red-50">
              <AlertTriangle className="h-4 w-4" />
              <AlertDescription>
                <strong>{overdueSubscriptions.length} overdue subscriptions</strong> require attention.
              </AlertDescription>
            </Alert>
          )}
          {expiringSubscriptions.length > 0 && (
            <Alert className="border-yellow-200 bg-yellow-50">
              <Calendar className="h-4 w-4" />
              <AlertDescription>
                <strong>{expiringSubscriptions.length} subscriptions</strong> expire within 7 days.
              </AlertDescription>
            </Alert>
          )}
        </div>
      )}

      <Tabs value={selectedTab} onValueChange={setSelectedTab} className="space-y-4">
        <TabsList>
          <TabsTrigger value="overview">Overview</TabsTrigger>
          <TabsTrigger value="subscriptions">Subscriptions</TabsTrigger>
          <TabsTrigger value="plans">Membership Plans</TabsTrigger>
          <TabsTrigger value="payments">Payments</TabsTrigger>
        </TabsList>

        <TabsContent value="overview" className="space-y-4">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <Card>
              <CardHeader>
                <CardTitle>Recent Subscriptions</CardTitle>
                <CardDescription>Latest subscription activities</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {subscriptions.slice(0, 5).map((subscription: Subscription) => (
                    <div key={subscription.id} className="flex items-center justify-between p-3 border rounded-lg">
                      <div className="flex items-center space-x-3">
                        {getStatusIcon(subscription.status)}
                        <div>
                          <p className="font-medium">{subscription.user?.firstName} {subscription.user?.lastName}</p>
                          <p className="text-sm text-muted-foreground">{subscription.plan?.name}</p>
                        </div>
                      </div>
                      <Badge className={getStatusColor(subscription.status)}>
                        {subscription.status}
                      </Badge>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>Recent Payments</CardTitle>
                <CardDescription>Latest payment transactions</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {payments.slice(0, 5).map((payment: Payment) => (
                    <div key={payment.id} className="flex items-center justify-between p-3 border rounded-lg">
                      <div className="flex items-center space-x-3">
                        {getStatusIcon(payment.status)}
                        <div>
                          <p className="font-medium">${(payment.amount / 100).toFixed(2)}</p>
                          <p className="text-sm text-muted-foreground">
                            {payment.user?.firstName} {payment.user?.lastName}
                          </p>
                        </div>
                      </div>
                      <Badge className={getStatusColor(payment.status)}>
                        {payment.status}
                      </Badge>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        <TabsContent value="subscriptions" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>All Subscriptions</CardTitle>
              <CardDescription>Manage member subscriptions and billing</CardDescription>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Member</TableHead>
                    <TableHead>Plan</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead>Next Billing</TableHead>
                    <TableHead>Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {subscriptions.map((subscription: Subscription) => (
                    <TableRow key={subscription.id}>
                      <TableCell>
                        <div>
                          <p className="font-medium">{subscription.user?.firstName} {subscription.user?.lastName}</p>
                          <p className="text-sm text-muted-foreground">{subscription.user?.email}</p>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div>
                          <p className="font-medium">{subscription.plan?.name}</p>
                          <p className="text-sm text-muted-foreground">
                            ${(subscription.plan?.price / 100).toFixed(2)}/{subscription.plan?.billingInterval}
                          </p>
                        </div>
                      </TableCell>
                      <TableCell>
                        <Badge className={getStatusColor(subscription.status)}>
                          {subscription.status}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        {subscription.nextBillingDate ? (
                          format(new Date(subscription.nextBillingDate), "MMM dd, yyyy")
                        ) : (
                          "-"
                        )}
                      </TableCell>
                      <TableCell>
                        <div className="flex space-x-2">
                          {subscription.status === "active" && (
                            <>
                              <Button
                                size="sm"
                                variant="outline"
                                onClick={() => suspendSubscriptionMutation.mutate({ 
                                  id: subscription.id, 
                                  reason: "Administrative suspension" 
                                })}
                                disabled={suspendSubscriptionMutation.isPending}
                              >
                                Suspend
                              </Button>
                              <Button
                                size="sm"
                                variant="destructive"
                                onClick={() => cancelSubscriptionMutation.mutate({ 
                                  id: subscription.id, 
                                  reason: "Administrative cancellation" 
                                })}
                                disabled={cancelSubscriptionMutation.isPending}
                              >
                                Cancel
                              </Button>
                            </>
                          )}
                          {subscription.status === "suspended" && (
                            <Button
                              size="sm"
                              onClick={() => reactivateSubscriptionMutation.mutate(subscription.id)}
                              disabled={reactivateSubscriptionMutation.isPending}
                            >
                              Reactivate
                            </Button>
                          )}
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="plans" className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {membershipPlans.map((plan: MembershipPlan) => (
              <Card key={plan.id} className={!plan.isActive ? "opacity-60" : ""}>
                <CardHeader>
                  <div className="flex justify-between items-start">
                    <div>
                      <CardTitle className="flex items-center gap-2">
                        {plan.name}
                        <div className="flex gap-1">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => openEditPlan(plan)}
                            className="h-6 w-6 p-0"
                            title="Edit plan"
                          >
                            ✏️
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => openDeletePlan(plan)}
                            className="h-6 w-6 p-0 text-red-500 hover:text-red-700"
                            title="Delete plan"
                          >
                            🗑️
                          </Button>
                        </div>
                      </CardTitle>
                      <CardDescription>{plan.description}</CardDescription>
                    </div>
                    <Badge variant={plan.isActive ? "default" : "secondary"}>
                      {plan.isActive ? "Active" : "Inactive"}
                    </Badge>
                  </div>
                </CardHeader>
                <CardContent>
                  <div className="space-y-4">
                    <div>
                      <p className="text-3xl font-bold">${(plan.price / 100).toFixed(2)}</p>
                      <p className="text-sm text-muted-foreground">per {plan.interval}</p>
                    </div>
                    {plan.maxUsers && (
                      <p className="text-sm text-muted-foreground">
                        Max {plan.maxUsers} users
                      </p>
                    )}
                    {plan.features && (
                      <div className="text-sm space-y-2">
                        <p className="font-medium">Features:</p>
                        {plan.features.items && plan.features.items.length > 0 ? (
                          <ul className="space-y-1">
                            {plan.features.items.map((feature: string, index: number) => (
                              <li key={index} className="text-muted-foreground flex items-center">
                                <span className="text-green-500 mr-2">✓</span>
                                {feature}
                              </li>
                            ))}
                          </ul>
                        ) : (
                          <p className="text-muted-foreground">{plan.features.description}</p>
                        )}
                      </div>
                    )}
                    <div className="pt-2 border-t space-y-2">
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => openEditPlan(plan)}
                        className="w-full"
                      >
                        Edit Plan
                      </Button>
                      <Button
                        variant="destructive"
                        size="sm"
                        onClick={() => openDeletePlan(plan)}
                        className="w-full"
                      >
                        Delete Plan
                      </Button>
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </TabsContent>

        <TabsContent value="payments" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>Payment History</CardTitle>
              <CardDescription>All payment transactions and billing history</CardDescription>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Date</TableHead>
                    <TableHead>Member</TableHead>
                    <TableHead>Amount</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead>Method</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {payments.map((payment: Payment) => (
                    <TableRow key={payment.id}>
                      <TableCell>
                        {payment.paidAt ? (
                          format(new Date(payment.paidAt), "MMM dd, yyyy")
                        ) : (
                          format(new Date(payment.createdAt), "MMM dd, yyyy")
                        )}
                      </TableCell>
                      <TableCell>
                        <div>
                          <p className="font-medium">{payment.user?.firstName} {payment.user?.lastName}</p>
                          <p className="text-sm text-muted-foreground">{payment.user?.email}</p>
                        </div>
                      </TableCell>
                      <TableCell>
                        <p className="font-medium">${(payment.amount / 100).toFixed(2)}</p>
                        <p className="text-sm text-muted-foreground">{payment.currency}</p>
                      </TableCell>
                      <TableCell>
                        <Badge className={getStatusColor(payment.status)}>
                          {payment.status}
                        </Badge>
                        {payment.failureReason && (
                          <p className="text-xs text-red-600 mt-1">{payment.failureReason}</p>
                        )}
                      </TableCell>
                      <TableCell>
                        {payment.stripePaymentId ? "Stripe" : "Manual"}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}