import { useState, useEffect } from "react";
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogHeader,
    DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { 
    Play, 
    Pause, 
    XCircle, 
    RefreshCw, 
    Calendar, 
    CreditCard,
    Package,
    User,
    DollarSign,
    FileText,
    History
} from "lucide-react";
import { toast } from "sonner";

interface Subscription {
    id: number;
    order_id: number;
    product_id: number;
    variation_id: number;
    customer_id: number;
    user_id: number;
    quantity: number;
    total: number;
    status: string;
    billing_period: string;
    billing_interval: number;
    trial_period?: string;
    trial_end?: string;
    start_date: string;
    next_payment_date: string | null;
    end_date?: string | null;
    last_payment_date?: string | null;
    cancelled_date?: string | null;
    suspension_count: number;
    payment_method: string;
    payment_method_title: string;
    requires_manual_renewal: boolean;
    created_at: string;
    updated_at: string;
    // Enriched data
    product_name?: string;
    customer_name?: string;
    customer_email?: string;
    currency?: string;
}

interface SubscriptionDetailDialogProps {
    subscription: Subscription | null;
    open: boolean;
    onOpenChange: (open: boolean) => void;
    onUpdate: () => void;
}

const statusColors: Record<string, string> = {
    active: "bg-green-100 text-green-800 border-green-300",
    pending: "bg-yellow-100 text-yellow-800 border-yellow-300",
    "on-hold": "bg-orange-100 text-orange-800 border-orange-300",
    cancelled: "bg-red-100 text-red-800 border-red-300",
    expired: "bg-gray-100 text-gray-800 border-gray-300",
    "pending-cancel": "bg-orange-100 text-orange-800 border-orange-300",
};

const statusLabels: Record<string, string> = {
    active: "Active",
    pending: "Pending",
    "on-hold": "On Hold",
    cancelled: "Cancelled",
    expired: "Expired",
    "pending-cancel": "Pending Cancellation",
};

