'use client';

import React, { useState, useEffect } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import Link from 'next/link';
import { ChevronLeft, ChevronRight, Package, Truck, Plus, X, Loader2, Check, Wine } from 'lucide-react';
import { createSplit, ShippingOption, SampleSize } from '@/services/split-actions';
import { createClient } from '@/lib/supabase/client';

interface Bottle {
    id: string;
    name: string;
    distillery?: string;
    image_url?: string;
}

const DEFAULT_SIZES: SampleSize[] = [
    { cl: 2, glassCost: 0.50 },
    { cl: 5, glassCost: 0.80 },
    { cl: 10, glassCost: 1.50 },
];

export default function CreateSplitPage() {
    const router = useRouter();
    const searchParams = useSearchParams();
    const supabase = createClient();
    const preselectedBottleId = searchParams?.get('bottle');

    const [step, setStep] = useState(preselectedBottleId ? 2 : 1);
    const [bottles, setBottles] = useState<Bottle[]>([]);
    const [isLoadingBottles, setIsLoadingBottles] = useState(true);

    // Form state
    const [selectedBottle, setSelectedBottle] = useState<Bottle | null>(null);
    const [totalVolume, setTotalVolume] = useState(70);
    const [hostShare, setHostShare] = useState(10);
    const [priceBottle, setPriceBottle] = useState('');
    const [sampleSizes, setSampleSizes] = useState<SampleSize[]>(DEFAULT_SIZES);
    const [newSizeCl, setNewSizeCl] = useState('');
    const [newSizeCost, setNewSizeCost] = useState('');
    const [shippingOptions, setShippingOptions] = useState<ShippingOption[]>([
        { name: 'DHL', price: 5.50 },
        { name: 'Hermes', price: 4.90 },
    ]);
    const [newShippingName, setNewShippingName] = useState('');
    const [newShippingPrice, setNewShippingPrice] = useState('');

    const [isCreating, setIsCreating] = useState(false);
    const [error, setError] = useState<string | null>(null);

    useEffect(() => {
        fetchBottles();
        loadSavedDefaults();
    }, []);

    useEffect(() => {
        if (preselectedBottleId && bottles.length > 0) {
            const bottle = bottles.find(b => b.id === preselectedBottleId);
            if (bottle) {
                setSelectedBottle(bottle);
            }
        }
    }, [preselectedBottleId, bottles]);

    const loadSavedDefaults = () => {
        const saved = localStorage.getItem('split-defaults');
        if (saved) {
            const defaults = JSON.parse(saved);
            if (defaults.sampleSizes) {
                setSampleSizes(defaults.sampleSizes);
            }
            if (defaults.shippingOptions) {
                setShippingOptions(defaults.shippingOptions);
            }
        }
    };

    const saveDefaults = () => {
        localStorage.setItem('split-defaults', JSON.stringify({
            sampleSizes,
            shippingOptions,
        }));
    };

    const fetchBottles = async () => {
        const { data: { user } } = await supabase.auth.getUser();
        if (!user) {
            router.push('/login');
            return;
        }

        const { data } = await supabase
            .from('bottles')
            .select('id, name, distillery, image_url')
            .eq('user_id', user.id)
            .is('finished_at', null)
            .order('name');

        setBottles(data || []);
        setIsLoadingBottles(false);
    };

    const addSampleSize = () => {
        if (!newSizeCl || !newSizeCost) return;
        const cl = parseInt(newSizeCl);
        if (sampleSizes.some(s => s.cl === cl)) return;
        setSampleSizes([...sampleSizes, { cl, glassCost: parseFloat(newSizeCost) }].sort((a, b) => a.cl - b.cl));
        setNewSizeCl('');
        setNewSizeCost('');
    };

    const removeSampleSize = (cl: number) => {
        setSampleSizes(sampleSizes.filter(s => s.cl !== cl));
    };

    const addShippingOption = () => {
        if (!newShippingName || !newShippingPrice) return;
        setShippingOptions([...shippingOptions, {
            name: newShippingName,
            price: parseFloat(newShippingPrice),
        }]);
        setNewShippingName('');
        setNewShippingPrice('');
    };

    const removeShippingOption = (index: number) => {
        setShippingOptions(shippingOptions.filter((_, i) => i !== index));
    };

    const handleCreate = async () => {
        if (!selectedBottle || !priceBottle || sampleSizes.length === 0) return;

        setIsCreating(true);
        setError(null);
        saveDefaults();

        const result = await createSplit({
            bottleId: selectedBottle.id,
            totalVolume,
            hostShare,
            priceBottle: parseFloat(priceBottle),
            sampleSizes,
            shippingOptions,
        });

        if (result.success && result.slug) {
            router.push(`/splits/${result.slug}`);
        } else {
            setError(result.error || 'Fehler beim Erstellen');
            setIsCreating(false);
        }
    };

    const pricePerCl = priceBottle ? parseFloat(priceBottle) / totalVolume : 0;

    return (
        <main className="min-h-screen bg-zinc-950 p-4 md:p-8 lg:p-12">
            <div className="max-w-xl mx-auto space-y-6">
                {/* Header */}
                <div className="flex items-center justify-between">
                    <Link
                        href={preselectedBottleId ? `/bottles/${preselectedBottleId}` : '/'}
                        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} />
                        Abbrechen
                    </Link>
                    <span className="text-xs font-bold text-zinc-600">Schritt {step} von 3</span>
                </div>

                {/* Progress */}
                <div className="flex gap-2">
                    {[1, 2, 3].map(s => (
                        <div
                            key={s}
                            className={`h-1 flex-1 rounded-full transition-colors ${s <= step ? 'bg-orange-600' : 'bg-zinc-800'
                                }`}
                        />
                    ))}
                </div>

                {/* Step 1: Select Bottle */}
                {step === 1 && (
                    <div className="space-y-6">
                        <div>
                            <h1 className="text-2xl font-black text-white">Flasche wählen</h1>
                            <p className="text-zinc-500 text-sm">Welche Flasche möchtest du teilen?</p>
                        </div>

                        {isLoadingBottles ? (
                            <div className="flex justify-center py-12">
                                <Loader2 size={32} className="animate-spin text-orange-600" />
                            </div>
                        ) : bottles.length === 0 ? (
                            <div className="text-center py-12 text-zinc-500">
                                <Wine size={48} className="mx-auto mb-4 opacity-50" />
                                <p>Keine Flaschen in deiner Sammlung</p>
                            </div>
                        ) : (
                            <div className="grid gap-3 max-h-[400px] overflow-y-auto pr-2">
                                {bottles.map(bottle => (
                                    <button
                                        key={bottle.id}
                                        onClick={() => setSelectedBottle(bottle)}
                                        className={`flex items-center gap-4 p-4 rounded-2xl border-2 text-left transition-all ${selectedBottle?.id === bottle.id
                                                ? 'border-orange-500 bg-orange-500/10'
                                                : 'border-zinc-800 hover:border-zinc-700'
                                            }`}
                                    >
                                        {bottle.image_url ? (
                                            <img
                                                src={bottle.image_url}
                                                alt={bottle.name}
                                                className="w-14 h-14 rounded-xl object-cover"
                                            />
                                        ) : (
                                            <div className="w-14 h-14 rounded-xl bg-zinc-800 flex items-center justify-center">
                                                <Wine size={24} className="text-zinc-600" />
                                            </div>
                                        )}
                                        <div className="flex-1 min-w-0">
                                            <p className="font-bold text-white truncate">{bottle.name}</p>
                                            {bottle.distillery && (
                                                <p className="text-xs text-zinc-500">{bottle.distillery}</p>
                                            )}
                                        </div>
                                        {selectedBottle?.id === bottle.id && (
                                            <Check size={20} className="text-orange-500" />
                                        )}
                                    </button>
                                ))}
                            </div>
                        )}

                        <button
                            onClick={() => setStep(2)}
                            disabled={!selectedBottle}
                            className="w-full py-4 bg-orange-600 hover:bg-orange-700 disabled:bg-zinc-800 disabled:text-zinc-600 text-white rounded-2xl font-bold flex items-center justify-center gap-2 transition-colors"
                        >
                            Weiter
                            <ChevronRight size={18} />
                        </button>
                    </div>
                )}

                {/* Step 2: Pricing & Sizes */}
                {step === 2 && (
                    <div className="space-y-6">
                        <div>
                            <h1 className="text-2xl font-black text-white">Preise & Größen</h1>
                            <p className="text-zinc-500 text-sm">{selectedBottle?.name}</p>
                        </div>

                        <div className="space-y-4">
                            <div className="grid grid-cols-2 gap-4">
                                <div>
                                    <label className="text-xs font-bold text-zinc-500 block mb-2">Flascheninhalt (cl)</label>
                                    <input
                                        type="number"
                                        value={totalVolume}
                                        onChange={e => setTotalVolume(parseInt(e.target.value) || 70)}
                                        className="w-full bg-zinc-800 border border-zinc-700 rounded-xl px-4 py-3 text-white"
                                    />
                                </div>
                                <div>
                                    <label className="text-xs font-bold text-zinc-500 block mb-2">Dein Anteil (cl)</label>
                                    <input
                                        type="number"
                                        value={hostShare}
                                        onChange={e => setHostShare(parseInt(e.target.value) || 10)}
                                        className="w-full bg-zinc-800 border border-zinc-700 rounded-xl px-4 py-3 text-white"
                                    />
                                </div>
                            </div>

                            <div>
                                <label className="text-xs font-bold text-zinc-500 block mb-2">Flaschenpreis (€)</label>
                                <input
                                    type="number"
                                    step="0.01"
                                    value={priceBottle}
                                    onChange={e => setPriceBottle(e.target.value)}
                                    placeholder="z.B. 65.00"
                                    className="w-full bg-zinc-800 border border-zinc-700 rounded-xl px-4 py-3 text-white"
                                />
                            </div>

                            {/* Sample Sizes */}
                            <div className="space-y-3">
                                <label className="text-xs font-bold text-zinc-500 uppercase tracking-widest">Verfügbare Größen</label>
                                <div className="flex flex-wrap gap-2">
                                    {sampleSizes.map(size => (
                                        <div
                                            key={size.cl}
                                            className="flex items-center gap-2 px-3 py-2 bg-zinc-800 rounded-xl"
                                        >
                                            <span className="font-bold text-white">{size.cl}cl</span>
                                            <span className="text-zinc-500 text-xs">+{size.glassCost.toFixed(2)}€</span>
                                            <button
                                                onClick={() => removeSampleSize(size.cl)}
                                                className="text-red-500 hover:text-red-400 ml-1"
                                            >
                                                <X size={14} />
                                            </button>
                                        </div>
                                    ))}
                                </div>
                                <div className="flex gap-2">
                                    <input
                                        type="number"
                                        value={newSizeCl}
                                        onChange={e => setNewSizeCl(e.target.value)}
                                        placeholder="cl"
                                        className="w-20 bg-zinc-800 border border-zinc-700 rounded-xl px-3 py-2 text-white text-sm"
                                    />
                                    <input
                                        type="number"
                                        step="0.01"
                                        value={newSizeCost}
                                        onChange={e => setNewSizeCost(e.target.value)}
                                        placeholder="Glaskosten €"
                                        className="flex-1 bg-zinc-800 border border-zinc-700 rounded-xl px-3 py-2 text-white text-sm"
                                    />
                                    <button
                                        onClick={addSampleSize}
                                        disabled={!newSizeCl || !newSizeCost}
                                        className="p-2 bg-zinc-700 hover:bg-zinc-600 disabled:opacity-50 rounded-xl transition-colors"
                                    >
                                        <Plus size={20} className="text-white" />
                                    </button>
                                </div>
                            </div>

                            {/* Preview */}
                            {priceBottle && sampleSizes.length > 0 && (
                                <div className="bg-zinc-900 rounded-2xl p-4 border border-zinc-800">
                                    <p className="text-xs font-bold text-zinc-500 mb-3">Vorschau (inkl. Flasche)</p>
                                    <div className="grid grid-cols-2 gap-2">
                                        {sampleSizes.map(size => (
                                            <div key={size.cl} className="flex justify-between text-sm">
                                                <span className="text-zinc-400">{size.cl}cl:</span>
                                                <span className="font-bold text-orange-500">
                                                    {(pricePerCl * size.cl + size.glassCost).toFixed(2)}€
                                                </span>
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            )}
                        </div>

                        <div className="flex gap-3">
                            <button
                                onClick={() => setStep(1)}
                                className="flex-1 py-4 bg-zinc-800 hover:bg-zinc-700 text-white rounded-2xl font-bold transition-colors"
                            >
                                Zurück
                            </button>
                            <button
                                onClick={() => setStep(3)}
                                disabled={!priceBottle || sampleSizes.length === 0}
                                className="flex-1 py-4 bg-orange-600 hover:bg-orange-700 disabled:bg-zinc-800 disabled:text-zinc-600 text-white rounded-2xl font-bold flex items-center justify-center gap-2 transition-colors"
                            >
                                Weiter
                                <ChevronRight size={18} />
                            </button>
                        </div>
                    </div>
                )}

                {/* Step 3: Shipping */}
                {step === 3 && (
                    <div className="space-y-6">
                        <div>
                            <h1 className="text-2xl font-black text-white">Versandoptionen</h1>
                            <p className="text-zinc-500 text-sm">Welche Versandarten bietest du an?</p>
                        </div>

                        <div className="space-y-3">
                            {shippingOptions.map((option, i) => (
                                <div
                                    key={i}
                                    className="flex items-center justify-between p-4 bg-zinc-800 rounded-2xl"
                                >
                                    <div className="flex items-center gap-3">
                                        <Truck size={20} className="text-orange-600" />
                                        <span className="font-bold text-white">{option.name}</span>
                                    </div>
                                    <div className="flex items-center gap-3">
                                        <span className="text-zinc-400">{option.price.toFixed(2)}€</span>
                                        <button
                                            onClick={() => removeShippingOption(i)}
                                            className="text-red-500 hover:text-red-400"
                                        >
                                            <X size={18} />
                                        </button>
                                    </div>
                                </div>
                            ))}

                            <div className="flex gap-2">
                                <input
                                    type="text"
                                    value={newShippingName}
                                    onChange={e => setNewShippingName(e.target.value)}
                                    placeholder="Name (z.B. DPD)"
                                    className="flex-1 bg-zinc-800 border border-zinc-700 rounded-xl px-4 py-3 text-white text-sm"
                                />
                                <input
                                    type="number"
                                    step="0.01"
                                    value={newShippingPrice}
                                    onChange={e => setNewShippingPrice(e.target.value)}
                                    placeholder="Preis"
                                    className="w-24 bg-zinc-800 border border-zinc-700 rounded-xl px-4 py-3 text-white text-sm"
                                />
                                <button
                                    onClick={addShippingOption}
                                    disabled={!newShippingName || !newShippingPrice}
                                    className="p-3 bg-zinc-700 hover:bg-zinc-600 disabled:opacity-50 rounded-xl transition-colors"
                                >
                                    <Plus size={20} className="text-white" />
                                </button>
                            </div>
                        </div>

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

                        <div className="flex gap-3">
                            <button
                                onClick={() => setStep(2)}
                                className="flex-1 py-4 bg-zinc-800 hover:bg-zinc-700 text-white rounded-2xl font-bold transition-colors"
                            >
                                Zurück
                            </button>
                            <button
                                onClick={handleCreate}
                                disabled={isCreating || shippingOptions.length === 0}
                                className="flex-1 py-4 bg-orange-600 hover:bg-orange-700 disabled:bg-zinc-800 disabled:text-zinc-600 text-white rounded-2xl font-bold flex items-center justify-center gap-2 transition-colors"
                            >
                                {isCreating ? (
                                    <Loader2 size={20} className="animate-spin" />
                                ) : (
                                    <>
                                        <Package size={18} />
                                        Split erstellen
                                    </>
                                )}
                            </button>
                        </div>
                    </div>
                )}
            </div>
        </main>
    );
}
