'use client';

import React, { useState, useEffect } from 'react';
import { useParams } from 'next/navigation';
import Link from 'next/link';
import { ChevronLeft, Share2, User, Package, Truck, Loader2, CheckCircle2, Clock, AlertCircle, LogIn } from 'lucide-react';
import { getSplitBySlug, requestSlot, SplitDetails, SampleSize, ShippingOption } from '@/services/split-actions';
import SplitProgressBar from '@/components/SplitProgressBar';
import { createClient } from '@/lib/supabase/client';
import { useI18n } from '@/i18n/I18nContext';

export default function SplitPublicPage() {
    const { slug } = useParams();
    const { t } = useI18n();
    const supabase = createClient();
    const [split, setSplit] = useState<SplitDetails | null>(null);
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);

    const [selectedAmount, setSelectedAmount] = useState<number | null>(null);
    const [selectedShipping, setSelectedShipping] = useState<string>('');
    const [isRequesting, setIsRequesting] = useState(false);
    const [requestSuccess, setRequestSuccess] = useState(false);
    const [requestError, setRequestError] = useState<string | null>(null);
    const [currentUserId, setCurrentUserId] = useState<string | null>(null);

    useEffect(() => {
        fetchSplit();
        checkUser();
    }, [slug]);

    const checkUser = async () => {
        const { data: { user } } = await supabase.auth.getUser();
        setCurrentUserId(user?.id || null);
    };

    const fetchSplit = async () => {
        setIsLoading(true);
        const result = await getSplitBySlug(slug as string);
        if (result.success && result.data) {
            setSplit(result.data);
            if (result.data.shippingOptions.length > 0) {
                setSelectedShipping(result.data.shippingOptions[0].name);
            }
            if (result.data.sampleSizes.length > 0) {
                setSelectedAmount(result.data.sampleSizes[0].cl);
            }
        } else {
            setError(result.error || t('splits.noSplitsFound'));
        }
        setIsLoading(false);
    };

    const calculatePrice = (amountCl: number): { whisky: number; glass: number; shipping: number; total: number } => {
        if (!split) return { whisky: 0, glass: 0, shipping: 0, total: 0 };

        const pricePerCl = split.priceBottle / split.totalVolume;
        const whisky = pricePerCl * amountCl;
        const sizeOption = split.sampleSizes.find(s => s.cl === amountCl);
        const glass = sizeOption?.glassCost || 0;
        const shippingOption = split.shippingOptions.find(s => s.name === selectedShipping);
        const shipping = shippingOption?.price || 0;

        return {
            whisky: Math.round(whisky * 100) / 100,
            glass,
            shipping,
            total: Math.round((whisky + glass + shipping) * 100) / 100,
        };
    };

    const handleRequest = async () => {
        if (!selectedShipping || !selectedAmount) return;
        if (!currentUserId) {
            window.location.href = `/login?redirect=/splits/${slug}`;
            return;
        }

        setIsRequesting(true);
        setRequestError(null);

        const result = await requestSlot(split!.id, selectedAmount, selectedShipping);

        if (result.success) {
            setRequestSuccess(true);
            fetchSplit();
        } else {
            setRequestError(result.error || 'Anfrage fehlgeschlagen');
        }

        setIsRequesting(false);
    };

    const userParticipation = split?.participants.find(p => p.userId === currentUserId);
    const showRequestForm = !userParticipation && currentUserId !== split?.hostId;
    const isWaitlist = split && selectedAmount && split.remaining < selectedAmount;

    if (isLoading) {
        return (
            <div className="min-h-screen flex items-center justify-center bg-zinc-950">
                <Loader2 size={48} className="animate-spin text-orange-600" />
            </div>
        );
    }

    if (error || !split) {
        return (
            <div className="min-h-screen flex flex-col items-center justify-center gap-4 bg-zinc-950 p-6">
                <AlertCircle size={48} className="text-red-500" />
                <h1 className="text-xl font-bold text-zinc-50">{error || t('splits.noSplitsFound')}</h1>
                <Link href="/" className="text-orange-600 font-bold">{t('splits.backToStart')}</Link>
            </div>
        );
    }

    const price = selectedAmount ? calculatePrice(selectedAmount) : { whisky: 0, glass: 0, shipping: 0, total: 0 };

    return (
        <main className="min-h-screen bg-zinc-950 p-4 md:p-8 lg:p-12">
            <div className="max-w-2xl mx-auto space-y-6">
                <Link
                    href="/"
                    className="inline-flex items-center gap-2 text-zinc-500 hover:text-orange-600 transition-colors font-bold uppercase text-[10px] tracking-[0.2em]"
                >
                    <ChevronLeft size={16} />
                    {t('common.back')}
                </Link>

                {/* Hero */}
                <div className="bg-zinc-900 rounded-3xl overflow-hidden border border-zinc-800 shadow-xl">
                    {split.bottle.imageUrl && (
                        <div className="h-48 md:h-64 bg-zinc-800 relative">
                            <img
                                src={split.bottle.imageUrl}
                                alt={split.bottle.name}
                                className="w-full h-full object-cover opacity-80"
                            />
                            <div className="absolute inset-0 bg-gradient-to-t from-zinc-900 via-transparent to-transparent" />
                        </div>
                    )}

                    <div className="p-6 space-y-4">
                        <div>
                            <p className="text-[10px] font-black uppercase tracking-widest text-orange-500 mb-1">
                                {t('splits.falscheTeilung')}
                            </p>
                            <h1 className="text-2xl md:text-3xl font-black text-zinc-50">
                                {split.bottle.name}
                            </h1>
                            {split.bottle.distillery && (
                                <p className="text-zinc-500 font-medium">{split.bottle.distillery}</p>
                            )}
                        </div>

                        <div className="flex flex-wrap gap-3">
                            {split.bottle.abv && (
                                <span className="px-3 py-1.5 bg-zinc-800 rounded-xl text-xs font-bold text-zinc-300">
                                    {split.bottle.abv}% ABV
                                </span>
                            )}
                            {split.bottle.age && (
                                <span className="px-3 py-1.5 bg-zinc-800 rounded-xl text-xs font-bold text-zinc-300">
                                    {split.bottle.age} {t('splits.jahre')}
                                </span>
                            )}
                            <span className="px-3 py-1.5 bg-zinc-800 rounded-xl text-xs font-bold text-zinc-300">
                                {split.totalVolume}{t('splits.clFlasche')}
                            </span>
                        </div>

                        <div className="pt-4">
                            <SplitProgressBar
                                totalVolume={split.totalVolume}
                                hostShare={split.hostShare}
                                taken={split.taken}
                                reserved={split.reserved}
                                height="lg"
                            />
                        </div>
                    </div>
                </div>

                {/* Request Form */}
                {showRequestForm && !requestSuccess && (
                    <div className="bg-zinc-900 rounded-3xl p-6 border border-zinc-800 space-y-6">
                        <h2 className="text-sm font-black uppercase tracking-widest text-zinc-400">
                            {t('splits.joinTitle')}
                        </h2>

                        {/* Amount Selection */}
                        <div className="space-y-3">
                            <label className="text-xs font-bold text-zinc-500 uppercase tracking-widest">{t('splits.amount')}</label>
                            <div className="flex flex-wrap gap-2">
                                {split.sampleSizes.map(size => (
                                    <button
                                        key={size.cl}
                                        onClick={() => setSelectedAmount(size.cl)}
                                        className={`px-4 py-3 rounded-xl border-2 transition-all ${selectedAmount === size.cl
                                            ? 'border-orange-500 bg-orange-500/10'
                                            : 'border-zinc-700 hover:border-zinc-600'
                                            }`}
                                    >
                                        <span className="text-lg font-black text-white">{size.cl}cl</span>
                                    </button>
                                ))}
                            </div>
                        </div>

                        {/* Shipping Selection */}
                        <div className="space-y-3">
                            <label className="text-xs font-bold text-zinc-500 uppercase tracking-widest flex items-center gap-2">
                                <Truck size={14} />
                                {t('splits.shipping')}
                            </label>
                            <div className="flex flex-wrap gap-2">
                                {split.shippingOptions.map(option => (
                                    <button
                                        key={option.name}
                                        onClick={() => setSelectedShipping(option.name)}
                                        className={`px-4 py-3 rounded-xl border-2 transition-all text-left ${selectedShipping === option.name
                                            ? 'border-orange-500 bg-orange-500/10'
                                            : 'border-zinc-700 hover:border-zinc-600'
                                            }`}
                                    >
                                        <span className="text-sm font-bold text-white">{option.name}</span>
                                        <p className="text-xs text-zinc-500">{option.price.toFixed(2)}€</p>
                                    </button>
                                ))}
                            </div>
                        </div>

                        {/* Price Breakdown */}
                        {selectedAmount && (
                            <div className="bg-zinc-950 rounded-2xl p-4 space-y-2">
                                <div className="flex justify-between text-sm">
                                    <span className="text-zinc-500">{t('splits.whisky')} ({selectedAmount}cl)</span>
                                    <span className="text-zinc-300">{price.whisky.toFixed(2)}€</span>
                                </div>
                                <div className="flex justify-between text-sm">
                                    <span className="text-zinc-500">{t('splits.glass')}</span>
                                    <span className="text-zinc-300">{price.glass.toFixed(2)}€</span>
                                </div>
                                <div className="flex justify-between text-sm">
                                    <span className="text-zinc-500">{t('splits.shipping')} ({selectedShipping})</span>
                                    <span className="text-zinc-300">{price.shipping.toFixed(2)}€</span>
                                </div>
                                <div className="border-t border-zinc-800 pt-2 mt-2 flex justify-between">
                                    <span className="font-bold text-white">{t('splits.total')}</span>
                                    <span className="font-black text-xl text-orange-500">{price.total.toFixed(2)}€</span>
                                </div>
                            </div>
                        )}

                        {requestError && (
                            <div className="bg-red-500/10 border border-red-500/30 rounded-xl p-3 text-sm text-red-400">
                                {requestError}
                            </div>
                        )}

                        {currentUserId ? (
                            <button
                                onClick={handleRequest}
                                disabled={isRequesting || !selectedShipping || !selectedAmount}
                                className={`w-full py-4 rounded-2xl font-bold text-white transition-all flex items-center justify-center gap-2 ${isWaitlist
                                    ? 'bg-yellow-600 hover:bg-yellow-700'
                                    : 'bg-orange-600 hover:bg-orange-700'
                                    } disabled:opacity-50`}
                            >
                                {isRequesting ? (
                                    <Loader2 size={20} className="animate-spin" />
                                ) : isWaitlist ? (
                                    <>
                                        <Clock size={20} />
                                        {t('splits.waitlist')}
                                    </>
                                ) : (
                                    <>
                                        <Package size={20} />
                                        {t('splits.sendRequest')}
                                    </>
                                )}
                            </button>
                        ) : (
                            <div className="space-y-4 pt-4 border-t border-zinc-800">
                                <div className="flex items-start gap-4 p-4 bg-orange-600/10 rounded-2xl border border-orange-500/20">
                                    <AlertCircle className="text-orange-500 shrink-0 mt-0.5" size={18} />
                                    <div>
                                        <p className="text-sm font-bold text-white mb-1">{t('splits.loginToParticipate')}</p>
                                        <p className="text-xs text-orange-200/60 leading-relaxed">
                                            {t('splits.loginToParticipateDesc')}
                                        </p>
                                    </div>
                                </div>
                                <button
                                    onClick={() => window.location.href = `/login?redirect=/splits/${slug}`}
                                    className="w-full py-4 bg-orange-600 hover:bg-orange-500 text-white rounded-2xl font-bold flex items-center justify-center gap-2 shadow-xl shadow-orange-950/20 transition-all active:scale-[0.98]"
                                >
                                    <LogIn size={20} />
                                    {t('home.logout').replace('Logout', 'Login').replace('Abmelden', 'Anmelden')}
                                </button>
                            </div>
                        )}
                    </div>
                )}

                {requestSuccess && (
                    <div className="bg-green-500/10 border border-green-500/30 rounded-3xl p-6 text-center">
                        <CheckCircle2 size={48} className="mx-auto text-green-500 mb-4" />
                        <h3 className="text-lg font-bold text-white mb-2">{t('splits.requestSent')}</h3>
                        <p className="text-zinc-400 text-sm">
                            {t('splits.requestSentDesc')}
                        </p>
                    </div>
                )}

                {userParticipation && (
                    <div className="bg-zinc-900 rounded-3xl p-6 border border-zinc-800">
                        <div className="flex items-center gap-4">
                            <div className={`w-12 h-12 rounded-xl flex items-center justify-center ${['APPROVED', 'PAID', 'SHIPPED'].includes(userParticipation.status)
                                ? 'bg-green-500/20 text-green-500'
                                : userParticipation.status === 'PENDING'
                                    ? 'bg-yellow-500/20 text-yellow-500'
                                    : 'bg-red-500/20 text-red-500'
                                }`}>
                                {userParticipation.status === 'SHIPPED' ? <Package size={24} /> :
                                    userParticipation.status === 'PENDING' ? <Clock size={24} /> :
                                        <CheckCircle2 size={24} />}
                            </div>
                            <div>
                                <p className="text-sm font-bold text-white">{t('splits.youAreParticipating')}</p>
                                <p className="text-xs text-zinc-500">
                                    {userParticipation.amountCl}cl · {userParticipation.totalCost.toFixed(2)}€ ·
                                    Status: {userParticipation.status}
                                </p>
                            </div>
                        </div>
                    </div>
                )}

                {currentUserId === split.hostId && (
                    <div className="bg-zinc-900 rounded-3xl p-6 border border-zinc-800">
                        <p className="text-sm text-zinc-500 mb-4">Du bist der Host dieses Splits</p>
                        <Link
                            href="/splits/manage"
                            className="inline-block px-4 py-2 bg-zinc-800 hover:bg-zinc-700 text-white rounded-xl font-bold text-sm transition-colors"
                        >
                            Zum Dashboard
                        </Link>
                    </div>
                )}

                <button
                    onClick={() => navigator.share?.({ url: window.location.href })}
                    className="w-full py-4 bg-zinc-900 hover:bg-zinc-800 border border-zinc-800 rounded-2xl text-zinc-400 font-bold flex items-center justify-center gap-2 transition-colors"
                >
                    <Share2 size={18} />
                    {t('splits.shareLink')}
                </button>
            </div>
        </main>
    );
}
