import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Link } from 'react-router-dom';
import { api } from '@/lib/api/client';
import { Button } from '@/components/ui/button';
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
    AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import { Repeat, ChevronRight, Pause, Play, XCircle, Calendar, Package } from 'lucide-react';
import { toast } from 'sonner';
import SEOHead from '@/components/SEOHead';
import { formatPrice } from '@/lib/currency';

interface Subscription {
    id: number;
    product_id: number;
    product_name: string;
    product_image: string;
    status: 'pending' | 'active' | 'on-hold' | 'cancelled' | 'expired' | 'pending-cancel';
    billing_schedule: string;
    recurring_amount: string;
    next_payment_date: string | null;
    start_date: string;
    end_date: string | null;
    can_pause: boolean;
    can_resume: boolean;
    can_cancel: boolean;
}

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

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

export default function Subscriptions() {
    const queryClient = useQueryClient();
    const [actionLoading, setActionLoading] = useState<number | null>(null);

    const { data: subscriptions = [], isLoading } = useQuery<Subscription[]>({
        queryKey: ['account-subscriptions'],
        queryFn: () => api.get('/account/subscriptions'),
    });

    const actionMutation = useMutation({
        mutationFn: ({ id, action }: { id: number; action: string }) =>
            api.post(`/account/subscriptions/${id}/${action}`),
        onSuccess: (_, { action }) => {
            queryClient.invalidateQueries({ queryKey: ['account-subscriptions'] });
            const actionLabels: Record<string, string> = {
                'pause': 'paused',
                'resume': 'resumed',
                'cancel': 'cancelled',
            };
            toast.success(`Subscription ${actionLabels[action] || action} successfully`);
            setActionLoading(null);
        },
        onError: (error: any) => {
            toast.error(error.message || 'Action failed');
            setActionLoading(null);
        },
    });

    const handleAction = (id: number, action: string) => {
        setActionLoading(id);
        actionMutation.mutate({ id, action });
    };

    if (isLoading) {
        return (
            <div className="flex items-center justify-center py-12">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
            </div>
        );
    }

    return (
        <div className="space-y-6">
            <SEOHead title="My Subscriptions" description="Manage your subscriptions" />
            <div>
                <h1 className="text-2xl font-bold flex items-center gap-2">
                    <Repeat className="h-6 w-6" />
                    My Subscriptions
                </h1>
                <p className="text-gray-500">
                    Manage your recurring subscriptions
                </p>
            </div>

            {subscriptions.length === 0 ? (
                <div className="bg-white rounded-lg border p-12 text-center">
                    <Repeat className="h-12 w-12 mx-auto mb-4 text-gray-300" />
                    <p className="text-gray-500">You don't have any subscriptions yet.</p>
                    <p className="text-sm text-gray-400 mt-1">
                        Purchase a subscription product to get started.
                    </p>
                </div>
            ) : (
                <div className="space-y-4">
                    {subscriptions.map((sub) => (
                        <div key={sub.id} className="bg-white rounded-lg border overflow-hidden">
                            <div className="p-4">
                                <div className="flex items-start gap-4">
                                    {/* Product Image */}
                                    {sub.product_image ? (
                                        <img
                                            src={sub.product_image}
                                            alt={sub.product_name}
                                            className="w-16 h-16 object-cover rounded"
                                        />
                                    ) : (
                                        <div className="w-16 h-16 bg-gray-100 rounded flex items-center justify-center">
                                            <Package className="h-8 w-8 text-gray-400" />
                                        </div>
                                    )}

                                    {/* Subscription Info */}
                                    <div className="flex-1 min-w-0">
                                        <div className="flex items-start justify-between">
                                            <div>
                                                <h3 className="font-semibold">{sub.product_name}</h3>
                                                <p className="text-sm text-gray-500">{sub.billing_schedule}</p>
                                            </div>
                                            <span className={`px-2 py-1 rounded-full text-xs font-medium ${statusStyles[sub.status] || 'bg-gray-100'}`}>
                                                {statusLabels[sub.status] || sub.status}
                                            </span>
                                        </div>

                                        <div className="mt-3 flex items-center gap-6 text-sm">
                                            <div>
                                                <span className="text-gray-500">Amount: </span>
                                                <span className="font-medium">
                                                    {formatPrice(sub.recurring_amount)}
                                                </span>
                                            </div>
                                            {sub.next_payment_date && (
                                                <div className="flex items-center gap-1">
                                                    <Calendar className="h-4 w-4 text-gray-400" />
                                                    <span className="text-gray-500">Next: </span>
                                                    <span className="font-medium">
                                                        {new Date(sub.next_payment_date).toLocaleDateString()}
                                                    </span>
                                                </div>
                                            )}
                                        </div>
                                    </div>
                                </div>

                                {/* Actions */}
                                <div className="mt-4 pt-4 border-t flex items-center justify-between">
                                    <div className="flex items-center gap-2">
                                        {sub.can_pause && (
                                            <Button
                                                variant="outline"
                                                size="sm"
                                                onClick={() => handleAction(sub.id, 'pause')}
                                                disabled={actionLoading === sub.id}
                                            >
                                                <Pause className="h-4 w-4 mr-1" />
                                                Pause
                                            </Button>
                                        )}
                                        {sub.can_resume && (
                                            <Button
                                                variant="outline"
                                                size="sm"
                                                onClick={() => handleAction(sub.id, 'resume')}
                                                disabled={actionLoading === sub.id}
                                            >
                                                <Play className="h-4 w-4 mr-1" />
                                                Resume
                                            </Button>
                                        )}
                                        {sub.can_cancel && (
                                            <AlertDialog>
                                                <AlertDialogTrigger asChild>
                                                    <Button
                                                        variant="outline"
                                                        size="sm"
                                                        className="text-red-500 hover:text-red-600"
                                                        disabled={actionLoading === sub.id}
                                                    >
                                                        <XCircle className="h-4 w-4 mr-1" />
                                                        Cancel
                                                    </Button>
                                                </AlertDialogTrigger>
                                                <AlertDialogContent>
                                                    <AlertDialogHeader>
                                                        <AlertDialogTitle>Cancel Subscription</AlertDialogTitle>
                                                        <AlertDialogDescription>
                                                            Are you sure you want to cancel this subscription?
                                                            You will lose access at the end of your current billing period.
                                                        </AlertDialogDescription>
                                                    </AlertDialogHeader>
                                                    <AlertDialogFooter>
                                                        <AlertDialogCancel>Keep Subscription</AlertDialogCancel>
                                                        <AlertDialogAction
                                                            onClick={() => handleAction(sub.id, 'cancel')}
                                                            className="bg-red-500 hover:bg-red-600"
                                                        >
                                                            Yes, Cancel
                                                        </AlertDialogAction>
                                                    </AlertDialogFooter>
                                                </AlertDialogContent>
                                            </AlertDialog>
                                        )}
                                    </div>

                                    <Link
                                        to={`/my-account/subscriptions/${sub.id}`}
                                        className="text-sm text-blue-600 hover:text-blue-800 flex items-center gap-1"
                                    >
                                        View Details
                                        <ChevronRight className="h-4 w-4" />
                                    </Link>
                                </div>
                            </div>
                        </div>
                    ))}
                </div>
            )}
        </div>
    );
}
