import FrontendLayout from '@/layouts/frontend/layout';
import { type BreadcrumbItem, type SharedData } from '@/types';
import { Head, useForm } from '@inertiajs/react';
import { Button } from '@/components/ui/button';
import { CalendarDays, Gift } from 'lucide-react';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { useState, useMemo } from 'react';
import { Label } from '@/components/ui/label';
import { ItemTooltip } from '@/components/game/item-tooltip';
import { toast } from 'sonner';

const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Dashboard', href: '/dashboard' },
    { title: 'Event', href: '/dashboard/event' },
];

interface EventData {
    id: number;
    name: string;
    milestone: number;
    min_level: number;
    item_id: number;
    item_name: string;
    item_count: number;
    is_eligible: boolean;
    is_claimed: boolean;
    claimed_at: string | null;
    claimed_character: string | null;
    progress: number;
}

interface Character {
    id: number;
    name: string;
    level: number;
}

interface EventPageProps extends SharedData {
    events: EventData[];
    currentRegistrationCount: number;
    userCharacters: Character[];
}

export default function EventPage({
    events,
    currentRegistrationCount: _currentRegistrationCount,
    userCharacters,
}: EventPageProps) {
    const [showClaimDialog, setShowClaimDialog] = useState(false);
    const [showClaimAllDialog, setShowClaimAllDialog] = useState(false);
    const [selectedEvent, setSelectedEvent] = useState<EventData | null>(null);

    // Pagination State
    const [currentPage, setCurrentPage] = useState(0);
    const itemsPerPage = 6;

    const totalPages = Math.ceil(events.length / itemsPerPage);
    const visibleEvents = useMemo(() => {
        const start = currentPage * itemsPerPage;
        return events.slice(start, start + itemsPerPage);
    }, [events, currentPage]);

    const { data, setData, post, processing, reset } = useForm({
        event_id: '',
        role_id: '',
    });

    const handleOpenClaimDialog = (event: EventData) => {
        setSelectedEvent(event);
        setData('event_id', String(event.id));
        setShowClaimDialog(true);
    };

    const handleClaimSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        post('/dashboard/event/claim', {
            onSuccess: () => {
                setShowClaimDialog(false);
                reset();
                setSelectedEvent(null);
                toast.success('Reward claimed successfully! Check your in-game mailbox.');
            },
            onError: (errors: Record<string, string>) => {
                console.error('Claim errors:', errors);
                if (errors.error) {
                    toast.error(errors.error);
                } else {
                    toast.error('Failed to claim reward. Please try again.');
                }
            },
        });
    };

    const handleClaimAllSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        post('/dashboard/event/claim-all', {
            onSuccess: () => {
                setShowClaimAllDialog(false);
                reset();
                toast.success('All rewards claimed successfully!');
            },
            onError: (errors: Record<string, string>) => {
                console.error('Claim all errors:', errors);
                if (errors.error) {
                    toast.error(errors.error);
                } else {
                    toast.error('Failed to claim rewards. Please try again.');
                }
            },
        });
    };

    return (
        <FrontendLayout breadcrumbs={breadcrumbs}>
            <Head title="Event" />

            <div className="space-y-6">
                {/* Header */}
                <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
                    <div>
                        <h2 className="text-xl font-bold flex items-center gap-2">
                            <CalendarDays className="w-5 h-5 text-primary" />
                            Event
                        </h2>
                    </div>
                    {events.some((e) => e.is_eligible && !e.is_claimed) && (
                        <Button onClick={() => {
                            reset();
                            setShowClaimAllDialog(true);
                        }}>
                            <Gift className="w-4 h-4 mr-2" />
                            Claim All Rewards
                        </Button>
                    )}
                </div>

                {/* Events Grid */}
                {events.length > 0 ? (
                    <>
                        <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
                            {visibleEvents.map((event) => (
                                <div key={event.id} className="text-center space-y-3 p-4 relative group">
                                    {/* Event Name */}
                                    <h3 className="font-medium">{event.name}</h3>

                                    {/* Box Icon */}
                                    <div className="flex justify-center">
                                        <picture>
                                            <source srcSet="/img/animations/box_icon.webp" type="image/webp" />
                                            <img
                                                src="/img/animations/box_icon.png"
                                                alt="Event Reward"
                                                width={128}
                                                height={128}
                                                loading="lazy"
                                                decoding="async"
                                                className={`w-32 h-32 object-contain ${event.is_claimed ? 'opacity-50 grayscale' : ''}`}
                                            />
                                        </picture>
                                    </div>





                                    {/* Claim Button */}
                                    {event.is_eligible && !event.is_claimed && (
                                        <div
                                            onClick={() => handleOpenClaimDialog(event)}
                                            className="relative flex justify-center mt-2 cursor-pointer transition-transform hover:scale-105"
                                        >
                                            <picture>
                                                <source srcSet="/img/button/button_claim.webp" type="image/webp" />
                                                <img
                                                    src="/img/button/button_claim.png"
                                                    alt="Claim"
                                                    width={309}
                                                    height={68}
                                                    loading="eager"
                                                    decoding="async"
                                                    className="h-6 object-contain"
                                                />
                                            </picture>
                                            <span className="absolute inset-0 flex items-center justify-center text-xs font-bold text-white drop-shadow-md uppercase tracking-wider pt-0.5">
                                                Claim
                                            </span>
                                        </div>
                                    )}


                                </div>
                            ))}
                        </div>
                        {/* Pagination Controls */}
                        {totalPages > 1 && (
                            <div className="flex justify-center gap-2 mt-6">
                                <Button
                                    variant="outline"
                                    onClick={() => setCurrentPage((p) => Math.max(0, p - 1))}
                                    disabled={currentPage === 0}
                                >
                                    Previous
                                </Button>
                                <span className="flex items-center px-4 text-sm font-medium">
                                    Page {currentPage + 1} of {totalPages}
                                </span>
                                <Button
                                    variant="outline"
                                    onClick={() => setCurrentPage((p) => Math.min(totalPages - 1, p + 1))}
                                    disabled={currentPage >= totalPages - 1}
                                >
                                    Next
                                </Button>
                            </div>
                        )}
                    </>
                ) : (
                    <div className="py-12 text-center text-muted-foreground">
                        <picture>
                            <source srcSet="/img/animations/box_icon.webp" type="image/webp" />
                            <img
                                src="/img/animations/box_icon.png"
                                alt="No Events"
                                width={80}
                                height={80}
                                loading="lazy"
                                decoding="async"
                                className="w-20 h-20 mx-auto mb-3 opacity-50"
                            />
                        </picture>
                        <p>No active events</p>
                    </div>
                )}
            </div>

            {/* Claim Dialog */}
            <Dialog open={showClaimDialog} onOpenChange={setShowClaimDialog}>
                <DialogContent className="sm:max-w-md">
                    <DialogHeader>
                        <DialogTitle>Claim Reward</DialogTitle>
                        <DialogDescription>
                            Select a character to receive your reward.
                        </DialogDescription>
                    </DialogHeader>
                    <form onSubmit={handleClaimSubmit}>
                        <div className="py-4 space-y-4">
                            {selectedEvent && (
                                <div className="flex flex-col items-center gap-3 p-4 rounded-lg bg-muted">
                                    <picture>
                                        <source srcSet="/img/animations/box_icon.webp" type="image/webp" />
                                        <img
                                            src="/img/animations/box_icon.png"
                                            alt="Reward"
                                            width={64}
                                            height={64}
                                            loading="lazy"
                                            decoding="async"
                                            className="w-16 h-16 object-contain"
                                        />
                                    </picture>
                                    <div className="flex items-center justify-center">
                                        <ItemTooltip itemId={selectedEvent.item_id} showName={true} iconSize={20} />
                                        <span className="ml-1 text-sm font-medium">x{selectedEvent.item_count}</span>
                                    </div>
                                </div>
                            )}
                            <div className="space-y-2">
                                <Label>Character</Label>
                                <Select
                                    value={data.role_id}
                                    onValueChange={(value) => setData('role_id', value)}
                                >
                                    <SelectTrigger>
                                        <SelectValue placeholder="Select character" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {userCharacters.map((char) => {
                                            const isLevelValid = selectedEvent ? char.level >= selectedEvent.min_level : true;
                                            return (
                                                <SelectItem
                                                    key={char.id}
                                                    value={String(char.id)}
                                                    disabled={!isLevelValid}
                                                >
                                                    {char.name} (Lv. {char.level})
                                                    {!isLevelValid && selectedEvent && ` - Min Lv. ${selectedEvent.min_level}`}
                                                </SelectItem>
                                            );
                                        })}
                                    </SelectContent>
                                </Select>
                            </div>
                        </div>
                        <DialogFooter>
                            <Button type="button" variant="outline" onClick={() => setShowClaimDialog(false)}>
                                Cancel
                            </Button>
                            <Button type="submit" disabled={processing || !data.role_id}>
                                Claim
                            </Button>
                        </DialogFooter>
                    </form>
                </DialogContent>
            </Dialog>

            {/* Claim All Dialog */}
            <Dialog open={showClaimAllDialog} onOpenChange={setShowClaimAllDialog}>
                <DialogContent className="sm:max-w-md">
                    <DialogHeader>
                        <DialogTitle>Claim All Rewards</DialogTitle>
                        <DialogDescription>
                            Select a character to receive all available rewards.
                        </DialogDescription>
                    </DialogHeader>
                    <form onSubmit={handleClaimAllSubmit}>
                        <div className="py-4 space-y-4">
                            <div className="flex flex-col items-center gap-3 p-4 rounded-lg bg-muted">
                                <picture>
                                    <source srcSet="/img/animations/box_icon.webp" type="image/webp" />
                                    <img
                                        src="/img/animations/box_icon.png"
                                        alt="Rewards"
                                        width={64}
                                        height={64}
                                        loading="lazy"
                                        decoding="async"
                                        className="w-16 h-16 object-contain"
                                    />
                                </picture>
                                <div className="text-sm font-medium">
                                    {events.filter(e => e.is_eligible && !e.is_claimed).length} reward(s) available
                                </div>
                            </div>
                            <div className="space-y-2">
                                <Label>Character</Label>
                                <Select
                                    value={data.role_id}
                                    onValueChange={(value) => setData('role_id', value)}
                                >
                                    <SelectTrigger>
                                        <SelectValue placeholder="Select character" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {userCharacters.map((char) => {
                                            // Check if character is eligible for at least one claimable event
                                            const canClaimAny = events
                                                .filter(e => e.is_eligible && !e.is_claimed)
                                                .some(e => char.level >= e.min_level);

                                            return (
                                                <SelectItem
                                                    key={char.id}
                                                    value={String(char.id)}
                                                    disabled={!canClaimAny}
                                                >
                                                    {char.name} (Lv. {char.level})
                                                    {!canClaimAny && " - Level too low"}
                                                </SelectItem>
                                            );
                                        })}
                                    </SelectContent>
                                </Select>
                            </div>
                        </div>
                        <DialogFooter>
                            <Button type="button" variant="outline" onClick={() => setShowClaimAllDialog(false)}>
                                Cancel
                            </Button>
                            <Button type="submit" disabled={processing || !data.role_id}>
                                Claim All
                            </Button>
                        </DialogFooter>
                    </form>
                </DialogContent>
            </Dialog>
        </FrontendLayout>
    );
}
