import { Loader2, Send, Sparkles } from 'lucide-react';
import React, { useState } from 'react';
import { apiFetch } from '@/lib/loading/api-fetch';
import { useMetaAiSuggestions } from '../hooks/use-meta-ai-suggestions';
import { MetaComment } from '../types';

const TLL_LOGO = '/creatorsLogo/thelandlord.png';

const AVATAR_COLORS = [
    'bg-blue-500', 'bg-green-500', 'bg-purple-500', 'bg-pink-500',
    'bg-indigo-500', 'bg-teal-500', 'bg-orange-500', 'bg-cyan-500',
    'bg-rose-500', 'bg-emerald-500', 'bg-violet-500', 'bg-amber-500',
];

const nameToColor = (name: string) => {
    let hash = 0;
    for (let i = 0; i < name.length; i++) hash = name.charCodeAt(i) + ((hash << 5) - hash);
    return AVATAR_COLORS[Math.abs(hash) % AVATAR_COLORS.length];
};

export const timeAgo = (d?: string | null) => {
    if (!d) return '';
    const diff = Date.now() - new Date(d).getTime();
    const mins = Math.floor(diff / 60000);
    if (mins < 1) return "À l'instant";
    if (mins < 60) return `${mins} min`;
    const hours = Math.floor(mins / 60);
    if (hours < 24) return `${hours} h`;
    const days = Math.floor(hours / 24);
    if (days < 7) return `${days} j`;
    return new Date(d).toLocaleDateString('fr-FR', { day: 'numeric', month: 'short' });
};

interface Props {
    comment: MetaComment;
    platform: 'facebook' | 'instagram';
    depth?: number;
    postCaption?: string;
}

