import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Separator } from '@/components/ui/separator';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { ClassIcon } from '@/components/game/class-icon';
import FrontendLayout from '@/layouts/frontend/layout';
import { route } from '@/lib/route-helper';
import { type BreadcrumbItem } from '@/types';
import { Head, router, useForm } from '@inertiajs/react';
import axios from 'axios';
import {
    ArrowRight,
    Ban,
    CheckCircle2,
    Clock,
    Coins,
    ExternalLink,
    FileText,
    Hash,
    History,
    Image as ImageIcon,
    Link as LinkIcon,
    MessageSquare,
    Trash2,
    Upload,
    User,
    XCircle,
} from 'lucide-react';
import { useEffect, useRef, useState } from 'react';

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

interface User {
    id: number;
    name: string;
    truename: string;
}

interface ExistingRequest {
    id: number;
    status: 'pending' | 'approved' | 'rejected';
    code: string;
    discord_id: string;
    channel_link: string;
    character_id: number;
    requested_at: string;
    processed_at: string | null;
}

interface StreamerUpload {
    id: number;
    image_url: string;
    status: 'pending' | 'approved' | 'rejected';
    gold_reward: number | null;
    admin_notes: string | null;
    created_at: string;
    approved_at: string | null;
}

interface StreamerCodeUsage {
    code: string;
    total_usage: number;
}

interface StreamerCodeUsageHistory {
    id: string;
    gateway: string;
    reference: string | null;
    character_id: number | null;
    character_name: string;
    character_class: number;
    amount: number;
    gold_amount: number;
    payment_method: string | null;
    paid_at: string | null;
    created_at: string;
}

interface Props {
    user: User;
    characters: Character[];
    existingRequest: ExistingRequest | null;
    registrationOpen: boolean;
    streamerCodeUsage: StreamerCodeUsage | null;
    streamerCodeUsageHistory: StreamerCodeUsageHistory[];
}

const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Dashboard', href: '/dashboard' },
    { title: 'Streamer Registration', href: '/dashboard/regist-streamer' },
];

