import { ExternalLink, Loader2, MessageCircle, Send, Share2, Sparkles, ThumbsUp } from 'lucide-react';
import React, { useEffect, useRef, useState } from 'react';
import { apiFetch } from '@/lib/loading/api-fetch';
import { Pending } from '@/components/ui/pending';
import { CommentItem, timeAgo } from './components/CommentItem';
import { useMetaAiSuggestions } from './hooks/use-meta-ai-suggestions';
import { Discussion, MetaComment } from './types';

const TLL_LOGO = '/creatorsLogo/thelandlord.png';
const FACEBOOK_LOGO = '/facebook.png';
const INSTAGRAM_LOGO = '/instagram.png';

interface Props {
    discussion: Discussion | null;
}

// ── Main component — Facebook post card ──────────────────────────────

const CommentsView: React.FC<Props> = ({ discussion }) => {
    const [comments, setComments] = useState<MetaComment[]>([]);
    const [loading, setLoading] = useState(false);
    const [replyText, setReplyText] = useState('');
    const [sending, setSending] = useState(false);
    const commentsEndRef = useRef<HTMLDivElement>(null);

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

    const isFb = discussion?.communication_channel === 'facebook_comment';
    const platform = isFb ? 'facebook' : 'instagram';

    useEffect(() => {
        if (!discussion?.meta_post_id) { setComments([]); return; }
        setLoading(true);
        setComments([]);

        const url = isFb
            ? `/meta/facebook/posts/${discussion.meta_post_id}/comments`
            : `/meta/instagram/media/${discussion.meta_post_id}/comments`;

        apiFetch(url)
            .then((r) => r.json())
            .then(setComments)
            .catch(() => setComments([]))
            .finally(() => setLoading(false));
    }, [discussion?.meta_post_id]);

    const sendTopLevelComment = async () => {
        const text = replyText.trim();
        if (!text || sending || !discussion?.meta_post_id) return;
        setSending(true);
        try {
            const url = isFb
                ? `/meta/facebook/comments/${discussion.meta_post_id}/reply`
                : `/meta/instagram/comments/${discussion.meta_post_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();
                setComments((prev) => [...prev, {
                    id: data.id ?? 'temp_' + Date.now(),
                    message: text,
                    from_name: 'The Landlord',
                    created_time: new Date().toISOString(),
                    is_page: true,
                }]);
                setReplyText('');
                setTimeout(() => commentsEndRef.current?.scrollIntoView({ behavior: 'smooth' }), 100);
            }
        } catch { /* ignore */ }
        setSending(false);
    };

    if (!discussion) {
        return (
            <div className="flex flex-1 items-center justify-center overflow-hidden rounded-xl bg-[#f0f2f5]">
                <p className="text-sm text-gray-400">Sélectionnez une publication</p>
            </div>
        );
    }

    return (
        <div className="flex flex-1 flex-col overflow-hidden rounded-xl bg-[#f0f2f5]">
            <div className="flex-1 overflow-y-auto">
                {/* ── Facebook-style post card ─────────────────────────── */}
                <div className="mx-auto max-w-[680px] mt-3">
                    <div className="rounded-lg bg-white shadow-sm">
                        {/* Post header */}
                        <div className="flex items-center gap-3 px-4 pt-3 pb-2">
                            <img src={TLL_LOGO} alt="TLL" className="h-10 w-10 flex-shrink-0 rounded-full bg-[#2c3e50] object-contain p-1" />
                            <div className="flex-1 min-w-0">
                                <div className="flex items-center gap-2">
                                    <span className="text-[15px] font-semibold text-gray-900">The Landlord</span>
                                    {discussion.meta_permalink && (
                                        <a href={discussion.meta_permalink} target="_blank" rel="noopener noreferrer" className="text-gray-400 hover:text-gray-600">
                                            <ExternalLink className="h-3.5 w-3.5" />
                                        </a>
                                    )}
                                </div>
                                <span className="text-[12px] text-gray-500">{timeAgo(discussion.last_message_date)}</span>
                            </div>
                            <img
                                src={isFb ? FACEBOOK_LOGO : INSTAGRAM_LOGO}
                                alt={isFb ? 'Facebook' : 'Instagram'}
                                className="h-6 w-6 flex-shrink-0 rounded"
                            />
                        </div>

                        {/* Post text */}
                        {discussion.meta_message && (
                            <div className="px-4 pb-2">
                                <p className="text-[15px] text-gray-900 leading-snug whitespace-pre-wrap">{discussion.meta_message}</p>
                            </div>
                        )}

                        {/* Post media (image or video) — square aspect ratio */}
                        {discussion.meta_media_type === 'VIDEO' && discussion.meta_video_url ? (
                            <div className="relative w-full bg-black" style={{ aspectRatio: '1 / 1' }}>
                                <video
                                    src={discussion.meta_video_url}
                                    poster={discussion.meta_picture ?? undefined}
                                    controls
                                    playsInline
                                    preload="metadata"
                                    className="absolute inset-0 h-full w-full object-contain"
                                />
                            </div>
                        ) : discussion.meta_picture ? (
                            <div className="relative w-full" style={{ aspectRatio: '1 / 1' }}>
                                <img
                                    src={discussion.meta_picture}
                                    alt="Post"
                                    className="absolute inset-0 h-full w-full object-cover"
                                />
                            </div>
                        ) : null}

                        {/* Reactions bar */}
                        <div className="flex items-center justify-between px-4 py-2 text-[13px] text-gray-500">
                            <span></span>
                            <span>{discussion.meta_comments_count ?? 0} commentaire(s)</span>
                        </div>

                        {/* Action buttons */}
                        <div className="mx-4 flex items-center justify-around border-t border-b border-gray-200 py-1">
                            <button className="flex flex-1 items-center justify-center gap-1.5 rounded-md py-1.5 text-[14px] font-semibold text-gray-500 hover:bg-gray-100">
                                <ThumbsUp className="h-4 w-4" /> J'aime
                            </button>
                            <button className="flex flex-1 items-center justify-center gap-1.5 rounded-md py-1.5 text-[14px] font-semibold text-gray-500 hover:bg-gray-100">
                                <MessageCircle className="h-4 w-4" /> Commenter
                            </button>
                            <button className="flex flex-1 items-center justify-center gap-1.5 rounded-md py-1.5 text-[14px] font-semibold text-gray-500 hover:bg-gray-100">
                                <Share2 className="h-4 w-4" /> Partager
                            </button>
                        </div>

                        {/* ── Comments section ────────────────────────── */}
                        <Pending pending={loading} className="px-4 py-3">
                            {comments.length === 0 ? (
                                !loading && <p className="text-center text-sm text-gray-400 py-4">Aucun commentaire.</p>
                            ) : (
                                comments.map((c) => (
                                    <CommentItem key={c.id} comment={c} platform={platform} postCaption={discussion.meta_message ?? ''} />
                                ))
                            )}
                            <div ref={commentsEndRef} />
                        </Pending>

                        {/* ── Bottom reply input (always visible) ─────── */}
                        <div className="sticky bottom-0 border-t border-gray-200 bg-white px-4 py-3">
                            {/* AI suggestions */}
                            {aiSuggestions.length > 0 && (
                                <div className="mb-2 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-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>
                                <div className="flex flex-1 items-center rounded-full bg-[#f0f2f5] px-3 py-2">
                                    <input
                                        className="flex-1 bg-transparent text-[14px] placeholder:text-gray-400 focus:outline-none"
                                        placeholder="Commenter en tant que The Landlord..."
                                        value={replyText}
                                        onChange={(e) => setReplyText(e.target.value)}
                                        onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); sendTopLevelComment(); } }}
                                    />
                                    <button
                                        className="ml-1 text-purple-500 hover:text-purple-700 disabled:text-gray-300"
                                        onClick={() => fetchSuggestions({
                                            comment: comments.length > 0 ? comments[comments.length - 1].message : '',
                                            postCaption: discussion.meta_message ?? '',
                                            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={sendTopLevelComment}
                                        disabled={!replyText.trim() || sending}
                                    >
                                        <Send className="h-4 w-4" />
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default CommentsView;
