import { useEffect, useState } from 'react';
import { Link, useNavigate, useParams } from 'react-router-dom';
import axios from '../../../bootstrap';
import { ArrowLeft, ExternalLink, Globe, Loader2 } from 'lucide-react';
import { PANEL_ROUTES } from '../../../navigation/panelRoutes';

type KeyAgent = {
    id: string;
    domain: string;
    site_name: string;
    status: string;
    released_at?: string | null;
};

type ActivationKeyDetail = {
    id: number;
    key: string;
    type: string;
    status: string;
    max_activations: number;
    activations_count: number;
    active_slots: number;
    allowed_domains?: string | null;
    expires_at?: string | null;
    notes?: string | null;
    active_agents?: KeyAgent[];
    released_agents?: KeyAgent[];
};

function statusBadgeClass(status: string): string {
    switch (status) {
        case 'active':
            return 'bg-emerald-500/10 text-emerald-400 border-emerald-500/20';
        case 'offline':
            return 'bg-slate-700/40 text-slate-400 border-slate-600/40';
        case 'suspended':
            return 'bg-amber-500/10 text-amber-400 border-amber-500/20';
        case 'deactivation_allowed':
            return 'bg-orange-500/10 text-orange-400 border-orange-500/20';
        case 'pending_deletion':
            return 'bg-rose-500/10 text-rose-400 border-rose-500/20';
        case 'deleted':
            return 'bg-slate-700/40 text-slate-500 border-slate-600/40';
        default:
            return 'bg-slate-800 text-slate-400 border-slate-700/40';
    }
}