export const CommentItem: React.FC<Props> = ({ comment, platform, depth = 0, postCaption }) => {
    const [replyText, setReplyText] = useState('');
    const [showReplyInput, setShowReplyInput] = useState(false);
    const [sending, setSending] = useState(false);
    const [replies, setReplies] = useState<MetaComment[]>(comment.replies ?? []);
    const [loadingReplies, setLoadingReplies] = useState(false);
    const [repliesLoaded, setRepliesLoaded] = useState((comment.replies ?? []).length > 0);

    const { suggestions: aiSuggestions, setSuggestions: setAiSuggestions, loading: loadingAi, fetchSuggestions } = useMetaAiSuggestions();

    const loadReplies = async () => {
        if (platform !== 'facebook' || repliesLoaded) return;
        setLoadingReplies(true);
        try {
            const res = await apiFetch(`/meta/facebook/comments/${comment.id}/replies`);
            if (res.ok) {
                setReplies(await res.json());
                setRepliesLoaded(true);
            }
        } catch { /* ignore */ }
        setLoadingReplies(false);
    };

    const sendReply = async () => {
        const text = replyText.trim();
        if (!text || sending) return;
        setSending(true);
        try {
            const url = platform === 'facebook'
                ? `/meta/facebook/comments/${comment.id}/reply`
                : `/meta/instagram/comments/${comment.id}/reply`;
            const res = await apiFetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ?? '',
                },
                body: JSON.stringify({ message: text }),
            });
            if (res.ok) {
                const data = await res.json();
                setReplies((prev) => [...prev, {
                    id: data.id ?? 'temp_' + Date.now(),
                    message: text,
                    from_name: 'The Landlord',
                    created_time: new Date().toISOString(),
                    is_page: true,
                }]);
                setReplyText('');
                setShowReplyInput(false);
            }
        } catch { /* ignore */ }
        setSending(false);
    };

    const initial = (comment.from_name ?? '?').replace('@', '')[0]?.toUpperCase() ?? '?';
    const avatarColor = nameToColor(comment.from_id ?? comment.id ?? comment.from_name ?? '');

    return (
        <div className={`${depth > 0 ? 'ml-10' : ''} mb-1`}>
            <div className="flex items-start gap-2">
                {/* Avatar */}
                {comment.is_page ? (
                    <div className="mt-0.5 flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full bg-[#2c3e50]">
                        <img src={TLL_LOGO} alt="TLL" className="h-5 w-5 object-contain" />
                    </div>
                ) : comment.profile_picture ? (
                    <img src={comment.profile_picture} alt={comment.from_name} className="mt-0.5 h-8 w-8 flex-shrink-0 rounded-full object-cover" />
                ) : (
                    <div className={`mt-0.5 flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full text-xs font-bold text-white ${avatarColor}`}>
                        {initial}
                    </div>
                )}
                {/* Bubble */}
                <div className="flex-1 min-w-0">
                    <div className="inline-block rounded-2xl bg-[#f0f2f5] px-3 py-2" style={{ maxWidth: '100%' }}>
                        <span className="text-[13px] font-semibold text-gray-900">{comment.from_name}</span>
                        <p className="text-[13px] text-gray-800 whitespace-pre-wrap leading-snug">{comment.message}</p>
                    </div>
                    {/* Actions row */}
                    <div className="flex items-center gap-3 px-2 py-0.5">
                        <span className="text-[11px] text-gray-500">{timeAgo(comment.created_time)}</span>
                        {depth === 0 && (
                            <button
                                className="text-[12px] font-semibold text-gray-500 hover:underline"
                                onClick={() => setShowReplyInput(!showReplyInput)}
                            >
                                Répondre
                            </button>
                        )}
                    </div>
                </div>
            </div>

            {/* Load sub-replies link (FB only) */}
            {depth === 0 && platform === 'facebook' && (comment.reply_count ?? 0) > 0 && !repliesLoaded && (
                <button
                    className="ml-12 mt-0.5 mb-1 text-[12px] font-semibold text-gray-500 hover:underline"
                    onClick={loadReplies}
                    disabled={loadingReplies}
                >
                    {loadingReplies ? 'Chargement...' : `Voir ${comment.reply_count} réponse(s)`}
                </button>
            )}

            {/* Replies */}
            {replies.length > 0 && (
                <div className="mt-0.5">
                    {replies.map((r) => (
                        <CommentItem key={r.id} comment={r} platform={platform} depth={1} />
                    ))}
                </div>
            )}

            {/* Reply input (inline, under comment) */}
            {showReplyInput && depth === 0 && (
                <div className="ml-12 mt-1 mb-2">
                    {/* AI suggestions */}
                    {aiSuggestions.length > 0 && (
                        <div className="mb-1.5 flex flex-col gap-1">
                            {aiSuggestions.map((s, i) => (
                                <button
                                    key={i}
                                    className="rounded-lg border border-purple-200 bg-purple-50 px-3 py-1.5 text-left text-[12px] text-purple-800 transition-colors hover:bg-purple-100"
                                    onClick={() => { setReplyText(s); setAiSuggestions([]); }}
                                >
                                    <Sparkles className="mr-1 inline h-3 w-3 text-purple-500" />
                                    {s}
                                </button>
                            ))}
                        </div>
                    )}
                    <div className="flex items-center gap-2">
                        <div className="flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-full bg-[#2c3e50]">
                            <img src={TLL_LOGO} alt="TLL" className="h-4 w-4 object-contain" />
                        </div>
                        <div className="flex flex-1 items-center rounded-full bg-[#f0f2f5] px-3 py-1.5">
                            <input
                                className="flex-1 bg-transparent text-[13px] placeholder:text-gray-400 focus:outline-none"
                                placeholder="Répondre..."
                                value={replyText}
                                onChange={(e) => setReplyText(e.target.value)}
                                onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); sendReply(); } }}
                                autoFocus
                            />
                            <button
                                className="ml-1 text-purple-500 hover:text-purple-700 disabled:text-gray-300"
                                onClick={() => fetchSuggestions({ comment: comment.message, postCaption: postCaption ?? '', platform })}
                                disabled={loadingAi}
                                title="Générer des suggestions IA"
                            >
                                {loadingAi ? <Loader2 className="h-4 w-4 animate-spin" /> : <Sparkles className="h-4 w-4" />}
                            </button>
                            <button
                                className="ml-1 text-[#1877f2] disabled:text-gray-300"
                                onClick={sendReply}
                                disabled={!replyText.trim() || sending}
                            >
                                <Send className="h-4 w-4" />
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};
