'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { ChevronLeft, Package, Users, Copy, Check, ExternalLink, Loader2, X, Clock, CheckCircle2, Truck, Ban } from 'lucide-react';
import { getHostSplits, getSplitBySlug, updateParticipantStatus, generateForumExport, closeSplit, SplitDetails } from '@/services/split-actions';
import SplitProgressBar from '@/components/SplitProgressBar';

interface SplitSummary {
    id: string;
    slug: string;
    bottleName: string;
    bottleImage?: string;
    totalVolume: number;
    hostShare: number;
    participantCount: number;
    pendingCount: number;
    isActive: boolean;
}

export default function SplitManagePage() {
    const [splits, setSplits] = useState<SplitSummary[]>([]);
    const [isLoading, setIsLoading] = useState(true);
    const [selectedSplit, setSelectedSplit] = useState<SplitDetails | null>(null);
    const [isLoadingDetails, setIsLoadingDetails] = useState(false);
    const [forumText, setForumText] = useState<string | null>(null);
    const [copiedLink, setCopiedLink] = useState<string | null>(null);

    useEffect(() => {
        fetchSplits();
    }, []);

    const fetchSplits = async () => {
        const result = await getHostSplits();
        if (result.success && result.splits) {
            setSplits(result.splits);
        }
        setIsLoading(false);
    };

    const openSplitDetails = async (slug: string) => {
        setIsLoadingDetails(true);
        const result = await getSplitBySlug(slug);
        if (result.success && result.data) {
            setSelectedSplit(result.data);
        }
        setIsLoadingDetails(false);
    };

    const handleStatusUpdate = async (participantId: string, newStatus: 'APPROVED' | 'REJECTED' | 'PAID' | 'SHIPPED') => {
        const result = await updateParticipantStatus(participantId, newStatus);
        if (result.success && selectedSplit) {
            openSplitDetails(selectedSplit.publicSlug);
            fetchSplits();
        }
    };

    const handleForumExport = async (splitId: string) => {
        const result = await generateForumExport(splitId);
        if (result.success && result.text) {
            setForumText(result.text);
        }
    };

    const handleCloseSplit = async (splitId: string) => {
        if (!confirm('Möchtest du diesen Split wirklich schließen?')) return;
        const result = await closeSplit(splitId);
        if (result.success) {
            fetchSplits();
            setSelectedSplit(null);
        }
    };

    const copyLink = (slug: string) => {
        const url = `${window.location.origin}/splits/${slug}`;
        navigator.clipboard.writeText(url);
        setCopiedLink(slug);
        setTimeout(() => setCopiedLink(null), 2000);
    };

    const statusConfig: Record<string, { label: string; color: string; icon: typeof Clock }> = {
        PENDING: { label: 'Ausstehend', color: 'bg-yellow-500/20 text-yellow-500', icon: Clock },
        APPROVED: { label: 'Bestätigt', color: 'bg-green-500/20 text-green-500', icon: CheckCircle2 },
        PAID: { label: 'Bezahlt', color: 'bg-blue-500/20 text-blue-500', icon: Check },
        SHIPPED: { label: 'Versendet', color: 'bg-purple-500/20 text-purple-500', icon: Truck },
        REJECTED: { label: 'Abgelehnt', color: 'bg-red-500/20 text-red-500', icon: Ban },
        WAITLIST: { label: 'Warteliste', color: 'bg-zinc-500/20 text-zinc-500', icon: Clock },
    };

    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>
        );
    }

    return (
        <main className="min-h-screen bg-zinc-950 p-4 md:p-8 lg:p-12">
            <div className="max-w-4xl mx-auto space-y-6">
                {/* Header */}
                <div className="flex items-center justify-between">
                    <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} />
                        Zurück
                    </Link>
                    <Link
                        href="/splits/create"
                        className="px-4 py-2 bg-orange-600 hover:bg-orange-700 text-white rounded-xl font-bold text-sm transition-colors"
                    >
                        Neuer Split
                    </Link>
                </div>

                <div>
                    <h1 className="text-3xl font-black text-white">Meine Splits</h1>
                    <p className="text-zinc-500">Verwalte deine Flaschenteilungen</p>
                </div>

                {splits.length === 0 ? (
                    <div className="bg-zinc-900 rounded-3xl p-12 border border-zinc-800 text-center">
                        <Package size={48} className="mx-auto text-zinc-600 mb-4" />
                        <p className="text-zinc-500 mb-4">Du hast noch keine Splits erstellt</p>
                        <Link
                            href="/splits/create"
                            className="inline-block px-6 py-3 bg-orange-600 text-white rounded-xl font-bold"
                        >
                            Ersten Split erstellen
                        </Link>
                    </div>
                ) : (
                    <div className="grid gap-4">
                        {splits.map(split => (
                            <div
                                key={split.id}
                                className={`bg-zinc-900 rounded-2xl p-4 border transition-all cursor-pointer ${selectedSplit?.id === split.id
                                        ? 'border-orange-500'
                                        : 'border-zinc-800 hover:border-zinc-700'
                                    }`}
                                onClick={() => openSplitDetails(split.slug)}
                            >
                                <div className="flex items-center gap-4">
                                    {split.bottleImage ? (
                                        <img
                                            src={split.bottleImage}
                                            alt={split.bottleName}
                                            className="w-16 h-16 rounded-xl object-cover"
                                        />
                                    ) : (
                                        <div className="w-16 h-16 rounded-xl bg-zinc-800 flex items-center justify-center">
                                            <Package size={24} className="text-zinc-600" />
                                        </div>
                                    )}
                                    <div className="flex-1 min-w-0">
                                        <div className="flex items-center gap-2">
                                            <p className="font-bold text-white truncate">{split.bottleName}</p>
                                            {!split.isActive && (
                                                <span className="px-2 py-0.5 bg-zinc-800 rounded text-[10px] font-bold text-zinc-500">
                                                    Geschlossen
                                                </span>
                                            )}
                                        </div>
                                        <div className="flex items-center gap-4 mt-1 text-xs text-zinc-500">
                                            <span className="flex items-center gap-1">
                                                <Users size={12} />
                                                {split.participantCount} bestätigt
                                            </span>
                                            {split.pendingCount > 0 && (
                                                <span className="flex items-center gap-1 text-yellow-500">
                                                    <Clock size={12} />
                                                    {split.pendingCount} ausstehend
                                                </span>
                                            )}
                                        </div>
                                    </div>
                                    <button
                                        onClick={(e) => {
                                            e.stopPropagation();
                                            copyLink(split.slug);
                                        }}
                                        className="p-2 hover:bg-zinc-800 rounded-xl transition-colors"
                                    >
                                        {copiedLink === split.slug ? (
                                            <Check size={18} className="text-green-500" />
                                        ) : (
                                            <Copy size={18} className="text-zinc-500" />
                                        )}
                                    </button>
                                </div>
                            </div>
                        ))}
                    </div>
                )}

                {/* Detail Panel */}
                {selectedSplit && (
                    <div className="bg-zinc-900 rounded-3xl p-6 border border-zinc-800 space-y-6">
                        <div className="flex items-center justify-between">
                            <h2 className="text-lg font-bold text-white">{selectedSplit.bottle.name}</h2>
                            <button
                                onClick={() => setSelectedSplit(null)}
                                className="p-2 hover:bg-zinc-800 rounded-xl"
                            >
                                <X size={20} className="text-zinc-500" />
                            </button>
                        </div>

                        {/* Progress */}
                        <SplitProgressBar
                            totalVolume={selectedSplit.totalVolume}
                            hostShare={selectedSplit.hostShare}
                            taken={selectedSplit.taken}
                            reserved={selectedSplit.reserved}
                            height="md"
                        />

                        {/* Participants */}
                        <div className="space-y-3">
                            <h3 className="text-xs font-bold text-zinc-500 uppercase tracking-widest">Teilnehmer</h3>

                            {selectedSplit.participants.length === 0 ? (
                                <p className="text-sm text-zinc-500 italic">Noch keine Anfragen</p>
                            ) : (
                                selectedSplit.participants.map(p => {
                                    const config = statusConfig[p.status];
                                    const StatusIcon = config.icon;
                                    return (
                                        <div key={p.id} className="flex items-center justify-between p-3 bg-zinc-800 rounded-xl">
                                            <div className="flex items-center gap-3">
                                                <div className={`w-8 h-8 rounded-lg flex items-center justify-center ${config.color}`}>
                                                    <StatusIcon size={16} />
                                                </div>
                                                <div>
                                                    <p className="text-sm font-bold text-white">
                                                        {p.username || 'Anonym'}
                                                    </p>
                                                    <p className="text-xs text-zinc-500">
                                                        {p.amountCl}cl · {p.totalCost.toFixed(2)}€ · {p.shippingMethod}
                                                    </p>
                                                </div>
                                            </div>

                                            {/* Status Actions */}
                                            <div className="flex gap-2">
                                                {p.status === 'PENDING' && (
                                                    <>
                                                        <button
                                                            onClick={() => handleStatusUpdate(p.id, 'APPROVED')}
                                                            className="px-3 py-1.5 bg-green-600 hover:bg-green-700 text-white rounded-lg text-xs font-bold"
                                                        >
                                                            Bestätigen
                                                        </button>
                                                        <button
                                                            onClick={() => handleStatusUpdate(p.id, 'REJECTED')}
                                                            className="px-3 py-1.5 bg-red-600/20 hover:bg-red-600/40 text-red-400 rounded-lg text-xs font-bold"
                                                        >
                                                            Ablehnen
                                                        </button>
                                                    </>
                                                )}
                                                {p.status === 'APPROVED' && (
                                                    <button
                                                        onClick={() => handleStatusUpdate(p.id, 'PAID')}
                                                        className="px-3 py-1.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-xs font-bold"
                                                    >
                                                        Bezahlt
                                                    </button>
                                                )}
                                                {p.status === 'PAID' && (
                                                    <button
                                                        onClick={() => handleStatusUpdate(p.id, 'SHIPPED')}
                                                        className="px-3 py-1.5 bg-purple-600 hover:bg-purple-700 text-white rounded-lg text-xs font-bold"
                                                    >
                                                        Versendet
                                                    </button>
                                                )}
                                            </div>
                                        </div>
                                    );
                                })
                            )}
                        </div>

                        {/* Actions */}
                        <div className="flex flex-wrap gap-3 pt-4 border-t border-zinc-800">
                            <Link
                                href={`/splits/${selectedSplit.publicSlug}`}
                                className="px-4 py-2 bg-zinc-800 hover:bg-zinc-700 text-white rounded-xl text-sm font-bold flex items-center gap-2 transition-colors"
                            >
                                <ExternalLink size={16} />
                                Öffentliche Seite
                            </Link>
                            <button
                                onClick={() => handleForumExport(selectedSplit.id)}
                                className="px-4 py-2 bg-zinc-800 hover:bg-zinc-700 text-white rounded-xl text-sm font-bold flex items-center gap-2 transition-colors"
                            >
                                <Copy size={16} />
                                Forum Export
                            </button>
                            {selectedSplit.isActive && (
                                <button
                                    onClick={() => handleCloseSplit(selectedSplit.id)}
                                    className="px-4 py-2 bg-red-600/20 hover:bg-red-600/40 text-red-400 rounded-xl text-sm font-bold transition-colors"
                                >
                                    Split schließen
                                </button>
                            )}
                        </div>
                    </div>
                )}

                {/* Forum Export Modal */}
                {forumText && (
                    <div className="fixed inset-0 bg-black/80 flex items-center justify-center p-4 z-50">
                        <div className="bg-zinc-900 rounded-3xl p-6 max-w-lg w-full space-y-4">
                            <div className="flex items-center justify-between">
                                <h3 className="font-bold text-white">Forum Export</h3>
                                <button onClick={() => setForumText(null)} className="p-2 hover:bg-zinc-800 rounded-xl">
                                    <X size={20} className="text-zinc-500" />
                                </button>
                            </div>
                            <pre className="bg-zinc-950 p-4 rounded-xl text-xs text-zinc-300 overflow-x-auto whitespace-pre-wrap">
                                {forumText}
                            </pre>
                            <button
                                onClick={() => {
                                    navigator.clipboard.writeText(forumText);
                                    setForumText(null);
                                }}
                                className="w-full py-3 bg-orange-600 hover:bg-orange-700 text-white rounded-xl font-bold flex items-center justify-center gap-2"
                            >
                                <Copy size={16} />
                                Kopieren & Schließen
                            </button>
                        </div>
                    </div>
                )}
            </div>
        </main>
    );
}