export function ActivationKeyDetailView() {
    const { keyId } = useParams<{ keyId: string }>();
    const navigate = useNavigate();
    const [keyDetail, setKeyDetail] = useState<ActivationKeyDetail | null>(null);
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);

    useEffect(() => {
        if (!keyId) {
            return;
        }

        const loadKey = async () => {
            setIsLoading(true);
            setError(null);

            try {
                const res = await axios.get(`/activation-keys/${keyId}`);
                setKeyDetail(res.data.key ?? null);
            } catch (err: any) {
                setError(err.response?.data?.message || 'Could not load activation key details.');
            } finally {
                setIsLoading(false);
            }
        };

        loadKey();
    }, [keyId]);

    if (isLoading) {
        return (
            <div className="flex justify-center items-center py-20">
                <Loader2 className="w-8 h-8 text-rose-500 animate-spin" />
            </div>
        );
    }

    if (error || !keyDetail) {
        return (
            <div className="space-y-4">
                <button
                    type="button"
                    onClick={() => navigate(PANEL_ROUTES.keys)}
                    className="inline-flex items-center gap-2 text-sm text-slate-400 hover:text-white"
                >
                    <ArrowLeft className="w-4 h-4" /> Back to Activation Keys
                </button>
                <div className="rounded-2xl border border-rose-500/20 bg-rose-500/10 p-6 text-sm text-rose-300">
                    {error || 'Activation key not found.'}
                </div>
            </div>
        );
    }

    const activeAgents = keyDetail.active_agents ?? [];
    const releasedAgents = keyDetail.released_agents ?? [];

    return (
        <div className="space-y-6">
            <div className="flex flex-wrap items-start justify-between gap-4">
                <div className="space-y-3">
                    <button
                        type="button"
                        onClick={() => navigate(PANEL_ROUTES.keys)}
                        className="inline-flex items-center gap-2 text-sm text-slate-400 hover:text-white"
                    >
                        <ArrowLeft className="w-4 h-4" /> Back to Activation Keys
                    </button>
                    <div>
                        <h3 className="text-xl font-bold text-white">Activation Key Details</h3>
                        <p className="mt-1 font-mono text-sm text-slate-300 select-all">{keyDetail.key}</p>
                    </div>
                </div>

                <div className="rounded-2xl border border-slate-800 bg-slate-900/40 px-5 py-4 text-right">
                    <p className="text-[10px] font-bold uppercase tracking-wider text-slate-500">Active Quota</p>
                    <p className="mt-1 text-2xl font-bold text-white">
                        {keyDetail.active_slots ?? keyDetail.activations_count}
                        <span className="text-base text-slate-500"> / {keyDetail.max_activations}</span>
                    </p>
                </div>
            </div>

            <div className="grid gap-4 md:grid-cols-4">
                <div className="rounded-2xl border border-slate-800 bg-slate-900/40 p-4">
                    <p className="text-[10px] font-bold uppercase tracking-wider text-slate-500">Type</p>
                    <p className="mt-2 text-sm font-semibold capitalize text-white">{keyDetail.type}</p>
                </div>
                <div className="rounded-2xl border border-slate-800 bg-slate-900/40 p-4">
                    <p className="text-[10px] font-bold uppercase tracking-wider text-slate-500">Status</p>
                    <p className="mt-2 text-sm font-semibold capitalize text-white">{keyDetail.status}</p>
                </div>
                <div className="rounded-2xl border border-slate-800 bg-slate-900/40 p-4">
                    <p className="text-[10px] font-bold uppercase tracking-wider text-slate-500">Expires</p>
                    <p className="mt-2 text-sm font-semibold text-white">
                        {keyDetail.expires_at ? new Date(keyDetail.expires_at).toLocaleDateString() : 'Never'}
                    </p>
                </div>
                <div className="rounded-2xl border border-slate-800 bg-slate-900/40 p-4">
                    <p className="text-[10px] font-bold uppercase tracking-wider text-slate-500">Allowed Domains</p>
                    <p className="mt-2 text-sm font-semibold text-white">{keyDetail.allowed_domains || 'Any'}</p>
                </div>
            </div>

            {keyDetail.notes ? (
                <div className="rounded-2xl border border-slate-800 bg-slate-900/40 p-4">
                    <p className="text-[10px] font-bold uppercase tracking-wider text-slate-500">Notes</p>
                    <p className="mt-2 text-sm text-slate-300">{keyDetail.notes}</p>
                </div>
            ) : null}

            <section className="rounded-2xl border border-slate-800 bg-slate-900/40 overflow-hidden">
                <div className="border-b border-slate-800 px-5 py-4">
                    <h4 className="text-sm font-bold text-white">Active Domains ({activeAgents.length})</h4>
                    <p className="mt-1 text-xs text-slate-500">Websites currently using this activation key.</p>
                </div>

                {activeAgents.length === 0 ? (
                    <div className="px-5 py-10 text-center text-sm text-slate-500">
                        No active domains are using this key right now.
                    </div>
                ) : (
                    <div className="overflow-x-auto">
                        <table className="w-full text-left border-collapse">
                            <thead>
                                <tr className="border-b border-slate-800 text-[10px] font-bold uppercase tracking-wider text-slate-500">
                                    <th className="px-5 py-3">Website</th>
                                    <th className="px-5 py-3">Domain</th>
                                    <th className="px-5 py-3">Status</th>
                                    <th className="px-5 py-3 text-right">Action</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-slate-800/60 text-sm text-slate-300">
                                {activeAgents.map((agent) => (
                                    <tr key={agent.id} className="hover:bg-slate-900/30">
                                        <td className="px-5 py-3 font-semibold text-white">{agent.site_name}</td>
                                        <td className="px-5 py-3 font-mono text-xs text-slate-400">{agent.domain}</td>
                                        <td className="px-5 py-3">
                                            <span
                                                className={`inline-flex rounded-md border px-2 py-0.5 text-[10px] font-bold uppercase ${statusBadgeClass(agent.status)}`}
                                            >
                                                {agent.status.replace(/_/g, ' ')}
                                            </span>
                                        </td>
                                        <td className="px-5 py-3 text-right">
                                            <Link
                                                to={PANEL_ROUTES.website(agent.id)}
                                                className="inline-flex items-center gap-1.5 rounded-lg border border-slate-800 px-3 py-1.5 text-xs font-semibold text-slate-300 hover:border-rose-500/30 hover:text-white"
                                            >
                                                <ExternalLink className="w-3.5 h-3.5" />
                                                Open Website
                                            </Link>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                )}
            </section>

            {releasedAgents.length > 0 ? (
                <section className="rounded-2xl border border-slate-800 bg-slate-900/40 overflow-hidden">
                    <div className="border-b border-slate-800 px-5 py-4">
                        <h4 className="text-sm font-bold text-white">Released Domains ({releasedAgents.length})</h4>
                        <p className="mt-1 text-xs text-slate-500">
                            Disconnected or deleted websites that no longer consume a quota slot.
                        </p>
                    </div>
                    <div className="overflow-x-auto">
                        <table className="w-full text-left border-collapse">
                            <thead>
                                <tr className="border-b border-slate-800 text-[10px] font-bold uppercase tracking-wider text-slate-500">
                                    <th className="px-5 py-3">Website</th>
                                    <th className="px-5 py-3">Domain</th>
                                    <th className="px-5 py-3">Released</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-slate-800/60 text-sm text-slate-300">
                                {releasedAgents.map((agent) => (
                                    <tr key={agent.id} className="hover:bg-slate-900/30">
                                        <td className="px-5 py-3 font-semibold text-white">{agent.site_name}</td>
                                        <td className="px-5 py-3 font-mono text-xs text-slate-400">{agent.domain}</td>
                                        <td className="px-5 py-3 text-xs text-slate-500">
                                            {agent.released_at
                                                ? new Date(agent.released_at).toLocaleString()
                                                : '—'}
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                </section>
            ) : null}

            <div className="rounded-2xl border border-slate-800/80 bg-slate-950/40 px-5 py-4 text-xs text-slate-500">
                <Globe className="mb-2 h-4 w-4 text-slate-600" />
                Quota counts only active registrations. Disconnect or delete a website to free a slot for reconnecting
                with this key.
            </div>
        </div>
    );
}
