import { Head, Link, router } from '@inertiajs/react';
import { useState } from 'react';
import UserLayout from '@/components/Layouts/UserLayout';
import Card from '@/components/Card/Card';
import { Show } from '@/types';

interface DashboardProps {
    shows: Show[];
    has_active_membership?: boolean;
    membership_expires_at?: string | null;
    membership_started_at?: string | null;
    streaming_maintenance?: boolean;
}

export default function Dashboard({ 
    shows, 
    has_active_membership = false,
    membership_expires_at = null,
    membership_started_at = null,
    streaming_maintenance = false,
}: DashboardProps) {
    // Filter hanya show yang aktif
    const activeShows = shows.filter((show) => Boolean(show.is_active));

    const handleLiveStream = (show: Show) => {
        if (!show.slug_live) {
            alert('Slug live tidak tersedia untuk show ini');
            return;
        }

        // Langsung redirect ke live player dengan slug
        router.visit(`/live/${show.slug_live}`);
    };

    const formatDate = (timestamp: number): string => {
        const date = new Date(timestamp * 1000);
        return date.toLocaleDateString('id-ID', {
            weekday: 'long',
            year: 'numeric',
            month: 'long',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit',
        });
    };

    const formatPrice = (price: number): string => {
        return new Intl.NumberFormat('id-ID', {
            style: 'currency',
            currency: 'IDR',
            minimumFractionDigits: 0,
        }).format(price);
    };

    return (
        <UserLayout title="Dashboard">
            <Head title="Dashboard" />
            <div className="space-y-6">
                {/* Header */}
                <div>
                    <div className="flex items-center gap-3">
                        <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Dashboard</h1>
                        {has_active_membership && (
                            <span className="inline-flex items-center gap-1.5 rounded-full bg-gradient-to-r from-purple-500 to-pink-500 px-3 py-1 text-xs font-semibold text-white shadow-lg">
                                <CrownIcon className="h-3.5 w-3.5" />
                                Membership Istimewa
                            </span>
                        )}
                    </div>
                    <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
                        {has_active_membership
                            ? 'Akses penuh ke semua show dengan membership Anda'
                            : 'Kelola dan akses show yang telah Anda beli'}
                    </p>
                    {has_active_membership && membership_expires_at && (
                        <div className="mt-2 flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400">
                            <ClockIcon className="h-4 w-4" />
                            <span>
                                Membership berlaku hingga:{' '}
                                <span className="font-medium text-gray-700 dark:text-gray-300">
                                    {new Date(membership_expires_at).toLocaleDateString('id-ID', {
                                        day: 'numeric',
                                        month: 'long',
                                        year: 'numeric',
                                    })}
                                </span>
                            </span>
                        </div>
                    )}
                </div>

                {/* Stats Cards */}
                <div className={`grid grid-cols-1 gap-4 ${has_active_membership ? 'sm:grid-cols-4' : 'sm:grid-cols-3'}`}>
                    {has_active_membership && (
                        <Card padding="md" className="bg-gradient-to-br from-purple-50 to-pink-50 dark:from-purple-900/20 dark:to-pink-900/20 border-purple-200 dark:border-purple-800">
                            <div className="flex items-center justify-between">
                                <div>
                                    <p className="text-sm font-medium text-purple-700 dark:text-purple-300">
                                        Membership
                                    </p>
                                    <p className="mt-2 text-2xl font-bold text-purple-900 dark:text-purple-100">
                                        Aktif
                                    </p>
                                    {membership_expires_at && (
                                        <p className="mt-1 text-xs text-purple-600 dark:text-purple-400">
                                            {(() => {
                                                const expires = new Date(membership_expires_at);
                                                const now = new Date();
                                                const daysLeft = Math.ceil((expires.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));
                                                return daysLeft > 0 ? `${daysLeft} hari lagi` : 'Expired';
                                            })()}
                                        </p>
                                    )}
                                </div>
                                <div className="flex h-12 w-12 items-center justify-center rounded-lg bg-gradient-to-br from-purple-500 to-pink-500">
                                    <CrownIcon className="h-6 w-6 text-white" />
                                </div>
                            </div>
                        </Card>
                    )}
                    <Card padding="md">
                        <div className="flex items-center justify-between">
                            <div>
                                <p className="text-sm font-medium text-gray-600 dark:text-gray-400">
                                    {has_active_membership ? 'Total Show Tersedia' : 'Total Show'}
                                </p>
                                <p className="mt-2 text-2xl font-bold text-gray-900 dark:text-white">
                                    {activeShows.length}
                                </p>
                            </div>
                            <div className="flex h-12 w-12 items-center justify-center rounded-lg bg-[#d4af37]/10 dark:bg-[#b8941f]/20">
                                <FilmIcon className="h-6 w-6 text-[#d4af37] dark:text-[#b8941f]" />
                            </div>
                        </div>
                    </Card>

                    <Card padding="md">
                        <div className="flex items-center justify-between">
                            <div>
                                <p className="text-sm font-medium text-gray-600 dark:text-gray-400">
                                    Show Aktif
                                </p>
                                <p className="mt-2 text-2xl font-bold text-gray-900 dark:text-white">
                                    {activeShows.length}
                                </p>
                            </div>
                            <div className="flex h-12 w-12 items-center justify-center rounded-lg bg-green-100 dark:bg-green-900/20">
                                <CheckCircleIcon className="h-6 w-6 text-green-600 dark:text-green-400" />
                            </div>
                        </div>
                    </Card>

                    <Card padding="md">
                        <div className="flex items-center justify-between">
                            <div>
                                <p className="text-sm font-medium text-gray-600 dark:text-gray-400">
                                    Show Live
                                </p>
                                <p className="mt-2 text-2xl font-bold text-gray-900 dark:text-white">
                                    {activeShows.filter((show) => show.is_live).length}
                                </p>
                            </div>
                            <div className="flex h-12 w-12 items-center justify-center rounded-lg bg-red-100 dark:bg-red-900/20">
                                <LiveIcon className="h-6 w-6 text-red-600 dark:text-red-400" />
                            </div>
                        </div>
                    </Card>
                </div>

                {/* Shows List */}
                <div>
                    <div className="mb-4 flex items-center justify-between">
                        <h2 className="text-lg font-semibold text-gray-900 dark:text-white">
                            Show Saya
                        </h2>
                        <Link
                            href="/jadwal"
                            className="text-sm font-medium text-[#d4af37] hover:text-[#b8941f] dark:text-[#b8941f] dark:hover:text-[#9a7d15]"
                        >
                            Lihat Semua Show →
                        </Link>
                    </div>

                    {activeShows.length === 0 ? (
                        <Card padding="md">
                            <div className="text-center py-12">
                                <div className="mx-auto flex h-16 w-16 items-center justify-center rounded-full bg-gray-100 dark:bg-gray-800">
                                    <FilmIcon className="h-8 w-8 text-gray-400 dark:text-gray-500" />
                                </div>
                                <h3 className="mt-4 text-lg font-semibold text-gray-900 dark:text-white">
                                    Belum ada show
                                </h3>
                                <p className="mt-2 text-sm text-gray-500 dark:text-gray-400">
                                    {has_active_membership
                                        ? 'Belum ada show yang tersedia saat ini.'
                                        : 'Anda belum membeli show apapun. Mulai jelajahi show yang tersedia.'}
                                </p>
                                {!has_active_membership && (
                                    <div className="mt-6">
                                        <Link
                                            href="/dashboard/shows"
                                            className="inline-flex items-center rounded-md bg-[#d4af37] px-4 py-2 text-sm font-semibold text-white shadow-sm hover:bg-[#b8941f] dark:bg-[#b8941f] dark:hover:bg-[#9a7d15]"
                                        >
                                            Jelajahi Show
                                        </Link>
                                    </div>
                                )}
                            </div>
                        </Card>
                    ) : (
                        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
                            {activeShows.map((show) => (
                                <Card key={show.id} padding="none" className="overflow-hidden relative">
                                    {/* Membership Badge */}
                                    {has_active_membership && (
                                        <div className="absolute top-3 left-3 z-10">
                                            <span className="inline-flex items-center gap-1 rounded-full bg-gradient-to-r from-purple-500 to-pink-500 px-2.5 py-1 text-xs font-semibold text-white shadow-lg">
                                                <CrownIcon className="h-3 w-3" />
                                                Akses Membership
                                            </span>
                                        </div>
                                    )}
                                    {show.banner_link && (
                                        <div className="aspect-video w-full overflow-hidden bg-gray-200 dark:bg-gray-700">
                                            <img
                                                src={show.banner_link}
                                                alt={show.title}
                                                className="h-full w-full object-cover"
                                            />
                                        </div>
                                    )}
                                    <div className="p-4">
                                        <div className="flex items-start justify-between">
                                            <div className="flex-1">
                                                <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
                                                    {show.title}
                                                </h3>
                                                <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
                                                    {formatDate(show.start_time)}
                                                </p>
                                            </div>
                                            {show.is_live && (
                                                <span className="ml-2 inline-flex items-center rounded-full bg-red-100 px-2.5 py-0.5 text-xs font-medium text-red-800 dark:bg-red-900/20 dark:text-red-200">
                                                    Live
                                                </span>
                                            )}
                                        </div>

                                        {show.description && (
                                            <p className="mt-2 line-clamp-2 text-sm text-gray-600 dark:text-gray-300">
                                                {show.description}
                                            </p>
                                        )}

                                        <div className="mt-4 flex flex-col gap-2">
                                            {!has_active_membership && (
                                                <div className="flex items-center gap-2">
                                                    <span className="text-sm font-medium text-gray-900 dark:text-white">
                                                        {show.is_promo && show.promo_price
                                                            ? formatPrice(show.promo_price)
                                                            : formatPrice(show.price)}
                                                    </span>
                                                    {show.is_promo && show.promo_price && (
                                                        <span className="text-xs text-gray-500 line-through dark:text-gray-400">
                                                            {formatPrice(show.price)}
                                                        </span>
                                                    )}
                                                </div>
                                            )}
                                            <div className="flex items-center gap-2">
                                                {show.is_live && show.slug_live && !streaming_maintenance && (
                                                    <button
                                                        onClick={() => handleLiveStream(show)}
                                                        className="flex-1 rounded-md bg-red-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-red-700 dark:bg-red-700 dark:hover:bg-red-800 flex items-center justify-center gap-1"
                                                    >
                                                        <LiveIcon className="h-3 w-3" />
                                                        Tonton Live
                                                    </button>
                                                )}
                                                {show.is_live && show.slug_live && streaming_maintenance && (
                                                    <button
                                                        disabled
                                                        className="flex-1 rounded-md bg-gray-300 px-3 py-1.5 text-xs font-semibold text-gray-500 cursor-not-allowed dark:bg-gray-700 dark:text-gray-400 flex items-center justify-center gap-1"
                                                    >
                                                        <WrenchIcon className="h-3 w-3" />
                                                        Maintenance
                                                    </button>
                                                )}
                                                {has_active_membership ? (
                                                    <Link
                                                        href={show.is_live && show.slug_live ? `/live/${show.slug_live}` : `/dashboard/shows`}
                                                        className={`rounded-md bg-gradient-to-r from-purple-500 to-pink-500 px-3 py-1.5 text-xs font-semibold text-white hover:from-purple-600 hover:to-pink-600 shadow-sm ${show.is_live && show.slug_live ? 'flex-1' : 'w-full'} flex items-center justify-center gap-1`}
                                                    >
                                                        {show.is_live ? (
                                                            <>
                                                                <LiveIcon className="h-3 w-3" />
                                                                Tonton Sekarang
                                                            </>
                                                        ) : (
                                                            <>
                                                                <EyeIcon className="h-3 w-3" />
                                                                Akses Show
                                                            </>
                                                        )}
                                                    </Link>
                                                ) : (
                                                    <Link
                                                        href={`/jadwal/${show.id}`}
                                                        className={`rounded-md bg-[#d4af37] px-3 py-1.5 text-xs font-medium text-white hover:bg-[#b8941f] dark:bg-[#b8941f] dark:hover:bg-[#9a7d15] ${show.is_live && show.slug_live ? 'flex-1' : ''}`}
                                                    >
                                                        Lihat Detail
                                                    </Link>
                                                )}
                                            </div>
                                        </div>
                                    </div>
                                </Card>
                            ))}
                        </div>
                    )}
                </div>
            </div>
        </UserLayout>
    );
}

