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

interface MembershipFee {
  id: number;
  organizationId: number;
  userId?: string;
  feeType: string;
  amount: number;
  currency: string;
  dueDate: string;
  description?: string;
  status: string;
  paymentMethod?: string;
  recurringInterval?: string;
  nextDueDate?: string;
  gracePeriodDays: number;
  createdAt: string;
  updatedAt: string;
}

interface PaymentActivity {
  id: number;
  membershipFeeId: number;
  organizationId: number;
  userId?: string;
  amount: number;
  currency: string;
  paymentMethod: string;
  status: string;
  transactionId?: string;
  stripeCustomerId?: string;
  stripePaymentIntentId?: string;
  failureReason?: string;
  processedAt?: string;
  refundedAt?: string;
  refundAmount?: number;
  metadata?: any;
  createdAt: string;
  updatedAt: string;
}

interface PaymentNotification {
  id: number;
  membershipFeeId: number;
  userId: string;
  organizationId: number;
  notificationType: string;
  method: string;
  status: string;
  scheduledFor: string;
  sentAt?: string;
  subject?: string;
  message?: string;
  emailAddress?: string;
  phoneNumber?: string;
  failureReason?: string;
  metadata?: any;
  createdAt: string;
  updatedAt: string;
}

interface AutomaticPaymentSchedule {
  id: number;
  organizationId: number;
  userId: string;
  membershipFeeId: number;
  stripeCustomerId: string;
  stripeSubscriptionId?: string;
  stripePriceId?: string;
  isActive: boolean;
  nextPaymentDate: string;
  amount: number;
  currency: string;
  interval: string;
  failedAttempts: number;
  maxRetryAttempts: number;
  lastPaymentDate?: string;
  lastFailureDate?: string;
  lastFailureReason?: string;
  suspendedAt?: string;
  createdAt: string;
  updatedAt: string;
}

interface MemberStatusHistory {
  id: number;
  userId: string;
  organizationId: number;
  previousStatus: string;
  newStatus: string;
  reason: string;
  membershipFeeId?: number;
  changedBy?: string;
  automaticChange: boolean;
  notes?: string;
  effectiveDate: string;
  createdAt: string;
}

