import { Head, router, usePage } from '@inertiajs/react';
import { useState, useEffect, useRef } from 'react';
import AdminLayout from '@/components/Layouts/AdminLayout';
import Card from '@/components/Card/Card';
import Button from '@/components/Button/Button';
import Table, { TableBody, TableCell, TableHeader, TableHeaderCell, TableRow } from '@/components/Table/Table';
import Modal from '@/components/Modal/Modal';
import Input from '@/components/Input/Input';
import Select from '@/components/Select/Select';
import SearchInput from '@/components/SearchInput/SearchInput';
import RefreshButton from '@/components/RefreshButton/RefreshButton';
import DateTimeInput from '@/components/DateTimeInput/DateTimeInput';
import LineupEditorModal from '@/components/LineupEditorModal/LineupEditorModal';
import { Form } from '@inertiajs/react';
import { Show } from '@/types';

// Dropdown Menu Component
function DropdownMenu({
    show,
    onEditLineup,
    onClose,
    buttonId,
}: {
    show: Show;
    onEditLineup: (show: Show, type: 'lineup' | 'seitansai' | 'graduation') => void;
    onClose: () => void;
    buttonId: string;
}) {
    const dropdownRef = useRef<HTMLDivElement>(null);
    const [position, setPosition] = useState<'bottom' | 'top'>('bottom');

    useEffect(() => {
        const button = document.getElementById(buttonId);
        if (!button || !dropdownRef.current) {
            return;
        }

        const updatePosition = () => {
            const buttonRect = button.getBoundingClientRect();
            const dropdownHeight = 120; // Approximate height of dropdown
            const spaceBelow = window.innerHeight - buttonRect.bottom;
            const spaceAbove = buttonRect.top;

            // Determine position
            const newPosition = spaceBelow < dropdownHeight && spaceAbove > dropdownHeight ? 'top' : 'bottom';
            setPosition(newPosition);

            // Set position using fixed positioning
            if (dropdownRef.current) {
                if (newPosition === 'top') {
                    dropdownRef.current.style.bottom = `${window.innerHeight - buttonRect.top + 4}px`;
                    dropdownRef.current.style.top = 'auto';
                } else {
                    dropdownRef.current.style.top = `${buttonRect.bottom + 4}px`;
                    dropdownRef.current.style.bottom = 'auto';
                }
                dropdownRef.current.style.right = `${window.innerWidth - buttonRect.right}px`;
                dropdownRef.current.style.left = 'auto';
            }
        };

        updatePosition();
        window.addEventListener('scroll', updatePosition, true);
        window.addEventListener('resize', updatePosition);

        // Close on outside click
        const handleClickOutside = (event: MouseEvent) => {
            if (
                dropdownRef.current &&
                !dropdownRef.current.contains(event.target as Node) &&
                button &&
                !button.contains(event.target as Node)
            ) {
                onClose();
            }
        };

        document.addEventListener('mousedown', handleClickOutside);
        return () => {
            document.removeEventListener('mousedown', handleClickOutside);
            window.removeEventListener('scroll', updatePosition, true);
            window.removeEventListener('resize', updatePosition);
        };
    }, [buttonId, onClose]);

    return (
        <>
            <div className="fixed inset-0 z-10" onClick={onClose}></div>
            <div
                ref={dropdownRef}
                className="fixed z-20 w-48 rounded-md bg-white shadow-lg ring-1 ring-black ring-opacity-5 dark:bg-gray-800 dark:ring-gray-700"
            >
                <div className="py-1">
                    <button
                        onClick={() => {
                            onEditLineup(show, 'lineup');
                            onClose();
                        }}
                        className="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700"
                    >
                        <i className="fas fa-list mr-2"></i>
                        Edit Lineup
                    </button>
                    <button
                        onClick={() => {
                            onEditLineup(show, 'seitansai');
                            onClose();
                        }}
                        className="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700"
                    >
                        <i className="fas fa-birthday-cake mr-2"></i>
                        Edit Seitansai
                    </button>
                    <button
                        onClick={() => {
                            onEditLineup(show, 'graduation');
                            onClose();
                        }}
                        className="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700"
                    >
                        <i className="fas fa-graduation-cap mr-2"></i>
                        Edit Graduation
                    </button>
                </div>
            </div>
        </>
    );
}

