import React, { useEffect, useState } from 'react';
import { FiInfo, FiCheck, FiX, FiPlus, FiMinus } from 'react-icons/fi';
import styles from '../features/chatbot/components/ChatbotSettings.module.css';

// Import images
import emptyBox from "../assets/images/empty_box.png";
import supportTeam from "../assets/images/support_team.png";
import allApis from 'app/utils/api';
import { useGlobalContext } from 'app/components/providers/global-context';

export default function SubscriptionPage() {
    const { agent } = useGlobalContext();
    const [billingCycle, setBillingCycle] = useState('monthly');
    const [openFaq, setOpenFaq] = useState<number | null>(0);
    const [plans, setPlans] = useState<any[]>([]);
    const [activeSubscription, setActiveSubscription] = useState<any>(null);
    const [isLoading, setIsLoading] = useState(true);

    const loadData = async () => {
        if (!agent?.workspace_id) return;
        setIsLoading(true);
        try {
            const [plansRes, activeRes] = await Promise.all([
                allApis.Subscriptions.getAllPlans(),
                allApis.Subscriptions.getActiveSubscription(agent.workspace_id)
            ]);
            console.log("plansRes", plansRes);
            console.log("activeRes", activeRes);
            setPlans(plansRes.data || plansRes || []);
            setActiveSubscription(activeRes.data || activeRes);
        } catch (error) {
            console.error("Error loading subscription data:", error);
        } finally {
            setIsLoading(false);
        }
    };

    useEffect(() => {
        loadData();
    }, [agent?.workspace_id]);

    const handlePurchase = async (plan: any) => {
        try {
            const payload = {
                subscription_plan_id: plan._id,
                workspace_id: agent?.workspace_id,
                plan_id: plan.plan_id
            };
            const res = await allApis.Subscriptions.purchaseSubscription(payload);
            const paymentLink = res?.payment_link || res?.data?.payment_link;
            if (paymentLink) {
                window.open(paymentLink, "_blank");
            }
        } catch (error) {
            console.error("Purchase error:", error);
        }
    };

    const faqs = [
        { q: 'Can I cancel my subscription at any time?', a: 'Yes, you can! For Chatty, we believe in giving you flexibility and control over your subscription. You can cancel your subscription at any time, and there will be no charge for the first 7 days after your free trial. We want to ensure that you have the freedom to choose what works best for you.' },
        { q: 'If I cancel the paid plans, will I lose the features or effects that were available in the previous Standard Plan?', a: 'Yes, if you cancel a paid plan, your account will eventually revert to the Free plan, and features specific to paid plans will be disabled.' },
        { q: 'Is it easy to switch between plans?', a: 'Absolutely. You can upgrade or downgrade your plan at any time from your subscription settings.' },
        { q: 'Can I have a refund?', a: 'Our policy general follows the rules of the platform, but please reach out to our support team if you have specific concerns.' },
        { q: 'When will I get charged after the trial ends?', a: 'You will be charged the plan amount immediately after your 7-day free trial ends, unless you cancel before then.' }
    ];

    // if (isLoading) {
    //     return <div style={{ padding: '32px' }}>Loading...</div>;
    // }

    return (
        <div className={styles.inboxContainer} style={{ background: '#f9fafb', minHeight: '100vh', display: 'flex', flexDirection: 'column', gap: '32px' }}>
            <h1 style={{ fontSize: '24px', fontWeight: 700 }}>Subscription</h1>

            {/* Subscription details */}
            <div className={styles.appearanceCard} style={{ padding: '32px' }}>
                <h3 style={{ fontSize: '16px', fontWeight: 600, marginBottom: '8px' }}>Subscription details</h3>
                <p style={{ fontSize: '14px', color: '#6b7280', marginBottom: '32px' }}>Information related to your current subscription.</p>

                <div style={{ background: '#f5f3ff', borderRadius: '16px', padding: '24px', marginBottom: '32px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <div>
                        <span style={{ fontSize: '13px', color: '#6b7280' }}>Current plan</span>
                        <h2 style={{ fontSize: '24px', fontWeight: 700, marginTop: '8px' }}>{activeSubscription?.plan?.name || 'Free'}</h2>
                    </div>
                    <div style={{ textAlign: 'right' }}>
                        <h2 style={{ fontSize: '24px', fontWeight: 700 }}>${activeSubscription?.plan?.amount || 0}</h2>
                        <span style={{ fontSize: '13px', color: '#6b7280' }}>per month</span>
                    </div>
                </div>

                {/* AI Conversation Usage */}
                <div style={{ marginBottom: '24px' }}>
                    <div style={{ marginBottom: '8px', display: 'flex', justifyContent: 'space-between' }}>
                        <span style={{ fontSize: '14px', fontWeight: 600 }}>AI conversation</span>
                        <span style={{ fontSize: '12px', color: '#6b7280' }}>{activeSubscription?.chat_token_limit_left || 0} / {activeSubscription?.benifites?.chat_token_limit || 0}</span>
                    </div>
                    <div style={{ width: '100%', height: '8px', background: '#f3f4f6', borderRadius: '4px', overflow: 'hidden' }}>
                        <div style={{ 
                            width: `${Math.min(100, ((activeSubscription?.chat_token_limit_left || 0) / (activeSubscription?.benifites?.chat_token_limit || 1)) * 100)}%`, 
                            height: '100%', 
                            background: '#7c3aed' 
                        }} />
                    </div>
                </div>

                {/* Agents Usage */}
                <div style={{ marginBottom: '24px' }}>
                    <div style={{ marginBottom: '8px', display: 'flex', justifyContent: 'space-between' }}>
                        <span style={{ fontSize: '14px', fontWeight: 600 }}>Agents</span>
                        <span style={{ fontSize: '12px', color: '#6b7280' }}>{activeSubscription?.agent_limit_left || 0} / {activeSubscription?.benifites?.agent_limit || 0}</span>
                    </div>
                    <div style={{ width: '100%', height: '8px', background: '#f3f4f6', borderRadius: '4px', overflow: 'hidden' }}>
                        <div style={{ 
                            width: `${Math.min(100, ((activeSubscription?.agent_limit_left || 0) / (activeSubscription?.benifites?.agent_limit || 1)) * 100)}%`, 
                            height: '100%', 
                            background: '#10b981' 
                        }} />
                    </div>
                </div>

                {/* Knowledgebase Usage */}
                <div style={{ marginBottom: '24px' }}>
                    <div style={{ marginBottom: '8px', display: 'flex', justifyContent: 'space-between' }}>
                        <span style={{ fontSize: '14px', fontWeight: 600 }}>Knowledgebase</span>
                        <span style={{ fontSize: '12px', color: '#6b7280' }}>{activeSubscription?.knowledgebase_limit_left || 0} / {activeSubscription?.benifites?.knowledgebase_limit || 0}</span>
                    </div>
                    <div style={{ width: '100%', height: '8px', background: '#f3f4f6', borderRadius: '4px', overflow: 'hidden' }}>
                        <div style={{ 
                            width: `${Math.min(100, ((activeSubscription?.knowledgebase_limit_left || 0) / (activeSubscription?.benifites?.knowledgebase_limit || 1)) * 100)}%`, 
                            height: '100%', 
                            background: '#3b82f6' 
                        }} />
                    </div>
                </div>

                {/* Workspace Members Usage */}
                <div>
                    <div style={{ marginBottom: '8px', display: 'flex', justifyContent: 'space-between' }}>
                        <span style={{ fontSize: '14px', fontWeight: 600 }}>Workspace Members</span>
                        <span style={{ fontSize: '12px', color: '#6b7280' }}>{activeSubscription?.workspace_member_limit_left || 0} / {activeSubscription?.benifites?.workspace_member_limit || 0}</span>
                    </div>
                    <div style={{ width: '100%', height: '8px', background: '#f3f4f6', borderRadius: '4px', overflow: 'hidden' }}>
                        <div style={{ 
                            width: `${Math.min(100, ((activeSubscription?.workspace_member_limit_left || 0) / (activeSubscription?.benifites?.workspace_member_limit || 1)) * 100)}%`, 
                            height: '100%', 
                            background: '#f59e0b' 
                        }} />
                    </div>
                </div>
            </div>

            {/* Billing summary */}
            <div className={styles.appearanceCard} style={{ padding: '32px' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '8px' }}>
                    <h3 style={{ fontSize: '16px', fontWeight: 600 }}>AI conversation billing summary</h3>
                    <FiInfo size={16} color="#6b7280" />
                </div>
                <p style={{ fontSize: '14px', color: '#6b7280', marginBottom: '40px' }}>Track your AI conversations usage and related charges for each billing cycle.</p>

                <div style={{ textAlign: 'center', padding: '40px 0' }}>
                    <img src={emptyBox} alt="No usage" style={{ width: '150px', marginBottom: '24px' }} />
                    <p style={{ color: '#9ca3af', fontSize: '14px' }}>No usage charges found</p>
                </div>
            </div>

            {/* Pricing Toggle */}
            <div style={{ display: 'flex', justifyContent: 'center', marginBottom: '16px' }}>
                <div style={{ background: '#f3f4f6', borderRadius: '30px', padding: '4px', display: 'flex', alignItems: 'center' }}>
                    <button
                        onClick={() => setBillingCycle('monthly')}
                        style={{
                            padding: '8px 24px',
                            borderRadius: '24px',
                            border: 'none',
                            fontSize: '14px',
                            fontWeight: 600,
                            background: billingCycle === 'monthly' ? '#7c3aed' : 'transparent',
                            color: billingCycle === 'monthly' ? 'white' : '#6b7280',
                            cursor: 'pointer'
                        }}
                    >
                        Monthly
                    </button>
                    <button
                        onClick={() => setBillingCycle('yearly')}
                        style={{
                            padding: '8px 24px',
                            borderRadius: '24px',
                            border: 'none',
                            fontSize: '14px',
                            fontWeight: 600,
                            background: billingCycle === 'yearly' ? '#7c3aed' : 'transparent',
                            color: billingCycle === 'yearly' ? 'white' : '#6b7280',
                            cursor: 'pointer',
                            display: 'flex',
                            alignItems: 'center',
                            gap: '4px'
                        }}
                    >
                        Yearly <span style={{ background: '#dbeafe', color: '#2563eb', padding: '2px 8px', borderRadius: '12px', fontSize: '10px' }}>15% off</span>
                    </button>
                </div>
            </div>

            {/* Plan Cards */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: '24px' }}>
                {plans?.map((plan: any, idx: number) => {
                    const isActive = activeSubscription?.plan_id === plan.plan_id;
                    return (
                        <div key={idx} className={`${styles.appearanceCard} ${styles.planCard}`} style={{ padding: '32px' }}>
                            <div style={{ display: 'flex', flexDirection: 'column' }}>
                                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
                                    <h3 style={{ fontSize: '24px', fontWeight: 800 }}>{plan.name}</h3>
                                    {isActive && <span style={{ background: '#dcfce7', color: '#22c55e', padding: '4px 12px', borderRadius: '6px', fontSize: '12px', fontWeight: 700 }}>Active</span>}
                                </div>
                                <p style={{ fontSize: '14px', color: '#6b7280', lineHeight: 1.6, marginBottom: '24px' }}>{plan.description}</p>
                                <div style={{ marginBottom: '32px' }}>
                                    <span style={{ fontSize: '28px', fontWeight: 800, color: '#7c3aed' }}>${plan.amount}</span>
                                    <span style={{ fontSize: '14px', color: '#6b7280' }}> /month</span>
                                </div>
                                <button
                                    onClick={() => handlePurchase(plan)}
                                    disabled={isActive}
                                    className={styles.syncBtn}
                                    style={{
                                        width: '100%',
                                        background: plan.name === 'Pro' ? '#7c3aed' : 'white',
                                        color: plan.name === 'Pro' ? 'white' : '#374151',
                                        border: plan.name === 'Pro' ? 'none' : '1px solid #e5e7eb',
                                        opacity: isActive ? 0.6 : 1,
                                        cursor: isActive ? 'default' : 'pointer'
                                    }}
                                >
                                    {isActive ? 'Current Plan' : (plan.amount === 0 ? 'Continue as free' : 'Start 7-day free trial')}
                                </button>
                            </div>

                            <div className={styles.planFeatures}>
                                {plan.benefits?.map((benefit: string, bidx: number) => (
                                    <div key={bidx} style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                                        <FiCheck color="#22c55e" size={18} />
                                        <span style={{ fontSize: '14px', color: '#374151' }}>{benefit}</span>
                                    </div>
                                ))}
                            </div>
                        </div>
                    );
                })}
            </div>

            {/* Dedicated FAQ section */}
            <div style={{ marginTop: '40px' }}>
                <h2 style={{ fontSize: '18px', fontWeight: 700, marginBottom: '24px' }}>Frequently Asked Questions</h2>
                <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
                    {faqs.map((faq, idx) => (
                        <div key={idx} className={styles.appearanceCard} style={{ padding: 0 }}>
                            <div
                                onClick={() => setOpenFaq(openFaq === idx ? null : idx)}
                                style={{ padding: '20px 24px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', cursor: 'pointer' }}
                            >
                                <span style={{ fontSize: '15px', fontWeight: 600, color: '#374151' }}>{faq.q}</span>
                                {openFaq === idx ? <FiMinus color="#9ca3af" /> : <FiPlus color="#9ca3af" />}
                            </div>
                            {openFaq === idx && (
                                <div style={{ padding: '0 24px 20px', fontSize: '14px', color: '#6b7280', lineHeight: 1.6 }}>
                                    {faq.a}
                                </div>
                            )}
                        </div>
                    ))}
                </div>
            </div>

            {/* Support Banner */}
            <div className={styles.supportBanner} style={{ background: '#eff6ff', borderRadius: '16px', padding: '32px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: '24px' }}>
                <div style={{ flex: 1 }}>
                    <h3 style={{ fontSize: '16px', fontWeight: 700, marginBottom: '8px' }}>Don't see your answer?</h3>
                    <p style={{ fontSize: '13px', color: '#6b7280', marginBottom: '24px' }}>Reach out to our team for help with subscription plans, or any account-related questions.</p>
                    <div style={{ display: 'flex', gap: '16px', alignItems: 'center' }}>
                        <button className={styles.syncBtn} style={{ background: '#7c3aed', padding: '10px 24px' }}>Book call</button>
                        <span style={{ fontSize: '13px', color: '#7c3aed', fontWeight: 600, cursor: 'pointer' }}>Chat with us</span>
                    </div>
                </div>
                <div>
                    <img src={supportTeam} alt="Support" style={{ height: '120px' }} />
                </div>
            </div>
        </div>
    );
}
