import React, { useState, useEffect, useCallback } from 'react';
import { useQuery, useMutation, useQueryClient, keepPreviousData } from '@tanstack/react-query';
import { useNavigate, Link } from 'react-router-dom';
import { Repeat, MoreHorizontal, Play, Pause, XCircle, RefreshCw, Eye, Filter, Package } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
    Select,
    SelectContent,
    SelectGroup,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Skeleton } from '@/components/ui/skeleton';
import { ErrorCard } from '@/components/ErrorCard';
import { getPageLoadErrorMessage } from '@/lib/errorHandling';
import { usePageHeader } from '@/contexts/PageHeaderContext';
import { __ } from '@/lib/i18n';
import { toast } from 'sonner';
import { api } from '@/lib/api';
import { setQuery, getQuery } from '@/lib/query-params';
import { Pagination } from '@/components/Pagination';

interface Subscription {
    id: number;
    user_id: number;
    order_id: number;
    product_id: number;
    product_name: string;
    user_name: string;
    user_email: string;
    status: 'pending' | 'active' | 'on-hold' | 'cancelled' | 'expired' | 'pending-cancel';
    billing_schedule: string;
    recurring_amount: string;
    next_payment_date: string | null;
    created_at: string;
    can_pause: boolean;
    can_resume: boolean;
    can_cancel: boolean;
}

const statusColors: Record<string, string> = {
    'pending': 'bg-amber-100 text-amber-800',
    'active': 'bg-emerald-100 text-emerald-800',
    'on-hold': 'bg-blue-100 text-blue-800',
    'cancelled': 'bg-zinc-200 text-zinc-800',
    'expired': 'bg-rose-100 text-rose-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'),
};

