// src/app/contact/page.tsx
"use client";

import React, { useEffect, useState } from "react";
// import Image from "next/image";
import { useRouter } from "next/navigation";
import { X, RefreshCw } from "react-feather"
import { useToast } from "@/components/ui/ToastContext";
// import ErrorMessages from "@/constants/ErrorMessage";
import AutoDmHeader from "@/components/AutoDmHeader";
import apiClient from "@/lib/apiClient";

import { useAppDispatch, useAppSelector } from "@/hooks/useAppDispatch";
import { fetchConnectionStatus, fetchInstaPosts } from "@/features/autoDm/autoDmThunk";
import { selectPost, resetCampaignData, disconnectInstagram } from "@/features/autoDm/autoDmSlice";
import { logger } from "@/lib/logger";
import GlobalLoadingOverlay from "@/components/ui/GlobalLoadingOverlay";

export default function AutoDmHome() {
    const showToast = useToast();
    const router = useRouter();
    const dispatch = useAppDispatch();

    // State for disconnect confirmation modal
    const [showDisconnectConfirmation, setShowDisconnectConfirmation] = useState(false);
    const [isDisconnecting, setIsDisconnecting] = useState(false);
    const [isPageLoading, setIsPageLoading] = useState(false);
    const [isNavigating, setIsNavigating] = useState(false);

    // Show disconnect confirmation modal
    const handleDisconnectClick = () => {
        setShowDisconnectConfirmation(true);
    }

    // Handle refresh posts
    const handleRefreshPosts = () => {
        if (connected) {
            setIsPageLoading(true);
            dispatch(fetchInstaPosts(true))
                .finally(() => setIsPageLoading(false));
        }
    }

    // Handle actual Instagram disconnection
    const handleDisconnectInstagram = async () => {
        try {
            setIsDisconnecting(true);
            const response = await apiClient.get('/ig/disconnect');

            if (response.data.success) {
                // Clear all Instagram data from Redux and localStorage
                dispatch(disconnectInstagram());
                showToast("Your Instagram account has been disconnected.");
                setShowDisconnectConfirmation(false);
                // Redirect to connect Instagram page
                router.push('/auto-dm/step-1');
            } else {
                showToast("Unable to disconnect right now. Please try again.");
            }
        } catch (error) {
            logger.error("Failed to disconnect Instagram:", error);
            showToast("Unable to disconnect right now. Please try again.");
        } finally {
            setIsDisconnecting(false);
        }
    }

    // Close disconnect confirmation modal
    const closeDisconnectConfirmation = () => {
        setShowDisconnectConfirmation(false);
    }

    const {
        connected,
        loading,
        username,  // ← from fetchConnectionStatus
        ig_posts,
        selectedPost
    } = useAppSelector((state) => state.autoDm);

    // Initialize component state
    useEffect(() => {
        // Reset campaign data when user returns to step-1 (fresh start)
        // This preserves connection status from persisted state
        dispatch(resetCampaignData());
    }, [dispatch]);

    // Check connection status and fetch posts with token validation
    useEffect(() => {
        // Check if we have a valid access token
        const hasValidToken = typeof window !== 'undefined' && localStorage.getItem('access_token');
        
        if (!hasValidToken) {
            // No token, redirect to login
            router.replace("/");
            return;
        }

        // If we have persisted connection data, use it and fetch posts if needed
        if (connected === true) {
            if (ig_posts.length === 0) {
                setIsPageLoading(true);
                dispatch(fetchInstaPosts())
                    .finally(() => setIsPageLoading(false));
            }
            return;
        }

        // If no connection data, fetch fresh connection status
        if (connected === undefined) {
            setIsPageLoading(true);
            dispatch(fetchConnectionStatus())
                .then((result) => {
                    // If connection is successful, immediately fetch posts
                    if (result.payload && typeof result.payload === 'object' && 'connected' in result.payload && result.payload.connected === true) {
                        return dispatch(fetchInstaPosts());
                    }
                })
                .finally(() => setIsPageLoading(false));
        }
    }, [connected, dispatch, ig_posts.length, router]);

    // 3) Once the status check completes, if still not connected → redirect
    useEffect(() => {
        if (!loading && connected === false) {
            router.replace("/auto-dm");
        }
    }, [loading, connected, router]);

    // // 4 While loading or redirecting, render a spinner or nothing
    // if (loading || !connected) {
    //     return (
    //         <div className="pcoded-main-container">
    //             <div className="pcoded-content text-center py-20">
    //                 <p className="text-xl">Verifying Instagram connection…</p>
    //             </div>
    //         </div>
    //     );
    // }

    // const handleClick = (e: React.MouseEvent) => {
    //     if (!selectedPost) {
    //         // prevent navigation when "disabled"
    //         e.preventDefault();
    //         return;
    //     }
    //     // do your push
    //     router.push("/auto-dm/step-2");
    // };

    return (
        <div className="pcoded-main-container bg-light webContent ">
            <GlobalLoadingOverlay show={isNavigating } />
            <div className="pcoded-content">
                <AutoDmHeader
                    currentStep={1}
                    totalSteps={4}
                    username={username || ""}
                    connected={connected}
                    onDisconnect={handleDisconnectClick}
                    onNext={() => {
                        setIsNavigating(true);
                        // No API calls on navigation, so we can use intentional delay
                        setTimeout(() => {
                            router.push("/auto-dm/step-2");
                        }, 300);
                    }}
                    nextDisabled={!selectedPost || !ig_posts || ig_posts.length === 0}
                    showSetupHistory={true}
                    onSetupClick={() => {/* Handle setup click */ }}
                    onHistoryClick={() => router.push("/auto-dm/history")}
                    isLoading={isPageLoading || isNavigating}
                />

                <div className="row my-3">
                    <div className="col-xxl-12 col-xl-12 col-lg-12 col-md-12 col-12 mb-3">
                        <div className="card performance-card m-0 mb-3 h-auto">
                            <div className="card-body platform-cards auto-dm-posts h-auto">
                                <div className="d-flex justify-content-between align-items-center mb-3 mt-2">
                                    <p className="mb-0">Select your post</p>
                                    <button
                                        type="button"
                                        className="btn btn-outline-secondary btn-sm d-flex align-items-center gap-2"
                                        onClick={handleRefreshPosts}
                                        disabled={isPageLoading || !connected}
                                        style={{ borderRadius: '8px' }}
                                    >
                                        <RefreshCw size={16} />
                                        Refresh Posts
                                    </button>
                                </div>
                                {loading || isPageLoading ? (
                                    <div className="text-center py-5">
                                        <div className="mb-3">
                                            <div 
                                                className="spinner-border color-first" 
                                                role="status"
                                                style={{ width: '3rem', height: '3rem' }}
                                            >
                                                <span className="visually-hidden">Loading...</span>
                                            </div>
                                        </div>
                                        <h5 className="text-muted mb-2">Loading Posts...</h5>
                                        <p className="text-muted mb-0">
                                            Fetching your Instagram posts...
                                        </p>
                                    </div>
                                ) : ig_posts && ig_posts.length > 0 ? (
                                    <div className="row row-cols-3 row-cols-md-5 row-cols-lg-6 g-1 g-md-3">
                                        {ig_posts.map((post) => (
                                            <div className="col" key={post.id}>
                                                <label className="custom-checkbox-label">
                                                    <input
                                                        type="radio"
                                                        name="post"
                                                        className="custom-checkbox"
                                                        checked={selectedPost?.id === post.id}
                                                        onChange={() => dispatch(selectPost(post))}
                                                    />
                                                    <span className="checkmark"></span>
                                                    <img
                                                        src={post.media_type === "VIDEO" ? post.thumbnail_url : post.media_url}
                                                        alt={post?.caption || "Instagram post"}
                                                        width={158}
                                                        height={160}
                                                        className="img-fluid"
                                                    />
                                                    <span className="after-overlay"></span>
                                                </label>
                                            </div>
                                        ))}
                                    </div>
                                ) : (
                                    <div className="text-center py-5">
                                        <div className="mb-3">
                                            <svg width="64" height="64" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" className="color-first">
                                                <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z" fill="currentColor"/>
                                            </svg>
                                        </div>
                                        <h5 className="text-muted mb-2">No Active Posts Available</h5>
                                        <p className="text-muted mb-0">
                                            We couldn&apos;t find any posts from your Instagram account. 
                                            <br />
                                            Make sure you have published posts and try refreshing the page.
                                        </p>
                                        {/* <button 
                                            className="btn btn-outline-primary color-first mt-3"
                                            onClick={() => window.location.reload()}
                                        >
                                            Refresh Posts
                                        </button> */}
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>
                </div>

                {/* Disconnect Instagram Confirmation Modal */}
                {showDisconnectConfirmation && (
                    <>
                        {/* Backdrop */}
                        <div
                            className="modal-backdrop fade show"
                            style={{
                                position: 'fixed',
                                top: 0,
                                left: 0,
                                width: '100vw',
                                height: '100vh',
                                backgroundColor: 'rgba(0, 0, 0, 0.5)',
                                zIndex: 1040,
                                cursor: isDisconnecting ? "not-allowed" : "pointer",
                            }}
                            onClick={() => { if (!isDisconnecting) closeDisconnectConfirmation() }}
                            title="Click outside to close"
                        />

                        {/* Modal */}
                        <section
                            className="modal fade my-modal show d-block"
                            style={{
                                position: 'fixed',
                                top: 0,
                                left: 0,
                                width: '100vw',
                                height: '100vh',
                                zIndex: 1050
                            }}
                            aria-hidden="false"
                            onClick={() => { if (!isDisconnecting) closeDisconnectConfirmation(); }}
                        >
                            <div className="modal-dialog modal-dialog-centered" onClick={(e) => e.stopPropagation()}>
                                <div className="modal-content" onClick={(e) => e.stopPropagation()}>
                                    <div className="modal-body text-center p-3">
                                        <div className="modal-name mb-0 d-flex justify-content-end">
                                            <button
                                                type="button"
                                                className="btn-close"
                                                onClick={closeDisconnectConfirmation}
                                                aria-label="Close"
                                                disabled={isDisconnecting}
                                            >
                                                <X size={20} />
                                            </button>
                                        </div>
                                        <h4 className="mb-3">Disconnect Instagram?</h4>
                                        <p className="px-2 mb-4">
                                            This will stop Auto-DM functionality until you reconnect.
                                        </p>

                                        <div className="d-flex gap-2 justify-content-center">
                                            <button
                                                type="button"
                                                className="btn btn-secondary"
                                                onClick={closeDisconnectConfirmation}
                                                disabled={isDisconnecting}
                                            >
                                                Cancel
                                            </button>
                                            <button
                                                type="button"
                                                className="btn btn-danger"
                                                onClick={handleDisconnectInstagram}
                                                disabled={isDisconnecting}
                                            >
                                                {isDisconnecting ? "Disconnecting..." : "Disconnect"}
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </section>
                    </>
                )}
            </div>
        </div>
    );
}