interface ShowsPageProps {
    shows: Show[];
    pagination?: {
        data: Show[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
        links: Array<{ url: string | null; label: string; active: boolean }>;
    };
    filters?: {
        type?: string;
        status?: string;
        search?: string;
    };
}

export default function Index({ shows = [], pagination, filters = {} }: ShowsPageProps) {
    const { props } = usePage();
    const flash = (props as any).flash as { success?: string; error?: string; sync_result?: any; update_result?: any };
    
    const [search, setSearch] = useState(filters.search || '');
    const [typeFilter, setTypeFilter] = useState(filters.type || 'all');
    const [statusFilter, setStatusFilter] = useState(filters.status || 'all');
    const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
    const [isEditModalOpen, setIsEditModalOpen] = useState(false);
    const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
    const [isLineupModalOpen, setIsLineupModalOpen] = useState(false);
    const [isSyncModalOpen, setIsSyncModalOpen] = useState(false);
    const [isSyncResultModalOpen, setIsSyncResultModalOpen] = useState(false);
    const [isSyncing, setIsSyncing] = useState(false);
    const [syncResult, setSyncResult] = useState<any>(null);
    const [lineupType, setLineupType] = useState<'lineup' | 'seitansai' | 'graduation'>('lineup');
    const [selectedShow, setSelectedShow] = useState<Show | null>(null);
    const [openDropdownId, setOpenDropdownId] = useState<number | null>(null);
    const [startTime, setStartTime] = useState<number>(Math.floor(Date.now() / 1000));
    const [editStartTime, setEditStartTime] = useState<number>(0);

    // Handle flash message untuk sync result
    useEffect(() => {
        if (flash?.sync_result) {
            setSyncResult(flash.sync_result);
            setIsSyncResultModalOpen(true);
        }
    }, [flash]);

    const handleEdit = (show: Show) => {
        setSelectedShow(show);
        setEditStartTime(show.start_time);
        setIsEditModalOpen(true);
    };

    const handleDelete = (show: Show) => {
        setSelectedShow(show);
        setIsDeleteModalOpen(true);
    };

    const handleEditLineup = (show: Show, type: 'lineup' | 'seitansai' | 'graduation') => {
        setSelectedShow(show);
        setLineupType(type);
        setOpenDropdownId(null); // Close dropdown
        setIsLineupModalOpen(true);
    };

    const handleDeleteConfirm = () => {
        if (selectedShow) {
            router.delete(`/admin/shows/${selectedShow.id}`, {
                onSuccess: () => {
                    setIsDeleteModalOpen(false);
                    setSelectedShow(null);
                },
            });
        }
    };

    const handleSyncConfirm = () => {
        setIsSyncModalOpen(false);
        setIsSyncing(true);
        setSyncResult(null);

        router.post(
            '/admin/shows/sync-upcoming',
            {},
            {
                preserveState: true,
                preserveScroll: true,
                onSuccess: (page) => {
                    setIsSyncing(false);
                    const flash = (page.props as any).flash as any;
                    if (flash?.sync_result) {
                        setSyncResult(flash.sync_result);
                        setIsSyncResultModalOpen(true);
                    } else if (flash?.error) {
                        alert('Error: ' + flash.error);
                        router.reload();
                    } else {
                        router.reload();
                    }
                },
                onError: (errors) => {
                    setIsSyncing(false);
                    console.error('Error syncing shows:', errors);
                    const errorMessage = typeof errors === 'string' ? errors : errors?.message || 'Terjadi kesalahan saat sync';
                    alert('Error: ' + errorMessage);
                },
            }
        );
    };


    // Handle search dengan debounce
    useEffect(() => {
        const isInitialLoad =
            search === (filters.search || '') &&
            typeFilter === (filters.type || 'all') &&
            statusFilter === (filters.status || 'all');
        if (isInitialLoad) {
            return;
        }

        const timer = setTimeout(() => {
            router.get(
                '/admin/shows',
                {
                    type: typeFilter !== 'all' ? typeFilter : undefined,
                    status: statusFilter !== 'all' ? statusFilter : undefined,
                    search: search || undefined,
                },
                {
                    preserveState: true,
                    preserveScroll: true,
                    replace: true,
                }
            );
        }, 300);

        return () => clearTimeout(timer);
    }, [search, typeFilter, statusFilter]);

    const handleFilterChange = (filterType: 'type' | 'status', value: string) => {
        if (filterType === 'type') {
            setTypeFilter(value);
        } else {
            setStatusFilter(value);
        }
        router.get(
            '/admin/shows',
            {
                type: filterType === 'type' ? (value !== 'all' ? value : undefined) : typeFilter !== 'all' ? typeFilter : undefined,
                status: filterType === 'status' ? (value !== 'all' ? value : undefined) : statusFilter !== 'all' ? statusFilter : undefined,
                search: search || undefined,
            },
            {
                preserveState: true,
                preserveScroll: true,
                replace: true,
            }
        );
    };

    const handleSearchClear = () => {
        setSearch('');
    };

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

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

    const getStatusBadge = (show: Show) => {
        if (show.is_live) {
            return (
                <span className="inline-flex rounded-full bg-red-100 px-2 py-1 text-xs font-semibold text-red-800 dark:bg-red-900/30 dark:text-red-400">
                    Live
                </span>
            );
        }
        if (show.is_replay) {
            return (
                <span className="inline-flex rounded-full bg-blue-100 px-2 py-1 text-xs font-semibold text-blue-800 dark:bg-blue-900/30 dark:text-blue-400">
                    Replay
                </span>
            );
        }
        if (show.is_active) {
            return (
                <span className="inline-flex rounded-full bg-green-100 px-2 py-1 text-xs font-semibold text-green-800 dark:bg-green-900/30 dark:text-green-400">
                    Active
                </span>
            );
        }
        return (
            <span className="inline-flex rounded-full bg-gray-100 px-2 py-1 text-xs font-semibold text-gray-800 dark:bg-gray-700 dark:text-gray-300">
                Inactive
            </span>
        );
    };

    return (
        <AdminLayout title="Shows Management">
            <Head title="Shows Management" />
            <div className="space-y-6">
                {/* Header dengan tombol Create dan Refresh */}
                <div className="flex items-center justify-between">
                    <div>
                        <h2 className="text-2xl font-bold text-gray-900 dark:text-white">Shows Management</h2>
                        <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
                            Kelola semua show yang terdaftar di sistem
                        </p>
                    </div>
                    <div className="flex items-center gap-2">
                        <RefreshButton />
                        <Button
                            variant="secondary"
                            onClick={() => setIsSyncModalOpen(true)}
                            disabled={isSyncing}
                        >
                            <i className={`fas fa-plus-circle mr-2 ${isSyncing ? 'animate-spin' : ''}`}></i>
                            {isSyncing ? 'Syncing...' : 'Sync Upcoming'}
                        </Button>
                        <Button onClick={() => setIsCreateModalOpen(true)}>Tambah Show</Button>
                    </div>
                </div>

                {/* Search and Filter */}
                <Card padding="md">
                    <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
                        <div>
                            <label className="mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300">
                                Cari Show
                            </label>
                            <SearchInput
                                placeholder="Cari berdasarkan judul, showId, atau slug..."
                                value={search}
                                onChange={(e) => setSearch(e.target.value)}
                                onClear={handleSearchClear}
                            />
                        </div>
                        <div>
                            <label className="mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300">
                                Filter Tipe
                            </label>
                            <Select
                                value={typeFilter}
                                onChange={(e) => handleFilterChange('type', e.target.value)}
                                options={[
                                    { value: 'all', label: 'Semua Tipe' },
                                    { value: 'Regular', label: 'Regular' },
                                    { value: 'Special', label: 'Special' },
                                    { value: 'Graduation', label: 'Graduation' },
                                    { value: 'Seitansai', label: 'Seitansai' },
                                ]}
                            />
                        </div>
                        <div>
                            <label className="mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300">
                                Filter Status
                            </label>
                            <Select
                                value={statusFilter}
                                onChange={(e) => handleFilterChange('status', e.target.value)}
                                options={[
                                    { value: 'all', label: 'Semua Status' },
                                    { value: 'active', label: 'Active' },
                                    { value: 'inactive', label: 'Inactive' },
                                    { value: 'live', label: 'Live' },
                                    { value: 'replay', label: 'Replay' },
                                ]}
                            />
                        </div>
                    </div>
                </Card>

                {/* Table */}
                <Card padding="none">
                    <div className="overflow-x-auto">
                        <Table pagination={pagination}>
                            <TableHeader>
                                <TableHeaderCell>Show ID</TableHeaderCell>
                                <TableHeaderCell>Judul</TableHeaderCell>
                                <TableHeaderCell>Tipe</TableHeaderCell>
                                <TableHeaderCell>Harga</TableHeaderCell>
                                <TableHeaderCell>Harga Koin</TableHeaderCell>
                                <TableHeaderCell>Status</TableHeaderCell>
                                <TableHeaderCell className="text-right">Actions</TableHeaderCell>
                            </TableHeader>
                            <TableBody>
                                {!shows || shows.length === 0 ? (
                                    <TableRow>
                                        <TableCell colSpan={7} className="text-center py-8 text-gray-500 dark:text-gray-400">
                                            Tidak ada data show
                                        </TableCell>
                                    </TableRow>
                                ) : (
                                    (shows || []).map((show) => (
                                        <TableRow key={show.id}>
                                            <TableCell className="font-medium text-sm">{show.showId}</TableCell>
                                            <TableCell className="max-w-xs truncate text-sm">{show.title}</TableCell>
                                            <TableCell>
                                                <span className="inline-flex rounded-full bg-gray-100 px-2 py-1 text-xs font-semibold text-gray-800 dark:bg-gray-700 dark:text-gray-300">
                                                    {show.type}
                                                </span>
                                            </TableCell>
                                            <TableCell className="text-sm">
                                                {show.is_promo && show.promo_price ? (
                                                    <div>
                                                        <div className="text-xs text-gray-500 line-through dark:text-gray-400">
                                                            {formatPrice(show.price)}
                                                        </div>
                                                        <div className="font-semibold text-[#d4af37] dark:text-[#b8941f]">
                                                            {formatPrice(show.promo_price)}
                                                        </div>
                                                    </div>
                                                ) : (
                                                    formatPrice(show.price)
                                                )}
                                            </TableCell>
                                            <TableCell className="text-sm">
                                                {show.is_promo && show.promo_coin_price ? (
                                                    <div>
                                                        <div className="text-xs text-gray-500 line-through dark:text-gray-400">
                                                            {show.coin_price ? `${show.coin_price} Koin` : '-'}
                                                        </div>
                                                        <div className="font-semibold text-[#d4af37] dark:text-[#b8941f]">
                                                            {show.promo_coin_price} Koin
                                                        </div>
                                                    </div>
                                                ) : (
                                                    <span>{show.coin_price ? `${show.coin_price} Koin` : '-'}</span>
                                                )}
                                            </TableCell>
                                            <TableCell>{getStatusBadge(show)}</TableCell>
                                            <TableCell>
                                                <div className="flex items-center justify-end gap-1">
                                                    <div className="relative">
                                                        <button
                                                            onClick={(e) => {
                                                                e.stopPropagation();
                                                                setOpenDropdownId(openDropdownId === show.id ? null : show.id);
                                                            }}
                                                            className="rounded-md p-2 text-[#d4af37] hover:bg-[#d4af37]/10 dark:text-[#b8941f] dark:hover:bg-[#b8941f]/20 transition-colors"
                                                            title="Edit Lineup/Seitansai/Graduation"
                                                            id={`lineup-btn-${show.id}`}
                                                        >
                                                            <i className="fas fa-users"></i>
                                                        </button>
                                                        {openDropdownId === show.id && (
                                                            <DropdownMenu
                                                                show={show}
                                                                onEditLineup={handleEditLineup}
                                                                onClose={() => setOpenDropdownId(null)}
                                                                buttonId={`lineup-btn-${show.id}`}
                                                            />
                                                        )}
                                                    </div>
                                                    <button
                                                        onClick={() => handleEdit(show)}
                                                        className="rounded-md p-2 text-blue-600 hover:bg-blue-50 dark:text-blue-400 dark:hover:bg-blue-900/20 transition-colors"
                                                        title="Edit"
                                                    >
                                                        <i className="fas fa-edit"></i>
                                                    </button>
                                                    <button
                                                        onClick={() => handleDelete(show)}
                                                        className="rounded-md p-2 text-red-600 hover:bg-red-50 dark:text-red-400 dark:hover:bg-red-900/20 transition-colors"
                                                        title="Hapus"
                                                    >
                                                        <i className="fas fa-trash"></i>
                                                    </button>
                                                </div>
                                            </TableCell>
                                        </TableRow>
                                    ))
                                )}
                            </TableBody>
                        </Table>
                    </div>
                </Card>

                {/* Create Modal */}
                <Modal
                    isOpen={isCreateModalOpen}
                    onClose={() => setIsCreateModalOpen(false)}
                    title="Tambah Show Baru"
                    size="2xl"
                    footer={
                        <div className="flex justify-end gap-2">
                            <Button variant="secondary" onClick={() => setIsCreateModalOpen(false)}>
                                Batal
                            </Button>
                            <Form action="/admin/shows" method="post" id="create-show-form">
                                <Button type="submit" form="create-show-form">
                                    Simpan
                                </Button>
                            </Form>
                        </div>
                    }
                >
                    <Form
                        action="/admin/shows"
                        method="post"
                        id="create-show-form"
                        className="space-y-6"
                        onSubmit={(e) => {
                            const form = e.currentTarget;
                            const datetimeInput = form.querySelector('input[type="datetime-local"]') as HTMLInputElement;
                            if (datetimeInput && datetimeInput.value) {
                                const timestamp = Math.floor(new Date(datetimeInput.value).getTime() / 1000);
                                const hiddenInput = form.querySelector('input[type="hidden"][name="start_time"]') as HTMLInputElement;
                                if (hiddenInput) {
                                    hiddenInput.value = timestamp.toString();
                                }
                            }
                        }}
                    >
                        {/* Informasi Dasar */}
                        <div className="space-y-4">
                            <h3 className="text-base font-semibold text-gray-900 dark:text-white border-b border-gray-200 dark:border-gray-700 pb-2">
                                Informasi Dasar
                            </h3>
                            <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
                                <Input
                                    name="showId"
                                    label="Show ID"
                                    required
                                    placeholder="Masukkan Show ID"
                                />
                                <Input
                                    name="title"
                                    label="Judul"
                                    required
                                    placeholder="Masukkan judul show"
                                    className="sm:col-span-2"
                                />
                            </div>
                            <Input
                                name="description"
                                label="Deskripsi"
                                type="textarea"
                                placeholder="Masukkan deskripsi show"
                            />
                        </div>

                        {/* Waktu & Tipe */}
                        <div className="space-y-4">
                            <h3 className="text-base font-semibold text-gray-900 dark:text-white border-b border-gray-200 dark:border-gray-700 pb-2">
                                Waktu & Tipe
                            </h3>
                            <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
                                <DateTimeInput
                                    name="start_time"
                                    label="Waktu Mulai"
                                    required
                                    value={startTime}
                                    onChange={(timestamp) => {
                                        setStartTime(timestamp);
                                        // Set hidden input value
                                        const hiddenInput = document.querySelector('input[name="start_time"]') as HTMLInputElement;
                                        if (hiddenInput) {
                                            hiddenInput.value = timestamp.toString();
                                        }
                                    }}
                                />
                                <Select
                                    name="type"
                                    label="Tipe Show"
                                    required
                                    options={[
                                        { value: 'Regular', label: 'Regular' },
                                        { value: 'Special', label: 'Special' },
                                        { value: 'Graduation', label: 'Graduation' },
                                        { value: 'Seitansai', label: 'Seitansai' },
                                    ]}
                                />
                                <Select
                                    name="type_live"
                                    label="Tipe Live"
                                    required
                                    defaultValue="idn"
                                    options={[
                                        { value: 'idn', label: 'IDN' },
                                        { value: 'youtube', label: 'YouTube' },
                                        { value: 'twitch', label: 'Twitch' },
                                    ]}
                                />
                            </div>
                        </div>

                        {/* Harga & Promo */}
                        <div className="space-y-4">
                            <h3 className="text-base font-semibold text-gray-900 dark:text-white border-b border-gray-200 dark:border-gray-700 pb-2">
                                Harga & Promo
                            </h3>
                            <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
                                <Input
                                    name="price"
                                    label="Harga (Rupiah)"
                                    type="number"
                                    step="0.01"
                                    required
                                    placeholder="Masukkan harga"
                                />
                                <Input
                                    name="coin_price"
                                    label="Harga Koin"
                                    type="number"
                                    step="1"
                                    min="0"
                                    placeholder="Masukkan harga koin"
                                />
                                <Input
                                    name="banner_link"
                                    label="Link Banner"
                                    type="url"
                                    placeholder="Masukkan link banner"
                                />
                            </div>
                            <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
                                <div className="flex items-center gap-2 pt-6">
                                    <input type="hidden" name="is_promo" value="0" />
                                    <input
                                        type="checkbox"
                                        name="is_promo"
                                        id="is_promo"
                                        value="1"
                                        className="h-4 w-4 rounded border-gray-300 text-[#d4af37] focus:ring-[#d4af37] dark:border-gray-600"
                                    />
                                    <label htmlFor="is_promo" className="text-sm font-medium text-gray-700 dark:text-gray-300">
                                        Aktifkan Promo
                                    </label>
                                </div>
                                <Input
                                    name="promo_price"
                                    label="Harga Promo (Rupiah)"
                                    type="number"
                                    step="0.01"
                                    placeholder="Masukkan harga promo"
                                />
                                <Input
                                    name="promo_coin_price"
                                    label="Harga Koin Promo"
                                    type="number"
                                    step="1"
                                    min="0"
                                    placeholder="Masukkan harga koin promo"
                                />
                            </div>
                        </div>

                        {/* Status */}
                        <div className="space-y-4">
                            <h3 className="text-base font-semibold text-gray-900 dark:text-white border-b border-gray-200 dark:border-gray-700 pb-2">
                                Status
                            </h3>
                            <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
                                <div className="flex items-center gap-2 p-4 rounded-lg border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900/50">
                                    <input type="hidden" name="is_active" value="0" />
                                    <input
                                        type="checkbox"
                                        name="is_active"
                                        id="is_active"
                                        value="1"
                                        className="h-4 w-4 rounded border-gray-300 text-[#d4af37] focus:ring-[#d4af37] dark:border-gray-600"
                                    />
                                    <label htmlFor="is_active" className="text-sm font-medium text-gray-700 dark:text-gray-300">
                                        Active
                                    </label>
                                </div>
                                <div className="flex items-center gap-2 p-4 rounded-lg border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900/50">
                                    <input type="hidden" name="is_live" value="0" />
                                    <input
                                        type="checkbox"
                                        name="is_live"
                                        id="is_live"
                                        value="1"
                                        className="h-4 w-4 rounded border-gray-300 text-[#d4af37] focus:ring-[#d4af37] dark:border-gray-600"
                                    />
                                    <label htmlFor="is_live" className="text-sm font-medium text-gray-700 dark:text-gray-300">
                                        Live
                                    </label>
                                </div>
                                <div className="flex items-center gap-2 p-4 rounded-lg border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900/50">
                                    <input type="hidden" name="is_replay" value="0" />
                                    <input
                                        type="checkbox"
                                        name="is_replay"
                                        id="is_replay"
                                        value="1"
                                        className="h-4 w-4 rounded border-gray-300 text-[#d4af37] focus:ring-[#d4af37] dark:border-gray-600"
                                    />
                                    <label htmlFor="is_replay" className="text-sm font-medium text-gray-700 dark:text-gray-300">
                                        Replay
                                    </label>
                                </div>
                            </div>
                        </div>

                        {/* Live Settings */}
                        <div className="space-y-4">
                            <h3 className="text-base font-semibold text-gray-900 dark:text-white border-b border-gray-200 dark:border-gray-700 pb-2">
                                Pengaturan Live
                            </h3>
                            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                                <Input
                                    name="streamer_live"
                                    label="Streamer Live ID"
                                    required
                                    defaultValue="50a27780-93e7-4e40-8474-60f6e0cca6da"
                                    placeholder="Masukkan streamer live ID"
                                />
                                <Input
                                    name="slug_live"
                                    label="Slug Live"
                                    required
                                    placeholder="Masukkan slug live"
                                />
                            </div>
                            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                                <Input
                                    name="url_live"
                                    label="URL Live"
                                    type="url"
                                    placeholder="Masukkan URL live"
                                />
                                <Input
                                    name="url_replay"
                                    label="URL Replay"
                                    type="url"
                                    placeholder="Masukkan URL replay"
                                />
                            </div>
                        </div>
                        {/* Hidden input for start_time */}
                        <input type="hidden" name="start_time" value={startTime} />
                    </Form>
                </Modal>

                {/* Edit Modal */}
                <Modal
                    isOpen={isEditModalOpen}
                    onClose={() => {
                        setIsEditModalOpen(false);
                        setSelectedShow(null);
                    }}
                    title="Edit Show"
                    size="2xl"
                    footer={
                        <div className="flex justify-end gap-2">
                            <Button
                                variant="secondary"
                                onClick={() => {
                                    setIsEditModalOpen(false);
                                    setSelectedShow(null);
                                }}
                            >
                                Batal
                            </Button>
                            {selectedShow && (
                                <Form
                                    action={`/admin/shows/${selectedShow.id}`}
                                    method="post"
                                    id="edit-show-form"
                                >
                                    <input type="hidden" name="_method" value="put" />
                                    <Button type="submit" form="edit-show-form">
                                        Update
                                    </Button>
                                </Form>
                            )}
                        </div>
                    }
                >
                    {selectedShow && (
                        <Form
                            action={`/admin/shows/${selectedShow.id}`}
                            method="post"
                            id="edit-show-form"
                            className="space-y-6"
                            onSubmit={(e) => {
                                const form = e.currentTarget;
                                const datetimeInput = form.querySelector('input[type="datetime-local"]') as HTMLInputElement;
                                if (datetimeInput && datetimeInput.value) {
                                    const timestamp = Math.floor(new Date(datetimeInput.value).getTime() / 1000);
                                    const hiddenInput = form.querySelector('input[type="hidden"][name="start_time"]') as HTMLInputElement;
                                    if (hiddenInput) {
                                        hiddenInput.value = timestamp.toString();
                                    }
                                }
                            }}
                        >
                            <input type="hidden" name="_method" value="put" />
                            
                            {/* Informasi Dasar */}
                            <div className="space-y-4">
                                <h3 className="text-base font-semibold text-gray-900 dark:text-white border-b border-gray-200 dark:border-gray-700 pb-2">
                                    Informasi Dasar
                                </h3>
                                <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
                                    <Input
                                        name="showId"
                                        label="Show ID"
                                        required
                                        defaultValue={selectedShow.showId}
                                        placeholder="Masukkan Show ID"
                                    />
                                    <Input
                                        name="title"
                                        label="Judul"
                                        required
                                        defaultValue={selectedShow.title}
                                        placeholder="Masukkan judul show"
                                        className="sm:col-span-2"
                                    />
                                </div>
                                <Input
                                    name="description"
                                    label="Deskripsi"
                                    type="textarea"
                                    defaultValue={selectedShow.description || ''}
                                    placeholder="Masukkan deskripsi show"
                                />
                            </div>

                            {/* Waktu & Tipe */}
                            <div className="space-y-4">
                                <h3 className="text-base font-semibold text-gray-900 dark:text-white border-b border-gray-200 dark:border-gray-700 pb-2">
                                    Waktu & Tipe
                                </h3>
                                <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
                                    <DateTimeInput
                                        name="start_time"
                                        label="Waktu Mulai"
                                        required
                                        value={editStartTime}
                                        onChange={(timestamp) => {
                                            setEditStartTime(timestamp);
                                            // Set hidden input value
                                            const hiddenInput = document.querySelector('#edit-show-form input[name="start_time"]') as HTMLInputElement;
                                            if (hiddenInput) {
                                                hiddenInput.value = timestamp.toString();
                                            }
                                        }}
                                    />
                                    <Select
                                        name="type"
                                        label="Tipe Show"
                                        required
                                        defaultValue={selectedShow.type}
                                        options={[
                                            { value: 'Regular', label: 'Regular' },
                                            { value: 'Special', label: 'Special' },
                                            { value: 'Graduation', label: 'Graduation' },
                                            { value: 'Seitansai', label: 'Seitansai' },
                                        ]}
                                    />
                                    <Select
                                        name="type_live"
                                        label="Tipe Live"
                                        required
                                        defaultValue={selectedShow.type_live}
                                        options={[
                                            { value: 'idn', label: 'IDN' },
                                            { value: 'youtube', label: 'YouTube' },
                                            { value: 'twitch', label: 'Twitch' },
                                        ]}
                                    />
                                </div>
                            </div>

                            {/* Harga & Promo */}
                            <div className="space-y-4">
                                <h3 className="text-base font-semibold text-gray-900 dark:text-white border-b border-gray-200 dark:border-gray-700 pb-2">
                                    Harga & Promo
                                </h3>
                                <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
                                    <Input
                                        name="price"
                                        label="Harga (Rupiah)"
                                        type="number"
                                        step="0.01"
                                        required
                                        defaultValue={selectedShow.price}
                                        placeholder="Masukkan harga"
                                    />
                                    <Input
                                        name="coin_price"
                                        label="Harga Koin"
                                        type="number"
                                        step="1"
                                        min="0"
                                        defaultValue={selectedShow.coin_price || ''}
                                        placeholder="Masukkan harga koin"
                                    />
                                    <Input
                                        name="banner_link"
                                        label="Link Banner"
                                        type="url"
                                        defaultValue={selectedShow.banner_link || ''}
                                        placeholder="Masukkan link banner"
                                    />
                                </div>
                                <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
                                    <div className="flex items-center gap-2 pt-6">
                                        <input type="hidden" name="is_promo" value="0" />
                                        <input
                                            type="checkbox"
                                            name="is_promo"
                                            id="edit_is_promo"
                                            value="1"
                                            defaultChecked={selectedShow.is_promo}
                                            className="h-4 w-4 rounded border-gray-300 text-[#d4af37] focus:ring-[#d4af37] dark:border-gray-600"
                                        />
                                        <label htmlFor="edit_is_promo" className="text-sm font-medium text-gray-700 dark:text-gray-300">
                                            Aktifkan Promo
                                        </label>
                                    </div>
                                    <Input
                                        name="promo_price"
                                        label="Harga Promo (Rupiah)"
                                        type="number"
                                        step="0.01"
                                        defaultValue={selectedShow.promo_price || ''}
                                        placeholder="Masukkan harga promo"
                                    />
                                    <Input
                                        name="promo_coin_price"
                                        label="Harga Koin Promo"
                                        type="number"
                                        step="1"
                                        min="0"
                                        defaultValue={selectedShow.promo_coin_price || ''}
                                        placeholder="Masukkan harga koin promo"
                                    />
                                </div>
                            </div>

                            {/* Status */}
                            <div className="space-y-4">
                                <h3 className="text-base font-semibold text-gray-900 dark:text-white border-b border-gray-200 dark:border-gray-700 pb-2">
                                    Status
                                </h3>
                                <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
                                    <div className="flex items-center gap-2 p-4 rounded-lg border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900/50">
                                        <input type="hidden" name="is_active" value="0" />
                                        <input
                                            type="checkbox"
                                            name="is_active"
                                            id="edit_is_active"
                                            value="1"
                                            defaultChecked={selectedShow.is_active}
                                            className="h-4 w-4 rounded border-gray-300 text-[#d4af37] focus:ring-[#d4af37] dark:border-gray-600"
                                        />
                                        <label htmlFor="edit_is_active" className="text-sm font-medium text-gray-700 dark:text-gray-300">
                                            Active
                                        </label>
                                    </div>
                                    <div className="flex items-center gap-2 p-4 rounded-lg border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900/50">
                                        <input type="hidden" name="is_live" value="0" />
                                        <input
                                            type="checkbox"
                                            name="is_live"
                                            id="edit_is_live"
                                            value="1"
                                            defaultChecked={selectedShow.is_live}
                                            className="h-4 w-4 rounded border-gray-300 text-[#d4af37] focus:ring-[#d4af37] dark:border-gray-600"
                                        />
                                        <label htmlFor="edit_is_live" className="text-sm font-medium text-gray-700 dark:text-gray-300">
                                            Live
                                        </label>
                                    </div>
                                    <div className="flex items-center gap-2 p-4 rounded-lg border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900/50">
                                        <input type="hidden" name="is_replay" value="0" />
                                        <input
                                            type="checkbox"
                                            name="is_replay"
                                            id="edit_is_replay"
                                            value="1"
                                            defaultChecked={selectedShow.is_replay}
                                            className="h-4 w-4 rounded border-gray-300 text-[#d4af37] focus:ring-[#d4af37] dark:border-gray-600"
                                        />
                                        <label htmlFor="edit_is_replay" className="text-sm font-medium text-gray-700 dark:text-gray-300">
                                            Replay
                                        </label>
                                    </div>
                                </div>
                            </div>

                            {/* Live Settings */}
                            <div className="space-y-4">
                                <h3 className="text-base font-semibold text-gray-900 dark:text-white border-b border-gray-200 dark:border-gray-700 pb-2">
                                    Pengaturan Live
                                </h3>
                                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                                    <Input
                                        name="streamer_live"
                                        label="Streamer Live ID"
                                        required
                                        defaultValue={selectedShow.streamer_live}
                                        placeholder="Masukkan streamer live ID"
                                    />
                                    <Input
                                        name="slug_live"
                                        label="Slug Live"
                                        required
                                        defaultValue={selectedShow.slug_live}
                                        placeholder="Masukkan slug live"
                                    />
                                </div>
                                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                                    <Input
                                        name="url_live"
                                        label="URL Live"
                                        type="url"
                                        defaultValue={selectedShow.url_live || ''}
                                        placeholder="Masukkan URL live"
                                    />
                                    <Input
                                        name="url_replay"
                                        label="URL Replay"
                                        type="url"
                                        defaultValue={selectedShow.url_replay || ''}
                                        placeholder="Masukkan URL replay"
                                    />
                                </div>
                            </div>
                            {/* Hidden input for start_time */}
                            <input type="hidden" name="start_time" value={editStartTime} />
                        </Form>
                    )}
                </Modal>

                {/* Delete Confirmation Modal */}
                <Modal
                    isOpen={isDeleteModalOpen}
                    onClose={() => {
                        setIsDeleteModalOpen(false);
                        setSelectedShow(null);
                    }}
                    title="Hapus Show"
                    size="sm"
                    footer={
                        <div className="flex justify-end gap-2">
                            <Button
                                variant="secondary"
                                onClick={() => {
                                    setIsDeleteModalOpen(false);
                                    setSelectedShow(null);
                                }}
                            >
                                Batal
                            </Button>
                            <Button variant="danger" onClick={handleDeleteConfirm}>
                                Hapus
                            </Button>
                        </div>
                    }
                >
                    <p className="text-sm text-gray-600 dark:text-gray-400">
                        Apakah Anda yakin ingin menghapus show{' '}
                        <span className="font-semibold text-gray-900 dark:text-white">
                            {selectedShow?.title}
                        </span>
                        ? Tindakan ini tidak dapat dibatalkan.
                    </p>
                </Modal>

                {/* Lineup Editor Modal */}
                {selectedShow && (
                    <LineupEditorModal
                        isOpen={isLineupModalOpen}
                        onClose={() => {
                            setIsLineupModalOpen(false);
                            setSelectedShow(null);
                        }}
                        show={selectedShow}
                        type={lineupType}
                    />
                )}

                {/* Sync Confirmation Modal */}
                <Modal
                    isOpen={isSyncModalOpen}
                    onClose={() => setIsSyncModalOpen(false)}
                    title="Sync Upcoming Shows"
                    size="md"
                    footer={
                        <div className="flex justify-end gap-2">
                            <Button variant="secondary" onClick={() => setIsSyncModalOpen(false)}>
                                Batal
                            </Button>
                            <Button onClick={handleSyncConfirm}>
                                <i className="fas fa-sync-alt mr-2"></i>
                                Ya, Sync Sekarang
                            </Button>
                        </div>
                    }
                >
                    <div className="space-y-4">
                        <p className="text-sm text-gray-600 dark:text-gray-400">
                            Apakah Anda yakin ingin melakukan sync upcoming shows dari external API?
                        </p>
                        <div className="rounded-lg bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 p-4">
                            <p className="text-sm text-blue-800 dark:text-blue-300">
                                <i className="fas fa-info-circle mr-2"></i>
                                Proses ini akan mengambil data upcoming shows dari external API dan menambahkannya ke database jika belum ada.
                            </p>
                        </div>
                        <div className="rounded-lg bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 p-4">
                            <p className="text-sm text-green-800 dark:text-green-300">
                                <i className="fas fa-coins mr-2"></i>
                                <strong>Konversi Harga:</strong> Harga rupiah akan otomatis dikonversi menjadi harga koin dengan rate <strong>1 koin = Rp 1.000</strong> (contoh: Rp 15.000 = 15 koin).
                            </p>
                        </div>
                    </div>
                </Modal>

                {/* Sync Result Modal */}
                <Modal
                    isOpen={isSyncResultModalOpen}
                    onClose={() => {
                        setIsSyncResultModalOpen(false);
                        setSyncResult(null);
                        router.reload();
                    }}
                    title="Hasil Sync Upcoming Shows"
                    size="lg"
                    footer={
                        <div className="flex justify-end gap-2">
                            <Button
                                onClick={() => {
                                    setIsSyncResultModalOpen(false);
                                    setSyncResult(null);
                                    router.reload();
                                }}
                            >
                                Tutup
                            </Button>
                        </div>
                    }
                >
                    {syncResult && (
                        <div className="space-y-4">
                            <div className="grid grid-cols-3 gap-4">
                                <div className="rounded-lg bg-gray-50 dark:bg-gray-800 p-4 text-center">
                                    <div className="text-2xl font-bold text-gray-900 dark:text-white">
                                        {syncResult.total || 0}
                                    </div>
                                    <div className="text-sm text-gray-600 dark:text-gray-400 mt-1">Total</div>
                                </div>
                                <div className="rounded-lg bg-green-50 dark:bg-green-900/20 p-4 text-center">
                                    <div className="text-2xl font-bold text-green-600 dark:text-green-400">
                                        {syncResult.created || 0}
                                    </div>
                                    <div className="text-sm text-gray-600 dark:text-gray-400 mt-1">Created</div>
                                </div>
                                <div className="rounded-lg bg-yellow-50 dark:bg-yellow-900/20 p-4 text-center">
                                    <div className="text-2xl font-bold text-yellow-600 dark:text-yellow-400">
                                        {syncResult.skipped || 0}
                                    </div>
                                    <div className="text-sm text-gray-600 dark:text-gray-400 mt-1">Skipped</div>
                                </div>
                            </div>

                            {syncResult.results && Array.isArray(syncResult.results) && syncResult.results.length > 0 && (
                                <div>
                                    <h4 className="text-sm font-semibold text-gray-900 dark:text-white mb-2">
                                        Detail Hasil:
                                    </h4>
                                    <div className="max-h-64 overflow-y-auto rounded-lg border border-gray-200 dark:border-gray-700">
                                        <table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                                            <thead className="bg-gray-50 dark:bg-gray-800">
                                                <tr>
                                                    <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">
                                                        Show ID
                                                    </th>
                                                    <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">
                                                        Status
                                                    </th>
                                                    <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">
                                                        Info
                                                    </th>
                                                </tr>
                                            </thead>
                                            <tbody className="bg-white dark:bg-gray-900 divide-y divide-gray-200 dark:divide-gray-700">
                                                {syncResult.results.slice(0, 20).map((result: any, index: number) => (
                                                    <tr key={index}>
                                                        <td className="px-4 py-2 text-sm text-gray-900 dark:text-white">
                                                            {result.showId || '-'}
                                                        </td>
                                                        <td className="px-4 py-2 text-sm">
                                                            {result.status === 'created' ? (
                                                                <span className="inline-flex rounded-full bg-green-100 px-2 py-1 text-xs font-semibold text-green-800 dark:bg-green-900/30 dark:text-green-400">
                                                                    Created
                                                                </span>
                                                            ) : result.status === 'skipped' ? (
                                                                <span className="inline-flex rounded-full bg-yellow-100 px-2 py-1 text-xs font-semibold text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400">
                                                                    Skipped
                                                                </span>
                                                            ) : (
                                                                <span className="inline-flex rounded-full bg-red-100 px-2 py-1 text-xs font-semibold text-red-800 dark:bg-red-900/30 dark:text-red-400">
                                                                    Error
                                                                </span>
                                                            )}
                                                        </td>
                                                        <td className="px-4 py-2 text-sm text-gray-600 dark:text-gray-400">
                                                            {result.title || result.reason || '-'}
                                                        </td>
                                                    </tr>
                                                ))}
                                            </tbody>
                                        </table>
                                        {syncResult.results.length > 20 && (
                                            <div className="px-4 py-2 text-xs text-gray-500 dark:text-gray-400 text-center bg-gray-50 dark:bg-gray-800">
                                                ... dan {syncResult.results.length - 20} hasil lainnya
                                            </div>
                                        )}
                                    </div>
                                </div>
                            )}
                        </div>
                    )}
                </Modal>

            </div>
        </AdminLayout>
    );
}