export default function StreamerRegistration({
    user,
    characters: _characters,
    existingRequest,
    registrationOpen,
    streamerCodeUsage,
    streamerCodeUsageHistory,
}: Props) {
    const {
        data,
        setData,
        post: _post,
        processing,
        errors,
    } = useForm({
        discord_id: '',
        code: '',
        channel_link: '',
    });

    const [uploads, setUploads] = useState<StreamerUpload[]>([]);
    const [uploadLoading, setUploadLoading] = useState(false);
    const [selectedImage, setSelectedImage] = useState<File | null>(null);
    const [imagePreview, setImagePreview] = useState<string | null>(null);
    const fileInputRef = useRef<HTMLInputElement>(null);

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        router.post(route('dashboard.regist-streamer.store'), data, {
            preserveScroll: true,
        });
    };

    const getStatusBadge = (status: string) => {
        switch (status) {
            case 'approved':
                return (
                    <Badge className="bg-green-600 hover:bg-green-700">
                        <CheckCircle2 className="mr-1 h-3 w-3" />
                        Approved
                    </Badge>
                );
            case 'rejected':
                return (
                    <Badge variant="destructive">
                        <XCircle className="mr-1 h-3 w-3" />
                        Rejected
                    </Badge>
                );
            case 'pending':
                return (
                    <Badge variant="outline">
                        <Clock className="mr-1 h-3 w-3" />
                        Pending Review
                    </Badge>
                );
            default:
                return null;
        }
    };

    // Fetch uploads for approved streamers
    useEffect(() => {
        if (existingRequest?.status === 'approved') {
            fetchUploads();
        }
    }, [existingRequest]);

    const fetchUploads = async () => {
        try {
            const response = await axios.get(route('dashboard.regist-streamer.uploads'));
            setUploads(response.data.uploads || []);
        } catch (error) {
            console.error('Failed to fetch uploads:', error);
        }
    };

    const handleImageSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (file) {
            setSelectedImage(file);
            const reader = new FileReader();
            reader.onloadend = () => {
                setImagePreview(reader.result as string);
            };
            reader.readAsDataURL(file);
        }
    };

    const handleUpload = async () => {
        if (!selectedImage) return;

        setUploadLoading(true);
        const formData = new FormData();
        formData.append('image', selectedImage);

        try {
            const token = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');

            await axios.post(route('dashboard.regist-streamer.upload'), formData, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                    'X-CSRF-TOKEN': token || '',
                },
            });

            setSelectedImage(null);
            setImagePreview(null);
            if (fileInputRef.current) {
                fileInputRef.current.value = '';
            }

            await fetchUploads();
            router.reload({ only: ['flash'] });
        } catch (error: any) {
            console.error('Upload failed:', error);
            alert(error.response?.data?.message || error.message || 'Upload failed');
        } finally {
            setUploadLoading(false);
        }
    };

    const handleDeleteUpload = async (uploadId: number) => {
        if (!confirm('Are you sure you want to delete this upload?')) return;

        try {
            await axios.delete(route('dashboard.regist-streamer.uploads.delete', uploadId));
            await fetchUploads();
            router.reload({ only: ['flash'] });
        } catch (error: any) {
            console.error('Delete failed:', error);
            alert(error.response?.data?.message || 'Delete failed');
        }
    };

    const totalGoldEarned = uploads.filter((u) => u.status === 'approved' && u.gold_reward).reduce((sum, u) => sum + (u.gold_reward || 0), 0);

    const pendingCount = uploads.filter((u) => u.status === 'pending').length;

    const hasUploadedToday = uploads.some((upload) => {
        const uploadDate = new Date(upload.created_at);
        const today = new Date();
        return uploadDate.toDateString() === today.toDateString();
    });

    const getNextUploadTime = () => {
        const tomorrow = new Date();
        tomorrow.setDate(tomorrow.getDate() + 1);
        tomorrow.setHours(0, 0, 0, 0);
        return tomorrow;
    };

    const formatDateTime = (dateString: string | null) => {
        if (!dateString) return '-';

        return new Date(dateString).toLocaleString('en-US', {
            year: 'numeric',
            month: 'short',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit',
        });
    };

    const isApproved = existingRequest?.status === 'approved';

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

            <div className="space-y-6">
                {/* Header */}
                <div>
                    <h2 className="text-xl font-bold tracking-tight">Streamer Registration</h2>
                    <p className="text-muted-foreground text-sm">Join our creator program to earn rewards and grow your community.</p>
                </div>

                {/* Tabs */}
                <Tabs defaultValue="registration" className="w-full">
                    <TabsList className={`grid w-full ${isApproved ? 'grid-cols-3' : 'grid-cols-1'}`}>
                        <TabsTrigger value="registration" className="flex items-center gap-2">
                            {isApproved ? <History className="h-4 w-4" /> : <FileText className="h-4 w-4" />}
                            {isApproved ? 'Top Up History' : 'Registration'}
                        </TabsTrigger>
                        {isApproved && (
                            <>
                                <TabsTrigger value="upload" className="flex items-center gap-2">
                                    <Upload className="h-4 w-4" />
                                    Result Live
                                </TabsTrigger>
                                <TabsTrigger value="history" className="flex items-center gap-2">
                                    <History className="h-4 w-4" />
                                    Upload History
                                </TabsTrigger>
                            </>
                        )}
                    </TabsList>

                    {/* Registration Tab */}
                    <TabsContent value="registration" className="mt-6">
                        {existingRequest ? (
                            <div className="space-y-6">
                                {isApproved ? (
                                    <Card>
                                        <CardHeader>
                                            <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                                                <div>
                                                    <CardTitle className="flex items-center gap-2">
                                                        <History className="h-5 w-5" />
                                                        Top Up History
                                                    </CardTitle>
                                                    <CardDescription>
                                                        Characters who topped up using streamer code{' '}
                                                        <code className="bg-muted text-foreground relative rounded px-[0.4rem] py-[0.2rem] font-mono text-xs font-bold">
                                                            {streamerCodeUsage?.code ?? existingRequest.code}
                                                        </code>
                                                    </CardDescription>
                                                </div>
                                                <Badge variant="outline" className="w-fit">
                                                    Total Usage:{' '}
                                                    {(streamerCodeUsage?.total_usage ?? streamerCodeUsageHistory.length).toLocaleString()}
                                                </Badge>
                                            </div>
                                        </CardHeader>
                                        <CardContent>
                                            {streamerCodeUsageHistory.length === 0 ? (
                                                <div className="text-muted-foreground py-8 text-center">
                                                    No successful top ups have used this streamer code yet.
                                                </div>
                                            ) : (
                                                <div className="overflow-x-auto">
                                                    <Table>
                                                        <TableHeader>
                                                            <TableRow>
                                                                <TableHead>Character</TableHead>
                                                                <TableHead>Payment</TableHead>
                                                                <TableHead className="text-right">Gold</TableHead>
                                                                <TableHead>Method</TableHead>
                                                                <TableHead>Date Time</TableHead>
                                                            </TableRow>
                                                        </TableHeader>
                                                        <TableBody>
                                                            {streamerCodeUsageHistory.map((history) => (
                                                                <TableRow key={history.id}>
                                                                    <TableCell>
                                                                        <div className="flex items-center gap-2">
                                                                            <ClassIcon classId={history.character_class} size="sm" />
                                                                            <span className="font-medium">{history.character_name}</span>
                                                                        </div>
                                                                    </TableCell>
                                                                    <TableCell>{history.gateway}</TableCell>
                                                                    <TableCell className="text-right font-medium">
                                                                        {history.gold_amount.toLocaleString()}
                                                                    </TableCell>
                                                                    <TableCell>{history.payment_method || '-'}</TableCell>
                                                                    <TableCell className="whitespace-nowrap">
                                                                        {formatDateTime(history.paid_at || history.created_at)}
                                                                    </TableCell>
                                                                </TableRow>
                                                            ))}
                                                        </TableBody>
                                                    </Table>
                                                </div>
                                            )}
                                        </CardContent>
                                    </Card>
                                ) : (
                                    <>
                                        {/* Status Alert */}
                                        {existingRequest.status === 'rejected' && (
                                            <Alert variant="destructive">
                                                <XCircle className="h-4 w-4" />
                                                <AlertTitle>Application Rejected</AlertTitle>
                                                <AlertDescription>
                                                    Your application was not approved. Please contact support for more details.
                                                </AlertDescription>
                                            </Alert>
                                        )}

                                        {existingRequest.status === 'pending' && (
                                            <Alert>
                                                <Clock className="h-4 w-4" />
                                                <AlertTitle>Under Review</AlertTitle>
                                                <AlertDescription>Your application is currently being reviewed by our team.</AlertDescription>
                                            </Alert>
                                        )}

                                        {/* Application Details Card */}
                                        <Card>
                                            <CardHeader className="pb-3">
                                                <div className="flex items-center justify-between">
                                                    <div>
                                                        <CardTitle>Application Status</CardTitle>
                                                        <CardDescription>
                                                            Submitted on {new Date(existingRequest.requested_at).toLocaleDateString()}
                                                        </CardDescription>
                                                    </div>
                                                    {getStatusBadge(existingRequest.status)}
                                                </div>
                                            </CardHeader>
                                            <CardContent className="grid gap-6 pt-2">
                                                {/* Profile Info */}
                                                <div className="grid gap-1">
                                                    <h3 className="flex items-center gap-2 leading-none font-semibold tracking-tight">
                                                        <User className="text-muted-foreground h-4 w-4" />
                                                        Profile Information
                                                    </h3>
                                                    <Separator className="my-2" />
                                                    <div className="grid gap-4 sm:grid-cols-2">
                                                        <div className="space-y-1">
                                                            <span className="text-muted-foreground text-sm">Full Name</span>
                                                            <p className="font-medium">{user.truename}</p>
                                                        </div>
                                                    </div>
                                                </div>

                                                {/* Referral Info */}
                                                <div className="grid gap-1">
                                                    <h3 className="flex items-center gap-2 leading-none font-semibold tracking-tight">
                                                        <Hash className="text-muted-foreground h-4 w-4" />
                                                        Referral Details
                                                    </h3>
                                                    <Separator className="my-2" />
                                                    <div className="grid gap-4 sm:grid-cols-2">
                                                        <div className="space-y-1">
                                                            <span className="text-muted-foreground text-sm">Referral Code</span>
                                                            <div className="flex items-center gap-2">
                                                                <code className="bg-muted text-foreground relative rounded px-[0.5rem] py-[0.3rem] font-mono text-base font-bold">
                                                                    {existingRequest.code}
                                                                </code>
                                                            </div>
                                                        </div>
                                                        <div className="space-y-1">
                                                            <span className="text-muted-foreground text-sm">Discord ID</span>
                                                            <p className="font-medium">{existingRequest.discord_id}</p>
                                                        </div>
                                                    </div>
                                                </div>

                                                {/* Channel Info */}
                                                <div className="grid gap-1">
                                                    <h3 className="flex items-center gap-2 leading-none font-semibold tracking-tight">
                                                        <LinkIcon className="text-muted-foreground h-4 w-4" />
                                                        Channel
                                                    </h3>
                                                    <Separator className="my-2" />
                                                    <div className="space-y-1">
                                                        <span className="text-muted-foreground text-sm">Channel Link</span>
                                                        <div className="flex">
                                                            <a
                                                                href={existingRequest.channel_link}
                                                                target="_blank"
                                                                rel="noopener noreferrer"
                                                                className="text-primary flex items-center gap-2 text-sm hover:underline"
                                                            >
                                                                {existingRequest.channel_link}
                                                                <ExternalLink className="h-3 w-3" />
                                                            </a>
                                                        </div>
                                                    </div>
                                                </div>

                                                {/* Statistics for approved streamers */}
                                                {isApproved && (
                                                    <div className="grid gap-1">
                                                        <h3 className="flex items-center gap-2 leading-none font-semibold tracking-tight">
                                                            <Coins className="text-muted-foreground h-4 w-4" />
                                                            Statistics
                                                        </h3>
                                                        <Separator className="my-2" />
                                                        <div className="grid gap-4 sm:grid-cols-3">
                                                            <div className="space-y-1">
                                                                <span className="text-muted-foreground text-sm">Total Uploads</span>
                                                                <p className="text-2xl font-bold">{uploads.length}</p>
                                                            </div>
                                                            <div className="space-y-1">
                                                                <span className="text-muted-foreground text-sm">Pending Approval</span>
                                                                <p className="text-2xl font-bold">{pendingCount}</p>
                                                            </div>
                                                            <div className="space-y-1">
                                                                <span className="text-muted-foreground text-sm">Total Gold Earned</span>
                                                                <p className="text-2xl font-bold">{totalGoldEarned.toLocaleString()}</p>
                                                            </div>
                                                        </div>
                                                    </div>
                                                )}
                                            </CardContent>
                                        </Card>

                                        {streamerCodeUsage && (
                                            <Card>
                                                <CardHeader>
                                                    <CardTitle>Streamer Code Usage</CardTitle>
                                                    <CardDescription>Total successful top up transactions using your streamer code.</CardDescription>
                                                </CardHeader>
                                                <CardContent>
                                                    <div className="overflow-x-auto">
                                                        <Table>
                                                            <TableHeader>
                                                                <TableRow>
                                                                    <TableHead>Streamer Code</TableHead>
                                                                    <TableHead className="text-right">Total Usage</TableHead>
                                                                </TableRow>
                                                            </TableHeader>
                                                            <TableBody>
                                                                <TableRow>
                                                                    <TableCell>
                                                                        <code className="bg-muted text-foreground relative rounded px-[0.5rem] py-[0.3rem] font-mono text-sm font-bold">
                                                                            {streamerCodeUsage.code}
                                                                        </code>
                                                                    </TableCell>
                                                                    <TableCell className="text-right text-lg font-bold">
                                                                        {streamerCodeUsage.total_usage.toLocaleString()}
                                                                    </TableCell>
                                                                </TableRow>
                                                            </TableBody>
                                                        </Table>
                                                    </div>
                                                </CardContent>
                                            </Card>
                                        )}
                                    </>
                                )}
                            </div>
                        ) : !registrationOpen ? (
                            <Card>
                                <CardHeader>
                                    <CardTitle className="flex items-center gap-2">
                                        <Ban className="h-5 w-5" />
                                        Registration Closed
                                    </CardTitle>
                                    <CardDescription>Streamer registration is currently closed</CardDescription>
                                </CardHeader>
                                <CardContent>
                                    <Alert>
                                        <Ban className="h-4 w-4" />
                                        <AlertTitle>Registration Temporarily Unavailable</AlertTitle>
                                        <AlertDescription>
                                            New streamer applications are not being accepted at this time. Please check back later or contact support
                                            for more information.
                                        </AlertDescription>
                                    </Alert>
                                </CardContent>
                            </Card>
                        ) : (
                            <Card>
                                <CardHeader>
                                    <CardTitle>Submit Application</CardTitle>
                                    <CardDescription>Fill out the form below to become an official streamer.</CardDescription>
                                </CardHeader>
                                <CardContent>
                                    <form onSubmit={handleSubmit} className="space-y-8">
                                        <div className="grid gap-6">
                                            {/* Personal Info Group */}
                                            <div className="space-y-4">
                                                <h3 className="text-muted-foreground text-sm font-medium tracking-wider uppercase">Identity</h3>
                                                <div className="grid gap-4 sm:grid-cols-2">
                                                    <div className="space-y-2">
                                                        <Label htmlFor="truename">Full Name</Label>
                                                        <Input id="truename" value={user.truename} disabled className="bg-muted" />
                                                    </div>
                                                </div>
                                            </div>

                                            <Separator />

                                            {/* Contact & Code Group */}
                                            <div className="space-y-4">
                                                <h3 className="text-muted-foreground text-sm font-medium tracking-wider uppercase">
                                                    Program Details
                                                </h3>
                                                <div className="grid gap-4 sm:grid-cols-2">
                                                    <div className="space-y-2">
                                                        <Label htmlFor="discord_id">
                                                            Discord Username <span className="text-destructive">*</span>
                                                        </Label>
                                                        <div className="relative">
                                                            <MessageSquare className="text-muted-foreground absolute top-2.5 left-3 h-4 w-4" />
                                                            <Input
                                                                id="discord_id"
                                                                placeholder="username#0000"
                                                                value={data.discord_id}
                                                                onChange={(e) => setData('discord_id', e.target.value)}
                                                                className={`pl-9 ${errors.discord_id ? 'border-destructive' : ''}`}
                                                            />
                                                        </div>
                                                        {errors.discord_id && <p className="text-destructive text-sm">{errors.discord_id}</p>}
                                                    </div>
                                                    <div className="space-y-2">
                                                        <Label htmlFor="code">
                                                            Desired Referral Code <span className="text-destructive">*</span>
                                                        </Label>
                                                        <div className="relative">
                                                            <Hash className="text-muted-foreground absolute top-2.5 left-3 h-4 w-4" />
                                                            <Input
                                                                id="code"
                                                                placeholder="MYCODE"
                                                                value={data.code}
                                                                onChange={(e) => setData('code', e.target.value.toUpperCase())}
                                                                maxLength={50}
                                                                className={`pl-9 font-mono uppercase ${errors.code ? 'border-destructive' : ''}`}
                                                            />
                                                        </div>
                                                        {errors.code && <p className="text-destructive text-sm">{errors.code}</p>}
                                                    </div>
                                                </div>
                                                <div className="space-y-2">
                                                    <Label htmlFor="channel_link">
                                                        Channel Link <span className="text-destructive">*</span>
                                                    </Label>
                                                    <div className="relative">
                                                        <LinkIcon className="text-muted-foreground absolute top-2.5 left-3 h-4 w-4" />
                                                        <Input
                                                            id="channel_link"
                                                            placeholder="https://youtube.com/@example"
                                                            value={data.channel_link}
                                                            onChange={(e) => setData('channel_link', e.target.value)}
                                                            className={`pl-9 ${errors.channel_link ? 'border-destructive' : ''}`}
                                                        />
                                                    </div>
                                                    {errors.channel_link && <p className="text-destructive text-sm">{errors.channel_link}</p>}
                                                </div>
                                            </div>
                                        </div>

                                        <div className="flex justify-end pt-4">
                                            <Button type="submit" disabled={processing} size="lg" className="w-full sm:w-auto">
                                                {processing ? (
                                                    <>
                                                        <Clock className="mr-2 h-4 w-4 animate-spin" />
                                                        Submitting...
                                                    </>
                                                ) : (
                                                    <>
                                                        Submit Application
                                                        <ArrowRight className="ml-2 h-4 w-4" />
                                                    </>
                                                )}
                                            </Button>
                                        </div>
                                    </form>
                                </CardContent>
                            </Card>
                        )}
                    </TabsContent>

                    {/* Upload Tab - Only for Approved Streamers */}
                    {isApproved && (
                        <TabsContent value="upload" className="mt-6">
                            {hasUploadedToday ? (
                                <Card>
                                    <CardHeader>
                                        <CardTitle className="flex items-center gap-2">
                                            <Clock className="h-5 w-5" />
                                            Daily Upload Limit Reached
                                        </CardTitle>
                                        <CardDescription>You have already uploaded an image today</CardDescription>
                                    </CardHeader>
                                    <CardContent>
                                        <Alert>
                                            <Clock className="h-4 w-4" />
                                            <AlertTitle>Next Upload Available</AlertTitle>
                                            <AlertDescription>
                                                You can upload your next image tomorrow at{' '}
                                                {getNextUploadTime().toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' })}
                                                <br />
                                                <span className="text-muted-foreground text-xs">
                                                    (
                                                    {getNextUploadTime().toLocaleDateString('en-US', {
                                                        weekday: 'long',
                                                        year: 'numeric',
                                                        month: 'long',
                                                        day: 'numeric',
                                                    })}
                                                    )
                                                </span>
                                            </AlertDescription>
                                        </Alert>
                                    </CardContent>
                                </Card>
                            ) : (
                                <Card>
                                    <CardHeader>
                                        <CardTitle className="flex items-center gap-2">
                                            <Upload className="h-5 w-5" />
                                            Upload Image
                                        </CardTitle>
                                        <CardDescription>
                                            Upload images to earn gold rewards. Maximum 1 upload per day. Upload result live to here, and get reward.
                                        </CardDescription>
                                    </CardHeader>
                                    <CardContent className="space-y-4">
                                        <div className="space-y-2">
                                            <Label htmlFor="image">Select Image</Label>
                                            <Input
                                                ref={fileInputRef}
                                                id="image"
                                                type="file"
                                                accept="image/jpeg,image/jpg,image/png,image/gif,image/webp"
                                                onChange={handleImageSelect}
                                            />
                                            <p className="text-muted-foreground text-xs">Accepted formats: JPG, PNG, GIF, WEBP. Max size: 5MB</p>
                                        </div>

                                        {imagePreview && (
                                            <div className="space-y-2">
                                                <Label>Preview</Label>
                                                <div className="relative w-full max-w-md">
                                                    <img
                                                        src={imagePreview}
                                                        alt="Preview"
                                                        className="h-auto max-h-64 w-full rounded-lg border object-contain"
                                                    />
                                                </div>
                                            </div>
                                        )}

                                        <Button onClick={handleUpload} disabled={!selectedImage || uploadLoading} className="w-full sm:w-auto">
                                            {uploadLoading ? (
                                                <>
                                                    <Clock className="mr-2 h-4 w-4 animate-spin" />
                                                    Uploading...
                                                </>
                                            ) : (
                                                <>
                                                    <Upload className="h-4 w-4" />
                                                    <span className="ml-2 hidden md:inline">Upload Image</span>
                                                </>
                                            )}
                                        </Button>
                                    </CardContent>
                                </Card>
                            )}
                        </TabsContent>
                    )}

                    {/* History Tab - Only for Approved Streamers */}
                    {isApproved && (
                        <TabsContent value="history" className="mt-6">
                            <Card>
                                <CardHeader>
                                    <CardTitle className="flex items-center gap-2">
                                        <ImageIcon className="h-5 w-5" />
                                        Upload History
                                    </CardTitle>
                                    <CardDescription>View your uploaded images and their approval status</CardDescription>
                                </CardHeader>
                                <CardContent>
                                    {uploads.length === 0 ? (
                                        <div className="text-muted-foreground py-8 text-center">
                                            No uploads yet. Upload your first image to start earning gold!
                                        </div>
                                    ) : (
                                        <div className="overflow-x-auto">
                                            <Table>
                                                <TableHeader>
                                                    <TableRow>
                                                        <TableHead>Image</TableHead>
                                                        <TableHead>Upload Date</TableHead>
                                                        <TableHead>Status</TableHead>
                                                        <TableHead>Gold Reward</TableHead>
                                                        <TableHead>Notes</TableHead>
                                                        <TableHead>Actions</TableHead>
                                                    </TableRow>
                                                </TableHeader>
                                                <TableBody>
                                                    {uploads.map((upload) => (
                                                        <TableRow key={upload.id}>
                                                            <TableCell>
                                                                <img
                                                                    src={upload.image_url}
                                                                    alt="Upload"
                                                                    className="h-16 w-16 rounded border object-cover"
                                                                />
                                                            </TableCell>
                                                            <TableCell className="text-sm">
                                                                {new Date(upload.created_at).toLocaleDateString()}
                                                            </TableCell>
                                                            <TableCell>{getStatusBadge(upload.status)}</TableCell>
                                                            <TableCell>
                                                                {upload.gold_reward ? (
                                                                    <span className="font-semibold">{upload.gold_reward.toLocaleString()} Gold</span>
                                                                ) : (
                                                                    <span className="text-muted-foreground">-</span>
                                                                )}
                                                            </TableCell>
                                                            <TableCell className="max-w-xs truncate text-sm">{upload.admin_notes || '-'}</TableCell>
                                                            <TableCell>
                                                                {upload.status === 'pending' && (
                                                                    <Button
                                                                        size="sm"
                                                                        variant="destructive"
                                                                        onClick={() => handleDeleteUpload(upload.id)}
                                                                    >
                                                                        <Trash2 className="h-4 w-4" />
                                                                    </Button>
                                                                )}
                                                            </TableCell>
                                                        </TableRow>
                                                    ))}
                                                </TableBody>
                                            </Table>
                                        </div>
                                    )}
                                </CardContent>
                            </Card>
                        </TabsContent>
                    )}
                </Tabs>
            </div>
        </FrontendLayout>
    );
}