export default function Payments() {
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const [selectedTab, setSelectedTab] = useState("fees");
  const [showCreateFeeDialog, setShowCreateFeeDialog] = useState(false);
  const [showCreatePaymentDialog, setShowCreatePaymentDialog] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");

  // Fetch membership fees
  const { data: membershipFees, isLoading: isLoadingFees } = useQuery({
    queryKey: ["/api/membership-fees"],
  });

  // Fetch overdue fees
  const { data: overdueFees } = useQuery({
    queryKey: ["/api/membership-fees/overdue"],
  });

  // Fetch payment activities
  const { data: paymentActivities, isLoading: isLoadingActivities } = useQuery({
    queryKey: ["/api/payment-activities"],
  });

  // Fetch payment notifications
  const { data: pendingNotifications } = useQuery({
    queryKey: ["/api/payment-notifications/pending"],
  });

  // Fetch automatic payment schedules
  const { data: paymentSchedules } = useQuery({
    queryKey: ["/api/automatic-payment-schedules"],
  });

  // Fetch users for dropdowns
  const { data: users } = useQuery({
    queryKey: ["/api/admin/users"],
  });

  // Create membership fee mutation
  const createFeeMutation = useMutation({
    mutationFn: async (feeData: any) => {
      return await apiRequest("POST", "/api/membership-fees", feeData);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/membership-fees"] });
      setShowCreateFeeDialog(false);
      toast({
        title: "Success",
        description: "Membership fee created successfully",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description: error.message || "Failed to create membership fee",
        variant: "destructive",
      });
    },
  });

  // Create payment activity mutation
  const createPaymentMutation = useMutation({
    mutationFn: async (paymentData: any) => {
      return await apiRequest("POST", "/api/payment-activities", paymentData);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/payment-activities"] });
      queryClient.invalidateQueries({ queryKey: ["/api/membership-fees"] });
      setShowCreatePaymentDialog(false);
      toast({
        title: "Success",
        description: "Payment recorded successfully",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description: error.message || "Failed to record payment",
        variant: "destructive",
      });
    },
  });

  // Process overdue payments mutation
  const processOverdueMutation = useMutation({
    mutationFn: async () => {
      return await apiRequest("POST", "/api/process-overdue-payments", {});
    },
    onSuccess: (data: any) => {
      queryClient.invalidateQueries({ queryKey: ["/api/membership-fees"] });
      queryClient.invalidateQueries({ queryKey: ["/api/membership-fees/overdue"] });
      toast({
        title: "Success",
        description: data.message || "Processed overdue payments",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description: error.message || "Failed to process overdue payments",
        variant: "destructive",
      });
    },
  });

  // Helper functions
  const formatCurrency = (amount: number, currency: string = "USD") => {
    return new Intl.NumberFormat("en-US", {
      style: "currency",
      currency,
    }).format(amount / 100);
  };

  const getStatusBadgeVariant = (status: string) => {
    switch (status) {
      case "paid":
      case "completed":
        return "default";
      case "pending":
        return "secondary";
      case "overdue":
      case "failed":
        return "destructive";
      case "cancelled":
        return "outline";
      default:
        return "secondary";
    }
  };

  const filteredFees = (membershipFees as MembershipFee[] || []).filter((fee: MembershipFee) => {
    const matchesSearch = fee.description?.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         fee.feeType.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesStatus = statusFilter === "all" || fee.status === statusFilter;
    return matchesSearch && matchesStatus;
  });

  // Calculate statistics
  const totalPendingAmount = (membershipFees as MembershipFee[] || []).reduce((sum: number, fee: MembershipFee) => 
    fee.status === "pending" ? sum + fee.amount : sum, 0);
  
  const totalOverdueAmount = (overdueFees as MembershipFee[] || []).reduce((sum: number, fee: MembershipFee) => 
    sum + fee.amount, 0);

  const totalCollectedThisMonth = (paymentActivities as PaymentActivity[] || []).reduce((sum: number, activity: PaymentActivity) => {
    const activityDate = new Date(activity.createdAt);
    const currentMonth = new Date();
    if (activity.status === "completed" && 
        activityDate.getMonth() === currentMonth.getMonth() && 
        activityDate.getFullYear() === currentMonth.getFullYear()) {
      return sum + activity.amount;
    }
    return sum;
  }, 0);

  return (
    <div className="container mx-auto p-6 space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold">Payment Management</h1>
          <p className="text-muted-foreground">
            Manage membership fees, payments, and automatic billing
          </p>
        </div>
        <div className="flex gap-2">
          <Button
            onClick={() => processOverdueMutation.mutate()}
            disabled={processOverdueMutation.isPending}
            variant="outline"
          >
            <AlertTriangle className="h-4 w-4 mr-2" />
            Process Overdue
          </Button>
          <Dialog open={showCreateFeeDialog} onOpenChange={setShowCreateFeeDialog}>
            <DialogTrigger asChild>
              <Button>
                <Plus className="h-4 w-4 mr-2" />
                Create Fee
              </Button>
            </DialogTrigger>
            <DialogContent className="max-w-md">
              <DialogHeader>
                <DialogTitle>Create Membership Fee</DialogTitle>
                <DialogDescription>
                  Create a new membership fee for a user or organization
                </DialogDescription>
              </DialogHeader>
              <CreateFeeForm
                onSubmit={(data) => createFeeMutation.mutate(data)}
                isSubmitting={createFeeMutation.isPending}
                users={users as any[] || []}
              />
            </DialogContent>
          </Dialog>
        </div>
      </div>

      {/* Statistics Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Pending Payments</CardTitle>
            <DollarSign className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{formatCurrency(totalPendingAmount)}</div>
            <p className="text-xs text-muted-foreground">
              {(membershipFees as MembershipFee[] || []).filter((f: MembershipFee) => f.status === "pending").length} fees pending
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Overdue Payments</CardTitle>
            <AlertTriangle className="h-4 w-4 text-destructive" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-destructive">{formatCurrency(totalOverdueAmount)}</div>
            <p className="text-xs text-muted-foreground">
              {(overdueFees as MembershipFee[] || []).length} fees overdue
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Collected This Month</CardTitle>
            <TrendingUp className="h-4 w-4 text-green-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">{formatCurrency(totalCollectedThisMonth)}</div>
            <p className="text-xs text-muted-foreground">
              {(paymentActivities as PaymentActivity[] || []).filter((a: PaymentActivity) => {
                const activityDate = new Date(a.createdAt);
                const currentMonth = new Date();
                return a.status === "completed" && 
                       activityDate.getMonth() === currentMonth.getMonth() && 
                       activityDate.getFullYear() === currentMonth.getFullYear();
              }).length} payments this month
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Auto Payments</CardTitle>
            <Activity className="h-4 w-4 text-blue-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{(paymentSchedules as AutomaticPaymentSchedule[] || []).filter((s: AutomaticPaymentSchedule) => s.isActive).length}</div>
            <p className="text-xs text-muted-foreground">
              Active automatic payment schedules
            </p>
          </CardContent>
        </Card>
      </div>

      {/* Main Content Tabs */}
      <Tabs value={selectedTab} onValueChange={setSelectedTab} className="space-y-4">
        <TabsList className="grid w-full grid-cols-5">
          <TabsTrigger value="fees">Membership Fees</TabsTrigger>
          <TabsTrigger value="activities">Payment Activities</TabsTrigger>
          <TabsTrigger value="notifications">Notifications</TabsTrigger>
          <TabsTrigger value="schedules">Auto Payments</TabsTrigger>
          <TabsTrigger value="overdue">Overdue Management</TabsTrigger>
        </TabsList>

        <TabsContent value="fees" className="space-y-4">
          <Card>
            <CardHeader>
              <div className="flex justify-between items-center">
                <div>
                  <CardTitle>Membership Fees</CardTitle>
                  <CardDescription>Manage all membership fees and subscriptions</CardDescription>
                </div>
                <div className="flex gap-2">
                  <div className="relative">
                    <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
                    <Input
                      placeholder="Search fees..."
                      value={searchTerm}
                      onChange={(e) => setSearchTerm(e.target.value)}
                      className="pl-8 w-64"
                    />
                  </div>
                  <Select value={statusFilter} onValueChange={setStatusFilter}>
                    <SelectTrigger className="w-32">
                      <SelectValue placeholder="Status" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">All Status</SelectItem>
                      <SelectItem value="pending">Pending</SelectItem>
                      <SelectItem value="paid">Paid</SelectItem>
                      <SelectItem value="overdue">Overdue</SelectItem>
                      <SelectItem value="cancelled">Cancelled</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </CardHeader>
            <CardContent>
              {isLoadingFees ? (
                <div className="flex items-center justify-center py-8">
                  <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
                </div>
              ) : (
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Type</TableHead>
                      <TableHead>Amount</TableHead>
                      <TableHead>Due Date</TableHead>
                      <TableHead>Status</TableHead>
                      <TableHead>User</TableHead>
                      <TableHead>Actions</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {filteredFees.map((fee: MembershipFee) => (
                      <TableRow key={fee.id}>
                        <TableCell>
                          <div>
                            <div className="font-medium">{fee.feeType}</div>
                            {fee.description && (
                              <div className="text-sm text-muted-foreground">{fee.description}</div>
                            )}
                          </div>
                        </TableCell>
                        <TableCell className="font-mono">
                          {formatCurrency(fee.amount, fee.currency)}
                        </TableCell>
                        <TableCell>
                          {format(new Date(fee.dueDate), "MMM dd, yyyy")}
                        </TableCell>
                        <TableCell>
                          <Badge variant={getStatusBadgeVariant(fee.status)}>
                            {fee.status}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          {fee.userId ? (
                            <div className="text-sm">
                              {(users as any[] || []).find((u: any) => u.id === fee.userId)?.firstName || "Unknown"}
                            </div>
                          ) : (
                            <span className="text-muted-foreground">Organization</span>
                          )}
                        </TableCell>
                        <TableCell>
                          <div className="flex gap-2">
                            <Dialog>
                              <DialogTrigger asChild>
                                <Button variant="outline" size="sm">
                                  <CreditCard className="h-4 w-4 mr-1" />
                                  Pay
                                </Button>
                              </DialogTrigger>
                              <DialogContent className="max-w-md">
                                <DialogHeader>
                                  <DialogTitle>Record Payment</DialogTitle>
                                  <DialogDescription>
                                    Record a payment for this membership fee
                                  </DialogDescription>
                                </DialogHeader>
                                <CreatePaymentForm
                                  membershipFee={fee}
                                  onSubmit={(data) => createPaymentMutation.mutate(data)}
                                  isSubmitting={createPaymentMutation.isPending}
                                />
                              </DialogContent>
                            </Dialog>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="activities" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>Payment Activities</CardTitle>
              <CardDescription>View all payment transactions and activities</CardDescription>
            </CardHeader>
            <CardContent>
              {isLoadingActivities ? (
                <div className="flex items-center justify-center py-8">
                  <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
                </div>
              ) : (
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Date</TableHead>
                      <TableHead>Amount</TableHead>
                      <TableHead>Method</TableHead>
                      <TableHead>Status</TableHead>
                      <TableHead>Transaction ID</TableHead>
                      <TableHead>User</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {(paymentActivities as PaymentActivity[] || []).map((activity: PaymentActivity) => (
                      <TableRow key={activity.id}>
                        <TableCell>
                          {format(new Date(activity.createdAt), "MMM dd, yyyy HH:mm")}
                        </TableCell>
                        <TableCell className="font-mono">
                          {formatCurrency(activity.amount, activity.currency)}
                        </TableCell>
                        <TableCell>{activity.paymentMethod}</TableCell>
                        <TableCell>
                          <Badge variant={getStatusBadgeVariant(activity.status)}>
                            {activity.status}
                          </Badge>
                        </TableCell>
                        <TableCell className="font-mono text-sm">
                          {activity.transactionId || activity.stripePaymentIntentId || "—"}
                        </TableCell>
                        <TableCell>
                          {activity.userId ? (
                            (users as any[] || []).find((u: any) => u.id === activity.userId)?.firstName || "Unknown"
                          ) : (
                            "—"
                          )}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="notifications" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>Payment Notifications</CardTitle>
              <CardDescription>Manage payment reminders and notifications</CardDescription>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Type</TableHead>
                    <TableHead>User</TableHead>
                    <TableHead>Method</TableHead>
                    <TableHead>Scheduled</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead>Subject</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {(pendingNotifications as PaymentNotification[] || []).map((notification: PaymentNotification) => (
                    <TableRow key={notification.id}>
                      <TableCell>
                        <Badge variant="outline">{notification.notificationType}</Badge>
                      </TableCell>
                      <TableCell>
                        {(users as any[] || []).find((u: any) => u.id === notification.userId)?.firstName || "Unknown"}
                      </TableCell>
                      <TableCell>{notification.method}</TableCell>
                      <TableCell>
                        {format(new Date(notification.scheduledFor), "MMM dd, yyyy HH:mm")}
                      </TableCell>
                      <TableCell>
                        <Badge variant={getStatusBadgeVariant(notification.status)}>
                          {notification.status}
                        </Badge>
                      </TableCell>
                      <TableCell>{notification.subject}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="schedules" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>Automatic Payment Schedules</CardTitle>
              <CardDescription>Manage recurring payment schedules and automatic billing</CardDescription>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>User</TableHead>
                    <TableHead>Amount</TableHead>
                    <TableHead>Interval</TableHead>
                    <TableHead>Next Payment</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead>Failed Attempts</TableHead>
                    <TableHead>Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {(paymentSchedules as AutomaticPaymentSchedule[] || []).map((schedule: AutomaticPaymentSchedule) => (
                    <TableRow key={schedule.id}>
                      <TableCell>
                        {(users as any[] || []).find((u: any) => u.id === schedule.userId)?.firstName || "Unknown"}
                      </TableCell>
                      <TableCell className="font-mono">
                        {formatCurrency(schedule.amount, schedule.currency)}
                      </TableCell>
                      <TableCell>{schedule.interval}</TableCell>
                      <TableCell>
                        {format(new Date(schedule.nextPaymentDate), "MMM dd, yyyy")}
                      </TableCell>
                      <TableCell>
                        <Badge variant={schedule.isActive ? "default" : "secondary"}>
                          {schedule.isActive ? "Active" : "Suspended"}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <span className={schedule.failedAttempts > 0 ? "text-destructive" : ""}>
                          {schedule.failedAttempts} / {schedule.maxRetryAttempts}
                        </span>
                      </TableCell>
                      <TableCell>
                        <Button variant="outline" size="sm" disabled={!schedule.isActive}>
                          Suspend
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="overdue" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>Overdue Payment Management</CardTitle>
              <CardDescription>Manage overdue payments and member suspensions</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                <div className="flex justify-between items-center p-4 bg-destructive/10 rounded-lg border border-destructive/20">
                  <div>
                    <h3 className="font-medium text-destructive">Overdue Payments</h3>
                    <p className="text-sm text-muted-foreground">
                      {(overdueFees as MembershipFee[] || []).length} payments are overdue totaling {formatCurrency(totalOverdueAmount)}
                    </p>
                  </div>
                  <Button
                    onClick={() => processOverdueMutation.mutate()}
                    disabled={processOverdueMutation.isPending}
                    variant="destructive"
                  >
                    <AlertTriangle className="h-4 w-4 mr-2" />
                    Process All Overdue
                  </Button>
                </div>

                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>User</TableHead>
                      <TableHead>Fee Type</TableHead>
                      <TableHead>Amount</TableHead>
                      <TableHead>Due Date</TableHead>
                      <TableHead>Days Overdue</TableHead>
                      <TableHead>Grace Period</TableHead>
                      <TableHead>Actions</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {(overdueFees as MembershipFee[] || []).map((fee: MembershipFee) => {
                      const daysOverdue = Math.floor((new Date().getTime() - new Date(fee.dueDate).getTime()) / (1000 * 60 * 60 * 24));
                      const gracePeriodEnded = daysOverdue > (fee.gracePeriodDays || 7);
                      
                      return (
                        <TableRow key={fee.id}>
                          <TableCell>
                            {fee.userId ? (
                              (users as any[])?.find((u: any) => u.id === fee.userId)?.firstName || "Unknown"
                            ) : (
                              "Organization"
                            )}
                          </TableCell>
                          <TableCell>{fee.feeType}</TableCell>
                          <TableCell className="font-mono">
                            {formatCurrency(fee.amount, fee.currency)}
                          </TableCell>
                          <TableCell>
                            {format(new Date(fee.dueDate), "MMM dd, yyyy")}
                          </TableCell>
                          <TableCell>
                            <span className="text-destructive font-medium">
                              {daysOverdue} days
                            </span>
                          </TableCell>
                          <TableCell>
                            <Badge variant={gracePeriodEnded ? "destructive" : "secondary"}>
                              {gracePeriodEnded ? "Expired" : `${fee.gracePeriodDays || 7} days`}
                            </Badge>
                          </TableCell>
                          <TableCell>
                            <div className="flex gap-2">
                              <Button variant="outline" size="sm">
                                <Bell className="h-4 w-4 mr-1" />
                                Notify
                              </Button>
                              {gracePeriodEnded && (
                                <Button variant="destructive" size="sm">
                                  <UserX className="h-4 w-4 mr-1" />
                                  Suspend
                                </Button>
                              )}
                            </div>
                          </TableCell>
                        </TableRow>
                      );
                    })}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}

// Form component for creating membership fees
function CreateFeeForm({ onSubmit, isSubmitting, users }: { onSubmit: (data: any) => void; isSubmitting: boolean; users: any[] }) {
  const [formData, setFormData] = useState({
    userId: "",
    organizationId: 1,
    feeType: "membership",
    amount: "",
    currency: "USD",
    dueDate: "",
    description: "",
    recurringInterval: "",
    gracePeriodDays: 7,
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onSubmit({
      ...formData,
      amount: parseInt(formData.amount) * 100, // Convert to cents
      userId: formData.userId || undefined,
    });
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div>
        <Label htmlFor="user">User (optional)</Label>
        <Select value={formData.userId} onValueChange={(value) => setFormData({ ...formData, userId: value })}>
          <SelectTrigger>
            <SelectValue placeholder="Select user or leave blank for organization" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="organization">Organization Fee</SelectItem>
            {users.map((user) => (
              <SelectItem key={user.id} value={user.id}>
                {user.firstName} {user.lastName} ({user.email})
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      <div>
        <Label htmlFor="feeType">Fee Type</Label>
        <Select value={formData.feeType} onValueChange={(value) => setFormData({ ...formData, feeType: value })}>
          <SelectTrigger>
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="membership">Membership</SelectItem>
            <SelectItem value="subscription">Subscription</SelectItem>
            <SelectItem value="registration">Registration</SelectItem>
            <SelectItem value="tournament">Tournament</SelectItem>
          </SelectContent>
        </Select>
      </div>

      <div>
        <Label htmlFor="amount">Amount (USD)</Label>
        <Input
          id="amount"
          type="number"
          step="0.01"
          placeholder="0.00"
          value={formData.amount}
          onChange={(e) => setFormData({ ...formData, amount: e.target.value })}
          required
        />
      </div>

      <div>
        <Label htmlFor="dueDate">Due Date</Label>
        <Input
          id="dueDate"
          type="date"
          value={formData.dueDate}
          onChange={(e) => setFormData({ ...formData, dueDate: e.target.value })}
          required
        />
      </div>

      <div>
        <Label htmlFor="description">Description</Label>
        <Textarea
          id="description"
          placeholder="Optional description"
          value={formData.description}
          onChange={(e) => setFormData({ ...formData, description: e.target.value })}
        />
      </div>

      <div>
        <Label htmlFor="recurringInterval">Recurring Interval (optional)</Label>
        <Select value={formData.recurringInterval} onValueChange={(value) => setFormData({ ...formData, recurringInterval: value })}>
          <SelectTrigger>
            <SelectValue placeholder="One-time payment" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="one-time">One-time payment</SelectItem>
            <SelectItem value="month">Monthly</SelectItem>
            <SelectItem value="quarter">Quarterly</SelectItem>
            <SelectItem value="year">Yearly</SelectItem>
          </SelectContent>
        </Select>
      </div>

      <div>
        <Label htmlFor="gracePeriodDays">Grace Period (days)</Label>
        <Input
          id="gracePeriodDays"
          type="number"
          value={formData.gracePeriodDays}
          onChange={(e) => setFormData({ ...formData, gracePeriodDays: parseInt(e.target.value) })}
          required
        />
      </div>

      <div className="flex justify-end gap-2">
        <Button type="submit" disabled={isSubmitting}>
          {isSubmitting ? "Creating..." : "Create Fee"}
        </Button>
      </div>
    </form>
  );
}

// Form component for recording payments
function CreatePaymentForm({ membershipFee, onSubmit, isSubmitting }: { membershipFee: MembershipFee; onSubmit: (data: any) => void; isSubmitting: boolean }) {
  const [formData, setFormData] = useState({
    amount: (membershipFee.amount / 100).toString(),
    paymentMethod: "cash",
    transactionId: "",
    notes: "",
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onSubmit({
      membershipFeeId: membershipFee.id,
      organizationId: membershipFee.organizationId,
      userId: membershipFee.userId,
      amount: parseInt(formData.amount) * 100, // Convert to cents
      currency: membershipFee.currency,
      paymentMethod: formData.paymentMethod,
      status: "completed",
      transactionId: formData.transactionId || undefined,
      processedAt: new Date().toISOString(),
      metadata: formData.notes ? { notes: formData.notes } : undefined,
    });
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div>
        <Label>Fee Details</Label>
        <div className="p-3 bg-muted rounded-lg">
          <div className="text-sm">
            <div><strong>Type:</strong> {membershipFee.feeType}</div>
            <div><strong>Amount:</strong> {new Intl.NumberFormat("en-US", { style: "currency", currency: membershipFee.currency }).format(membershipFee.amount / 100)}</div>
            <div><strong>Due:</strong> {format(new Date(membershipFee.dueDate), "MMM dd, yyyy")}</div>
          </div>
        </div>
      </div>

      <div>
        <Label htmlFor="amount">Payment Amount</Label>
        <Input
          id="amount"
          type="number"
          step="0.01"
          value={formData.amount}
          onChange={(e) => setFormData({ ...formData, amount: e.target.value })}
          required
        />
      </div>

      <div>
        <Label htmlFor="paymentMethod">Payment Method</Label>
        <Select value={formData.paymentMethod} onValueChange={(value) => setFormData({ ...formData, paymentMethod: value })}>
          <SelectTrigger>
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="cash">Cash</SelectItem>
            <SelectItem value="card">Credit/Debit Card</SelectItem>
            <SelectItem value="bank_transfer">Bank Transfer</SelectItem>
            <SelectItem value="check">Check</SelectItem>
            <SelectItem value="stripe">Stripe</SelectItem>
          </SelectContent>
        </Select>
      </div>

      <div>
        <Label htmlFor="transactionId">Transaction ID (optional)</Label>
        <Input
          id="transactionId"
          placeholder="Transaction reference number"
          value={formData.transactionId}
          onChange={(e) => setFormData({ ...formData, transactionId: e.target.value })}
        />
      </div>

      <div>
        <Label htmlFor="notes">Notes (optional)</Label>
        <Textarea
          id="notes"
          placeholder="Additional notes about this payment"
          value={formData.notes}
          onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
        />
      </div>

      <div className="flex justify-end gap-2">
        <Button type="submit" disabled={isSubmitting}>
          {isSubmitting ? "Recording..." : "Record Payment"}
        </Button>
      </div>
    </form>
  );
}