// Icons
function FilmIcon({ className }: { className?: string }) {
    return (
        <svg className={className} fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor">
            <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M15.75 10.5l4.72-4.72a.75.75 0 011.28.53v11.38a.75.75 0 01-1.28.53l-4.72-4.72M4.5 18.75h9a2.25 2.25 0 002.25-2.25v-9a2.25 2.25 0 00-2.25-2.25h-9A2.25 2.25 0 002.25 7.5v9a2.25 2.25 0 002.25 2.25z"
            />
        </svg>
    );
}

function CheckCircleIcon({ className }: { className?: string }) {
    return (
        <svg className={className} fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor">
            <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
            />
        </svg>
    );
}

function LiveIcon({ className }: { className?: string }) {
    return (
        <svg className={className} fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor">
            <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M5.25 7.5A2.25 2.25 0 017.5 5.25h9a2.25 2.25 0 012.25 2.25v9a2.25 2.25 0 01-2.25 2.25h-9a2.25 2.25 0 01-2.25-2.25v-9z"
            />
            <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M9 10.5l2.25 2.25L15 7.5"
            />
        </svg>
    );
}

function CrownIcon({ className }: { className?: string }) {
    return (
        <svg className={className} fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" d="M9.813 15.904L9 18.75l-.813-2.846a4.5 4.5 0 00-3.09-3.09L2.25 12l2.846-.813a4.5 4.5 0 003.09-3.09L9 5.25l.813 2.846a4.5 4.5 0 003.09 3.09L15.75 12l-2.846.813a4.5 4.5 0 00-3.09 3.09zM18.259 8.715L18 9.75l-.259-1.035a3.375 3.375 0 00-2.455-2.456L14.25 6l1.036-.259a3.375 3.375 0 002.455-2.456L18 2.25l.259 1.035a3.375 3.375 0 002.456 2.456L21.75 6l-1.035.259a3.375 3.375 0 00-2.456 2.456zM16.894 20.567L16.5 21.75l-.394-1.183a2.25 2.25 0 00-1.423-1.423L13.5 18.75l1.183-.394a2.25 2.25 0 001.423-1.423l.394-1.183.394 1.183a2.25 2.25 0 001.423 1.423l1.183.394-1.183.394a2.25 2.25 0 00-1.423 1.423z" />
        </svg>
    );
}