function StatusBadge({ value }: { value?: string }) {
    const v = (value || '').toLowerCase();
    const cls = statusColors[v] || 'bg-slate-100 text-slate-800';
    return (
        <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium capitalize ${cls}`}>
            {statusLabels[v] || v || 'unknown'}
        </span>
    );
}

export default function SubscriptionsIndex() {
    const navigate = useNavigate();
    const queryClient = useQueryClient();
    const { setPageHeader, clearPageHeader } = usePageHeader();

    const initial = getQuery();
    const [page, setPage] = useState(Number(initial.page ?? 1) || 1);
    const [status, setStatus] = useState<string | undefined>(initial.status || undefined);
    const [isRefreshing, setIsRefreshing] = useState(false);
    const [showCancelDialog, setShowCancelDialog] = useState(false);
    const [cancelTargetId, setCancelTargetId] = useState<number | null>(null);
    const perPage = 20;

    useEffect(() => {
        setPageHeader(__('Subscriptions'));
        return () => clearPageHeader();
    }, [setPageHeader, clearPageHeader]);

    useEffect(() => {
        setQuery({ page, status });
    }, [page, status]);

    const q = useQuery({
        queryKey: ['subscriptions', { status, page }],
        queryFn: () => api.get('/subscriptions', { status, page, per_page: perPage }),
        placeholderData: keepPreviousData,
    });

    const data = q.data as undefined | { subscriptions: Subscription[]; total: number };
    const subscriptions: Subscription[] = data?.subscriptions || [];
    const total = data?.total || 0;

    // Pull to refresh
    const handleRefresh = useCallback(async () => {
        setIsRefreshing(true);
        await q.refetch();
        setTimeout(() => setIsRefreshing(false), 500);
    }, [q]);

    // Subscription action mutation (using centralized api)
    const actionMutation = useMutation({
        mutationFn: ({ id, action, reason }: { id: number; action: string; reason?: string }) =>
            api.post(`/subscriptions/${id}/${action}`, { reason }),
        onSuccess: (_, { action }) => {
            queryClient.invalidateQueries({ queryKey: ['subscriptions'] });
            toast.success(__(`Subscription ${action}d successfully`));
            setShowCancelDialog(false);
            setCancelTargetId(null);
        },
        onError: (error: Error) => {
            toast.error(error.message);
            setShowCancelDialog(false);
        },
    });

    const handleAction = (id: number, action: string) => {
        if (action === 'cancel') {
            setCancelTargetId(id);
            setShowCancelDialog(true);
            return;
        }
        actionMutation.mutate({ id, action });
    };

    const confirmCancel = () => {
        if (cancelTargetId) {
            actionMutation.mutate({ id: cancelTargetId, action: 'cancel' });
        }
    };

    // Checkbox logic
    const [selectedIds, setSelectedIds] = useState<number[]>([]);
    const allIds = subscriptions.map(s => s.id);
    const allSelected = allIds.length > 0 && selectedIds.length === allIds.length;
    const someSelected = selectedIds.length > 0 && selectedIds.length < allIds.length;

    const toggleAll = () => {
        if (allSelected) {
            setSelectedIds([]);
        } else {
            setSelectedIds(allIds);
        }
    };

    const toggleRow = (id: number) => {
        setSelectedIds(prev =>
            prev.includes(id) ? prev.filter(i => i !== id) : [...prev, id]
        );
    };

    return (
        <div className="space-y-4 w-full pb-4">
            {/* Desktop: Toolbar Card */}
            <div className="hidden md:block rounded-lg border border-border p-4 bg-card">
                <div className="flex flex-col lg:flex-row lg:justify-between lg:items-center gap-3">
                    <div className="flex gap-3">
                        <button
                            className="border rounded-md px-3 py-2 text-sm hover:bg-accent disabled:opacity-50 inline-flex items-center gap-2"
                            onClick={handleRefresh}
                            disabled={q.isLoading || isRefreshing}
                        >
                            <RefreshCw className={`w-4 h-4 ${isRefreshing ? 'animate-spin' : ''}`} />
                            {__('Refresh')}
                        </button>
                    </div>

                    <div className="flex gap-2 items-center">
                        <Filter className="min-w-4 w-4 h-4 opacity-60" />
                        <Select
                            value={status ?? 'all'}
                            onValueChange={(v) => {
                                setPage(1);
                                setStatus(v === 'all' ? undefined : v);
                            }}
                        >
                            <SelectTrigger className="min-w-[140px]">
                                <SelectValue placeholder={__('All statuses')} />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectGroup>
                                    <SelectItem value="all">{__('All statuses')}</SelectItem>
                                    <SelectItem value="active">{__('Active')}</SelectItem>
                                    <SelectItem value="on-hold">{__('On Hold')}</SelectItem>
                                    <SelectItem value="pending">{__('Pending')}</SelectItem>
                                    <SelectItem value="cancelled">{__('Cancelled')}</SelectItem>
                                    <SelectItem value="expired">{__('Expired')}</SelectItem>
                                    <SelectItem value="pending-cancel">{__('Pending Cancel')}</SelectItem>
                                </SelectGroup>
                            </SelectContent>
                        </Select>

                        {status && (
                            <button
                                className="text-sm text-muted-foreground hover:text-foreground underline text-nowrap"
                                onClick={() => { setStatus(undefined); setPage(1); }}
                            >
                                {__('Clear filters')}
                            </button>
                        )}

                        <span className="text-sm text-muted-foreground ml-2">
                            {total} {__('subscriptions')}
                        </span>
                    </div>
                </div>
            </div>

            {/* Mobile: Status filter bar */}
            <div className="md:hidden">
                <div className="flex items-center gap-2">
                    <Select
                        value={status ?? 'all'}
                        onValueChange={(v) => {
                            setPage(1);
                            setStatus(v === 'all' ? undefined : v);
                        }}
                    >
                        <SelectTrigger className="flex-1">
                            <SelectValue placeholder={__('All statuses')} />
                        </SelectTrigger>
                        <SelectContent>
                            <SelectGroup>
                                <SelectItem value="all">{__('All statuses')}</SelectItem>
                                <SelectItem value="active">{__('Active')}</SelectItem>
                                <SelectItem value="on-hold">{__('On Hold')}</SelectItem>
                                <SelectItem value="pending">{__('Pending')}</SelectItem>
                                <SelectItem value="cancelled">{__('Cancelled')}</SelectItem>
                                <SelectItem value="expired">{__('Expired')}</SelectItem>
                            </SelectGroup>
                        </SelectContent>
                    </Select>
                    <button
                        className="border rounded-md px-3 py-2 text-sm hover:bg-accent disabled:opacity-50"
                        onClick={handleRefresh}
                        disabled={q.isLoading || isRefreshing}
                    >
                        <RefreshCw className={`w-4 h-4 ${isRefreshing ? 'animate-spin' : ''}`} />
                    </button>
                </div>
            </div>

            {/* Pull to Refresh Indicator */}
            {isRefreshing && (
                <div className="md:hidden flex justify-center py-2">
                    <RefreshCw className="w-5 h-5 animate-spin text-primary" />
                </div>
            )}

            {/* Loading State */}
            {q.isLoading && (
                <div className="space-y-3">
                    {Array.from({ length: 5 }).map((_, i) => (
                        <Skeleton key={i} className="w-full h-24 rounded-lg" />
                    ))}
                </div>
            )}

            {/* Error State */}
            {q.isError && (
                <ErrorCard
                    title={__('Failed to load subscriptions')}
                    message={getPageLoadErrorMessage(q.error)}
                    onRetry={() => q.refetch()}
                />
            )}

            {/* Content */}
            {!q.isLoading && !q.isError && (
                <>
                    {/* Mobile: Card List */}
                    <div className="md:hidden space-y-3">
                        {subscriptions.length > 0 ? (
                            subscriptions.map((sub) => (
                                <Link
                                    key={sub.id}
                                    to={`/subscriptions/${sub.id}`}
                                    className="block rounded-lg border bg-card p-4 hover:bg-accent/50 transition-colors"
                                >
                                    <div className="flex items-start justify-between mb-2">
                                        <div>
                                            <div className="font-medium">#{sub.id}</div>
                                            <div className="text-sm text-muted-foreground">{sub.user_name}</div>
                                        </div>
                                        <StatusBadge value={sub.status} />
                                    </div>
                                    <div className="text-sm">{sub.product_name}</div>
                                    <div className="flex items-center justify-between mt-2 text-sm text-muted-foreground">
                                        <span>{sub.billing_schedule}</span>
                                        {sub.next_payment_date && (
                                            <span>{new Date(sub.next_payment_date).toLocaleDateString()}</span>
                                        )}
                                    </div>
                                </Link>
                            ))
                        ) : (
                            <div className="flex flex-col items-center justify-center py-12 text-center">
                                <Repeat className="w-12 h-12 opacity-40 mb-3" />
                                <div className="font-medium text-lg mb-1">{__('No subscriptions found')}</div>
                                {status ? (
                                    <p className="text-sm text-muted-foreground">{__('Try adjusting filters.')}</p>
                                ) : (
                                    <p className="text-sm text-muted-foreground">{__('Subscriptions will appear here when customers subscribe.')}</p>
                                )}
                            </div>
                        )}
                    </div>

                    {/* Desktop: Table */}
                    <div className="hidden md:block rounded-lg border overflow-hidden">
                        <table className="min-w-[800px] w-full text-sm">
                            <thead className="bg-muted/50">
                                <tr className="border-b">
                                    <th className="w-12 p-3">
                                        <Checkbox
                                            checked={allSelected}
                                            onCheckedChange={toggleAll}
                                            aria-label={__('Select all')}
                                            className={someSelected ? 'data-[state=checked]:bg-gray-400' : ''}
                                        />
                                    </th>
                                    <th className="text-left p-3 font-medium">{__('ID')}</th>
                                    <th className="text-left p-3 font-medium">{__('Customer')}</th>
                                    <th className="text-left p-3 font-medium">{__('Product')}</th>
                                    <th className="text-left p-3 font-medium">{__('Status')}</th>
                                    <th className="text-left p-3 font-medium">{__('Billing')}</th>
                                    <th className="text-left p-3 font-medium">{__('Next Payment')}</th>
                                    <th className="text-center p-3 font-medium">{__('Actions')}</th>
                                </tr>
                            </thead>
                            <tbody>
                                {subscriptions.map((sub) => (
                                    <tr key={sub.id} className="border-b hover:bg-muted/30 last:border-0">
                                        <td className="p-3">
                                            <Checkbox
                                                checked={selectedIds.includes(sub.id)}
                                                onCheckedChange={() => toggleRow(sub.id)}
                                                aria-label={__('Select subscription')}
                                            />
                                        </td>
                                        <td className="p-3">
                                            <Link to={`/subscriptions/${sub.id}`} className="font-medium hover:underline">
                                                #{sub.id}
                                            </Link>
                                        </td>
                                        <td className="p-3">
                                            <div>
                                                <div className="font-medium">{sub.user_name}</div>
                                                <div className="text-sm text-muted-foreground">{sub.user_email}</div>
                                            </div>
                                        </td>
                                        <td className="p-3">{sub.product_name}</td>
                                        <td className="p-3">
                                            <StatusBadge value={sub.status} />
                                        </td>
                                        <td className="p-3">
                                            <div className="text-sm">{sub.billing_schedule}</div>
                                        </td>
                                        <td className="p-3">
                                            {sub.next_payment_date ? (
                                                <div className="text-sm">
                                                    {new Date(sub.next_payment_date).toLocaleDateString()}
                                                </div>
                                            ) : (
                                                <span className="text-muted-foreground">—</span>
                                            )}
                                        </td>
                                        <td className="p-3 text-center">
                                            <DropdownMenu>
                                                <DropdownMenuTrigger asChild>
                                                    <Button variant="ghost" className="h-8 w-8 p-0">
                                                        <span className="sr-only">{__('Open menu')}</span>
                                                        <MoreHorizontal className="h-4 w-4" />
                                                    </Button>
                                                </DropdownMenuTrigger>
                                                <DropdownMenuContent align="end">
                                                    <DropdownMenuItem onClick={() => navigate(`/subscriptions/${sub.id}`)}>
                                                        <Eye className="w-4 h-4 mr-2" />
                                                        {__('View Details')}
                                                    </DropdownMenuItem>
                                                    <DropdownMenuSeparator />
                                                    {sub.can_pause && (
                                                        <DropdownMenuItem onClick={() => handleAction(sub.id, 'pause')}>
                                                            <Pause className="w-4 h-4 mr-2" />
                                                            {__('Pause')}
                                                        </DropdownMenuItem>
                                                    )}
                                                    {sub.can_resume && (
                                                        <DropdownMenuItem onClick={() => handleAction(sub.id, 'resume')}>
                                                            <Play className="w-4 h-4 mr-2" />
                                                            {__('Resume')}
                                                        </DropdownMenuItem>
                                                    )}
                                                    {sub.status === 'active' && (
                                                        <DropdownMenuItem onClick={() => handleAction(sub.id, 'renew')}>
                                                            <RefreshCw className="w-4 h-4 mr-2" />
                                                            {__('Renew Now')}
                                                        </DropdownMenuItem>
                                                    )}
                                                    {sub.can_cancel && (
                                                        <>
                                                            <DropdownMenuSeparator />
                                                            <DropdownMenuItem
                                                                onClick={() => handleAction(sub.id, 'cancel')}
                                                                className="text-destructive focus:text-destructive"
                                                            >
                                                                <XCircle className="w-4 h-4 mr-2" />
                                                                {__('Cancel')}
                                                            </DropdownMenuItem>
                                                        </>
                                                    )}
                                                </DropdownMenuContent>
                                            </DropdownMenu>
                                        </td>
                                    </tr>
                                ))}

                                {subscriptions.length === 0 && (
                                    <tr>
                                        <td className="p-8 text-center text-muted-foreground" colSpan={8}>
                                            <div className="flex flex-col items-center gap-2">
                                                <Repeat className="w-8 h-8 opacity-40" />
                                                <div className="font-medium">{__('No subscriptions found')}</div>
                                                {status ? (
                                                    <p className="text-sm opacity-70">{__('Try adjusting filters.')}</p>
                                                ) : (
                                                    <p className="text-sm opacity-70">{__('Subscriptions will appear here when customers subscribe.')}</p>
                                                )}
                                            </div>
                                        </td>
                                    </tr>
                                )}
                            </tbody>
                        </table>
                    </div>
                </>
            )}

            {/* Pagination */}
            {!q.isLoading && !q.isError && data && (
                <Pagination
                    page={page}
                    perPage={perPage}
                    total={total}
                    onPageChange={setPage}
                />
            )}

            {/* Cancel Confirmation Dialog (replaces native confirm()) */}
            <AlertDialog open={showCancelDialog} onOpenChange={setShowCancelDialog}>
                <AlertDialogContent>
                    <AlertDialogHeader>
                        <AlertDialogTitle>{__('Cancel Subscription')}</AlertDialogTitle>
                        <AlertDialogDescription>
                            {__('Are you sure you want to cancel this subscription?')}
                            <br />
                            <span className="text-red-600 font-medium">{__('This action cannot be undone.')}</span>
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel
                            onClick={() => { setShowCancelDialog(false); setCancelTargetId(null); }}
                            disabled={actionMutation.isPending}
                        >
                            {__('Keep Subscription')}
                        </AlertDialogCancel>
                        <AlertDialogAction
                            onClick={confirmCancel}
                            disabled={actionMutation.isPending}
                            className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                        >
                            {actionMutation.isPending ? __('Cancelling...') : __('Cancel Subscription')}
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>
        </div>
    );
}