export function SubscriptionDetailDialog({
    subscription: initialSubscription,
    open,
    onOpenChange,
    onUpdate,
}: SubscriptionDetailDialogProps) {
    const [loading, setLoading] = useState(false);
    const [confirmAction, setConfirmAction] = useState<string | null>(null);
    const [note, setNote] = useState("");
    const [newStatus, setNewStatus] = useState("");
    const [subscription, setSubscription] = useState<Subscription | null>(initialSubscription);

    // Update local state when prop changes (e.g., when dialog opens with new subscription)
    useEffect(() => {
        setSubscription(initialSubscription);
    }, [initialSubscription]);

    if (!subscription) return null;

    const fetchSubscription = async () => {
        try {
            const apiUrl = window.swiftCommerceData?.apiUrl || '/wp-json/swift-commerce/v1';
            const response = await fetch(
                `${apiUrl}/subscriptions/${subscription.id}`,
                {
                    headers: {
                        "X-WP-Nonce": window.swiftCommerceData?.restNonce || "",
                    },
                }
            );
            const data = await response.json();
            if (data.success && data.subscription) {
                setSubscription(data.subscription);
            }
        } catch (error) {
            console.error('Failed to fetch subscription:', error);
        }
    };

    const formatDate = (dateString: string | null | undefined) => {
        if (!dateString) return "—";
        return new Date(dateString).toLocaleDateString("en-US", {
            year: "numeric",
            month: "long",
            day: "numeric",
        });
    };

    const formatDateTime = (dateString: string | null | undefined) => {
        if (!dateString) return "—";
        return new Date(dateString).toLocaleString("en-US", {
            year: "numeric",
            month: "short",
            day: "numeric",
            hour: "2-digit",
            minute: "2-digit",
        });
    };

    const formatBillingPeriod = (interval: number, period: string) => {
        if (interval === 1) {
            return `Every ${period}`;
        }
        return `Every ${interval} ${period}s`;
    };

    const formatCurrency = (amount: number) => {
        return new Intl.NumberFormat(undefined, {
            style: "currency",
            currency: subscription?.currency || "USD",
        }).format(amount);
    };

    const performAction = async (action: string, additionalData?: Record<string, unknown>) => {
        setLoading(true);
        try {
            const apiUrl = window.swiftCommerceData?.apiUrl || '/wp-json/swift-commerce/v1';
            const response = await fetch(
                `${apiUrl}/subscriptions/${subscription.id}/action`,
                {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                        "X-WP-Nonce": window.swiftCommerceData?.restNonce || "",
                    },
                    body: JSON.stringify({
                        action,
                        note,
                        ...additionalData,
                    }),
                }
            );
            
            const data = await response.json();
            
            if (data.success) {
                toast.success(`Subscription ${action} successfully`);
                setNote("");
                setConfirmAction(null);
                
                // Update local subscription state immediately if returned
                if (data.subscription) {
                    setSubscription(data.subscription);
                } else {
                    // Fallback: fetch the updated subscription
                    await fetchSubscription();
                }
                
                // Also notify parent to refresh list
                onUpdate();
            } else {
                toast.error(data.message || `Failed to ${action} subscription`);
            }
        } catch (error) {
            console.error(`Failed to ${action} subscription:`, error);
            toast.error(`Failed to ${action} subscription`);
        } finally {
            setLoading(false);
        }
    };

    const canActivate = ["pending", "on-hold", "cancelled"].includes(subscription.status);
    const canSuspend = subscription.status === "active";
    const canCancel = ["active", "on-hold", "pending"].includes(subscription.status);

    return (
        <>
            <Dialog open={open} onOpenChange={onOpenChange}>
                <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
                    <DialogHeader>
                        <div className="flex items-center justify-between">
                            <DialogTitle className="text-xl">
                                Subscription #{subscription.id}
                            </DialogTitle>
                            <Badge
                                variant="outline"
                                className={statusColors[subscription.status] || ""}
                            >
                                {statusLabels[subscription.status] || subscription.status}
                            </Badge>
                        </div>
                        <DialogDescription>
                            Created on {formatDateTime(subscription.created_at)}
                        </DialogDescription>
                    </DialogHeader>

                    <div className="grid gap-6 py-4">
                        {/* Quick Actions */}
                        <div className="flex flex-wrap gap-2">
                            {canActivate && (
                                <Button
                                    variant="default"
                                    size="sm"
                                    onClick={() => setConfirmAction("activate")}
                                    disabled={loading}
                                >
                                    <Play className="h-4 w-4 mr-1" />
                                    Activate
                                </Button>
                            )}
                            {canSuspend && (
                                <Button
                                    variant="outline"
                                    size="sm"
                                    onClick={() => setConfirmAction("suspend")}
                                    disabled={loading}
                                >
                                    <Pause className="h-4 w-4 mr-1" />
                                    Suspend
                                </Button>
                            )}
                            {canCancel && (
                                <Button
                                    variant="destructive"
                                    size="sm"
                                    onClick={() => setConfirmAction("cancel")}
                                    disabled={loading}
                                >
                                    <XCircle className="h-4 w-4 mr-1" />
                                    Cancel
                                </Button>
                            )}
                            {subscription.status === "active" && (
                                <Button
                                    variant="outline"
                                    size="sm"
                                    onClick={() => setConfirmAction("renew")}
                                    disabled={loading}
                                >
                                    <RefreshCw className="h-4 w-4 mr-1" />
                                    Process Renewal
                                </Button>
                            )}
                        </div>

                        <Separator />

                        {/* Subscription Details Grid */}
                        <div className="grid md:grid-cols-2 gap-6">
                            {/* Left Column */}
                            <div className="space-y-4">
                                {/* Product Info */}
                                <div className="bg-muted/50 rounded-lg p-4">
                                    <h4 className="font-medium flex items-center gap-2 mb-3">
                                        <Package className="h-4 w-4" />
                                        Product Details
                                    </h4>
                                    <div className="space-y-2 text-sm">
                                        <div className="flex justify-between">
                                            <span className="text-muted-foreground">Product</span>
                                            <span className="font-medium">
                                                {subscription.product_name || `Product #${subscription.product_id}`}
                                            </span>
                                        </div>
                                        {subscription.variation_id > 0 && (
                                            <div className="flex justify-between">
                                                <span className="text-muted-foreground">Variation</span>
                                                <span>#{subscription.variation_id}</span>
                                            </div>
                                        )}
                                        <div className="flex justify-between">
                                            <span className="text-muted-foreground">Quantity</span>
                                            <span>{subscription.quantity}</span>
                                        </div>
                                    </div>
                                </div>

                                {/* Customer Info */}
                                <div className="bg-muted/50 rounded-lg p-4">
                                    <h4 className="font-medium flex items-center gap-2 mb-3">
                                        <User className="h-4 w-4" />
                                        Customer
                                    </h4>
                                    <div className="space-y-2 text-sm">
                                        <div className="flex justify-between">
                                            <span className="text-muted-foreground">Name</span>
                                            <span className="font-medium">
                                                {subscription.customer_name || `Customer #${subscription.customer_id}`}
                                            </span>
                                        </div>
                                        {subscription.customer_email && (
                                            <div className="flex justify-between">
                                                <span className="text-muted-foreground">Email</span>
                                                <span>{subscription.customer_email}</span>
                                            </div>
                                        )}
                                        <div className="flex justify-between">
                                            <span className="text-muted-foreground">Customer ID</span>
                                            <span>#{subscription.customer_id}</span>
                                        </div>
                                    </div>
                                </div>

                                {/* Payment Info */}
                                <div className="bg-muted/50 rounded-lg p-4">
                                    <h4 className="font-medium flex items-center gap-2 mb-3">
                                        <CreditCard className="h-4 w-4" />
                                        Payment
                                    </h4>
                                    <div className="space-y-2 text-sm">
                                        <div className="flex justify-between">
                                            <span className="text-muted-foreground">Method</span>
                                            <span>{subscription.payment_method_title || subscription.payment_method || "—"}</span>
                                        </div>
                                        <div className="flex justify-between">
                                            <span className="text-muted-foreground">Renewal Type</span>
                                            <span>
                                                {subscription.requires_manual_renewal ? "Manual" : "Automatic"}
                                            </span>
                                        </div>
                                        <div className="flex justify-between">
                                            <span className="text-muted-foreground">Order ID</span>
                                            <a 
                                                href={`/wp-admin/post.php?post=${subscription.order_id}&action=edit`}
                                                target="_blank"
                                                rel="noopener noreferrer"
                                                className="text-primary hover:underline"
                                            >
                                                #{subscription.order_id}
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            {/* Right Column */}
                            <div className="space-y-4">
                                {/* Billing Info */}
                                <div className="bg-muted/50 rounded-lg p-4">
                                    <h4 className="font-medium flex items-center gap-2 mb-3">
                                        <DollarSign className="h-4 w-4" />
                                        Billing
                                    </h4>
                                    <div className="space-y-2 text-sm">
                                        <div className="flex justify-between">
                                            <span className="text-muted-foreground">Amount</span>
                                            <span className="font-semibold text-lg">
                                                {formatCurrency(subscription.total)}
                                            </span>
                                        </div>
                                        <div className="flex justify-between">
                                            <span className="text-muted-foreground">Billing Cycle</span>
                                            <span>
                                                {formatBillingPeriod(subscription.billing_interval, subscription.billing_period)}
                                            </span>
                                        </div>
                                        {subscription.trial_end && (
                                            <div className="flex justify-between">
                                                <span className="text-muted-foreground">Trial Ends</span>
                                                <span>{formatDate(subscription.trial_end)}</span>
                                            </div>
                                        )}
                                    </div>
                                </div>

                                {/* Schedule Info */}
                                <div className="bg-muted/50 rounded-lg p-4">
                                    <h4 className="font-medium flex items-center gap-2 mb-3">
                                        <Calendar className="h-4 w-4" />
                                        Schedule
                                    </h4>
                                    <div className="space-y-2 text-sm">
                                        <div className="flex justify-between">
                                            <span className="text-muted-foreground">Start Date</span>
                                            <span>{formatDate(subscription.start_date)}</span>
                                        </div>
                                        <div className="flex justify-between">
                                            <span className="text-muted-foreground">Next Payment</span>
                                            <span className="font-medium">
                                                {subscription.status === "active" 
                                                    ? formatDate(subscription.next_payment_date)
                                                    : "—"
                                                }
                                            </span>
                                        </div>
                                        {subscription.last_payment_date && (
                                            <div className="flex justify-between">
                                                <span className="text-muted-foreground">Last Payment</span>
                                                <span>{formatDate(subscription.last_payment_date)}</span>
                                            </div>
                                        )}
                                        {subscription.end_date && (
                                            <div className="flex justify-between">
                                                <span className="text-muted-foreground">End Date</span>
                                                <span>{formatDate(subscription.end_date)}</span>
                                            </div>
                                        )}
                                        {subscription.cancelled_date && (
                                            <div className="flex justify-between">
                                                <span className="text-muted-foreground">Cancelled</span>
                                                <span className="text-red-600">{formatDate(subscription.cancelled_date)}</span>
                                            </div>
                                        )}
                                    </div>
                                </div>

                                {/* Status Info */}
                                <div className="bg-muted/50 rounded-lg p-4">
                                    <h4 className="font-medium flex items-center gap-2 mb-3">
                                        <History className="h-4 w-4" />
                                        Status
                                    </h4>
                                    <div className="space-y-2 text-sm">
                                        <div className="flex justify-between">
                                            <span className="text-muted-foreground">Suspension Count</span>
                                            <span>{subscription.suspension_count}</span>
                                        </div>
                                        <div className="flex justify-between">
                                            <span className="text-muted-foreground">Last Updated</span>
                                            <span>{formatDateTime(subscription.updated_at)}</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <Separator />

                        {/* Change Status Section */}
                        <div className="bg-muted/30 rounded-lg p-4">
                            <h4 className="font-medium flex items-center gap-2 mb-3">
                                <FileText className="h-4 w-4" />
                                Change Status
                            </h4>
                            <div className="grid gap-4">
                                <div className="grid grid-cols-2 gap-4">
                                    <div>
                                        <Label>New Status</Label>
                                        <Select value={newStatus} onValueChange={setNewStatus}>
                                            <SelectTrigger className="mt-1">
                                                <SelectValue placeholder="Select status" />
                                            </SelectTrigger>
                                            <SelectContent>
                                                <SelectItem value="active">Active</SelectItem>
                                                <SelectItem value="pending">Pending</SelectItem>
                                                <SelectItem value="on-hold">On Hold</SelectItem>
                                                <SelectItem value="cancelled">Cancelled</SelectItem>
                                                <SelectItem value="expired">Expired</SelectItem>
                                            </SelectContent>
                                        </Select>
                                    </div>
                                    <div>
                                        <Label>Note (optional)</Label>
                                        <Textarea
                                            placeholder="Add a note for this change..."
                                            value={note}
                                            onChange={(e) => setNote(e.target.value)}
                                            className="mt-1 h-10"
                                        />
                                    </div>
                                </div>
                                <Button
                                    onClick={() => performAction("change_status", { new_status: newStatus })}
                                    disabled={loading || !newStatus || newStatus === subscription.status}
                                    className="w-full sm:w-auto"
                                >
                                    {loading ? (
                                        <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
                                    ) : null}
                                    Update Status
                                </Button>
                            </div>
                        </div>
                    </div>
                </DialogContent>
            </Dialog>

            {/* Confirmation Dialogs */}
            <AlertDialog open={confirmAction === "activate"} onOpenChange={() => setConfirmAction(null)}>
                <AlertDialogContent>
                    <AlertDialogHeader>
                        <AlertDialogTitle>Activate Subscription</AlertDialogTitle>
                        <AlertDialogDescription>
                            This will activate the subscription and schedule the next payment.
                            The customer will start being charged according to the billing schedule.
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel>Cancel</AlertDialogCancel>
                        <AlertDialogAction onClick={() => performAction("activate")}>
                            Activate
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>

            <AlertDialog open={confirmAction === "suspend"} onOpenChange={() => setConfirmAction(null)}>
                <AlertDialogContent>
                    <AlertDialogHeader>
                        <AlertDialogTitle>Suspend Subscription</AlertDialogTitle>
                        <AlertDialogDescription>
                            This will put the subscription on hold. No payments will be processed
                            until the subscription is reactivated.
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel>Cancel</AlertDialogCancel>
                        <AlertDialogAction onClick={() => performAction("suspend")}>
                            Suspend
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>

            <AlertDialog open={confirmAction === "cancel"} onOpenChange={() => setConfirmAction(null)}>
                <AlertDialogContent>
                    <AlertDialogHeader>
                        <AlertDialogTitle>Cancel Subscription</AlertDialogTitle>
                        <AlertDialogDescription>
                            Are you sure you want to cancel this subscription? This action cannot be easily undone.
                            The customer will no longer be charged.
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel>Keep Subscription</AlertDialogCancel>
                        <AlertDialogAction 
                            onClick={() => performAction("cancel")}
                            className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                        >
                            Cancel Subscription
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>

            <AlertDialog open={confirmAction === "renew"} onOpenChange={() => setConfirmAction(null)}>
                <AlertDialogContent>
                    <AlertDialogHeader>
                        <AlertDialogTitle>Process Renewal</AlertDialogTitle>
                        <AlertDialogDescription>
                            This will manually process a renewal for this subscription,
                            creating a new renewal order and updating the next payment date.
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel>Cancel</AlertDialogCancel>
                        <AlertDialogAction onClick={() => performAction("renew")}>
                            Process Renewal
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>
        </>
    );
}