function ClockIcon({ className }: { className?: string }) {
    return (
        <svg className={className} fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" d="M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z" />
        </svg>
    );
}

function EyeIcon({ className }: { className?: string }) {
    return (
        <svg className={className} fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor">
            <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M2.036 12.322a1.012 1.012 0 010-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178z"
            />
            <path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
        </svg>
    );
}

function WrenchIcon({ className }: { className?: string }) {
    return (
        <svg className={className} fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" d="M21.75 6.75a4.5 4.5 0 01-4.884 4.484c-1.076-.091-2.264.021-3.298.75M21.75 6.75a4.5 4.5 0 00-4.5-4.5h-1.5c-1.076 0-2.264.021-3.298.75m9.072 0a4.5 4.5 0 01-3.298.75m9.072 0a4.5 4.5 0 00-3.298-.75M3.75 6.75a4.5 4.5 0 004.5 4.5h1.5c1.076 0 2.264-.021 3.298-.75M3.75 6.75a4.5 4.5 0 00-4.5-4.5h-1.5c-1.076 0-2.264.021-3.298.75m9.072 0a4.5 4.5 0 01-3.298.75m9.072 0a4.5 4.5 0 00-3.298-.75M3.75 6.75h.007v.008H3.75v-.008zm.375 0a.375.375 0 11-.75 0 .375.375 0 01.75 0z" />
        </svg>
    );
}

