import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { secureApi } from '../services/secureApi';
import { OnboardingData } from '../types';


const CompanyWiki: React.FC = () => {
    const navigate = useNavigate();
    const [onboardingData, setOnboardingData] = useState<OnboardingData | null>(null);
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    const [activeSection, setActiveSection] = useState(1);
    const [onboardingCompleted, setOnboardingCompleted] = useState(false);
    const [lastStep, setLastStep] = useState<number | undefined>();

    useEffect(() => {
        loadOnboardingData();
    }, []);

    const loadOnboardingData = async () => {
        try {
            setIsLoading(true);
            const response = await secureApi.getOrgData();

            if (!response.onboardingCompleted) {
                navigate(`/onboarding`);
                return;
            }

            if (response.onboardingData) {
                setOnboardingData(response?.onboardingData);
                setOnboardingCompleted(response.onboardingCompleted);
                // setLastStep(response.lastStep);
            }
        } catch (err: any) {
            console.error('Failed to load onboarding data:', err);
            setError(err.message || 'Failed to load company wiki data');
        } finally {
            setIsLoading(false);
        }
    };

    const getSectionTitle = (section: number): string => {
        const titles = {
            1: 'Company Overview & Vision',
            2: 'Leadership & Organizational Structure',
            3: 'Operations & Execution',
            4: 'Culture & Team Health',
            5: 'Sales, Marketing & Growth',
            6: 'Innovation & Product/Service Strategy',
            7: 'Personal Leadership & Risk'
        };
        return titles[section as keyof typeof titles] || '';
    };

    const getSectionQuestions = (section: number) => {
        if (!onboardingData) return [];

        const sectionFields = {
            1: [
                'companySize',
                'mission',
                'missionEvolution',
                'vision',
                'strategicAdvantages',
                'vulnerabilities',
                'scalabilityChallenges',
                'growthLimitations'
            ],
            2: [
                'leadershipStructure',
                'criticalPeople',
                'leadershipGaps',
                'delegationOpportunities',
                'leadershipDevelopment',
                'heldOntoTooLong',
                'successionConfidence'
            ],
            3: [
                'businessSystems',
                'personalDependencies',
                'operationalFriction',
                'workflowEfficiency',
                'fragileProcesses',
                'recurringProblems'
            ],
            4: [
                'cultureDescription',
                'livedValues',
                'internalFriction',
                'speakUpCulture',
                'clearExpectations',
                'staffFeedback',
                'highPerformerLove'
            ],
            5: [
                'revenuePipeline',
                'customerAcquisition',
                'customerAcquisitionCost',
                'customerLifetimeValue',
                'underutilizedChannels',
                'overspendingROI',
                'currentBottleneck'
            ],
            6: [
                'monthlyBurnOverhead',
                'currentRevenue',
                'netProfitMargin',
                'financialsUpToDate',
                'financialGrowthPlanning',
                'cashRunway',
                'underpricing'
            ],
            7: [
                'uniqueOffering',
                'productStagnation',
                'industryTrends',
                'innovationAhead',
                'industryDirection'
            ],
            8: [
                'avoidedDecisions',
                'hardestCall',
                'energyDrain',
                'leadershipStretched',
                'sabbaticalRisks',
                'companyLegacy',
                'yearSuccess'
            ]
        };

        const fields = sectionFields[section as keyof typeof sectionFields] || [];
        return fields.map(field => ({
            field,
            question: getQuestionText(field),
            answer: onboardingData[field] || 'No answer provided'
        }));
    };

    const getQuestionText = (field: string): string => {
        const questions = {
            companySize: 'What is the size of your company?',
            mission: 'What is the mission of your company?',
            missionEvolution: 'How has your mission evolved in the last 1–3 years?',
            vision: 'What is your company\'s vision for the future?',
            strategicAdvantages: 'What does success look like for your company?',
            vulnerabilities: 'What are your core company values?',
            scalabilityChallenges: 'Describe your current leadership structure.',
            growthLimitations: 'Who are the most critical people in the business today?',

            leadershipStructure: 'Where are leadership gaps or weak links?',
            criticalPeople: 'What decisions are you still involved in that someone else should own?',
            leadershipGaps: 'What systems or tools do you rely on to run the business?',
            delegationOpportunities: 'Where does the business rely too much on you personally?',
            leadershipDevelopment: 'Where is the most operational friction inside the company?',
            heldOntoTooLong: 'How efficient is your workflow from sales to delivery?',
            successionConfidence: 'How confident are you in your succession plan?',

            businessSystems: 'What systems or tools do you rely on to run the business?',
            personalDependencies: 'Where does the business rely too much on you personally?',
            operationalFriction: 'Where is the most operational friction inside the company?',
            workflowEfficiency: 'How efficient is your workflow from sales to delivery?',
            fragileProcesses: 'What processes feel fragile or inconsistent?',
            recurringProblems: 'What recurring problems never seem to get solved?',

            cultureDescription: 'How would you describe your company culture in a few words?',
            livedValues: 'What values are truly lived out daily by your team?',
            internalFriction: 'Where is there internal friction or misalignment?',
            speakUpCulture: 'Do people speak up when things are broken or wrong?',
            clearExpectations: 'How do customers typically find you?',
            staffFeedback: 'What is your competitive advantage?',
            highPerformerLove: 'Where do you lose potential customers?',

            revenuePipeline: 'How consistent is your revenue pipeline?',
            customerAcquisition: 'Where do most of your customers come from?',
            customerAcquisitionCost: 'What is your customer acquisition cost (CAC)?',
            customerLifetimeValue: 'What\'s your average customer lifetime value (LTV)?',
            underutilizedChannels: 'What channels or strategies are underutilized?',
            overspendingROI: 'Where are you overspending with low ROI?',
            currentBottleneck: 'What is your current bottleneck in scaling revenue?',

            monthlyBurnOverhead: 'What is your monthly burn or overhead?',
            currentRevenue: 'What is your current monthly/annual revenue?',
            netProfitMargin: 'What is your current net profit margin?',
            financialsUpToDate: 'Are your financials up to date and properly reported?',
            financialGrowthPlanning: 'What would your team do differently if they had full financial transparency?',
            cashRunway: 'What does your cash runway look like?',
            underpricing: 'What are you underpricing or undervaluing?',

            uniqueOffering: 'What is your most unique offering?',
            productStagnation: 'What part of the product/service is outdated or stagnant?',
            industryTrends: 'What trends are you tracking in your industry?',
            innovationAhead: 'How does your company stay ahead of innovation?',
            industryDirection: 'What new product/service do you believe could change the game for you?',


            avoidedDecisions: 'What decisions are you avoiding right now?',
            hardestCall: 'What\'s been the hardest call you\'ve had to make in the last year?',
            energyDrain: 'What part of the business drains your energy the most?',
            leadershipStretched: 'Where are you most stretched as a leader?',
            sabbaticalRisks: 'If you had to take a 90-day sabbatical, what would collapse?',
            companyLegacy: 'What legacy are you trying to build through this company?',
            yearSuccess: 'What would need to happen in the next 12 months for this year to be a success?'
        };
        return questions[field as keyof typeof questions] || field;
    };

    if (isLoading) {
        return (
            <div className="flex-1 flex items-center justify-center">
                <div className="text-center">
                    <div className="animate-spin w-8 h-8 border-2 border-Brand-Orange border-t-transparent rounded-full mx-auto mb-4"></div>
                    <p className="text-[--$1]">Loading company wiki...</p>
                </div>
            </div>
        );
    }

    if (error) {
        return (
            <div className="flex-1 flex items-center justify-center">
                <div className="text-center text-red-600">
                    <p>Error: {error}</p>
                    <button
                        onClick={loadOnboardingData}
                        className="mt-4 px-4 py-2 bg-Brand-Orange text-white rounded-lg"
                    >
                        Retry
                    </button>
                </div>
            </div>
        );
    }

    if (!onboardingCompleted || !onboardingData) {
        return null;
    }

    return (
        <div className="flex h-full self-stretch rounded-3xl shadow-[0px_0px_15px_0px_rgba(0,0,0,0.08)] flex justify-between items-start">
            {/* Left Sidebar - Company Navigation */}
            {/* Main Content Area */}
            <div className="flex-1 self-stretch bg-[--Neutrals-NeutralSlate0] rounded-tr-3xl rounded-br-3xl inline-flex flex-col justify-start items-start">
                <div className="self-stretch flex-1 inline-flex justify-start items-center">
                    {/* Table of Contents Sidebar */}
                    <div className="flex-1 self-stretch max-w-64 min-w-64 border-r border-[--Neutrals-NeutralSlate200] inline-flex flex-col justify-start items-start">
                        <div className="self-stretch p-5 inline-flex justify-start items-center gap-2.5">
                            <div className="flex-1 justify-start text-[--$1] text-base font-medium font-['Inter'] leading-normal">Table of contents</div>
                        </div>
                        <div className="self-stretch px-3 flex flex-col justify-start items-start gap-1.5">
                            {[1, 2, 3, 4, 5, 6, 7].map((section, index) => (
                                <div
                                    key={section}
                                    className={`self-stretch p-2 ${activeSection === section ? 'bg-[--Neutrals-NeutralSlate100] rounded-full shadow-[0px_1px_2px_0px_rgba(10,13,20,0.03)]' : 'rounded-[10px]'} inline-flex justify-start items-center gap-2 overflow-hidden cursor-pointer`}
                                    onClick={() => setActiveSection(section)}
                                >
                                    <div className={`h-5 p-0.5 ${activeSection === section ? 'bg-[--Brand-Orange]' : 'bg-[--Neutrals-NeutralSlate100]'} rounded-[999px] inline-flex flex-col justify-center items-center gap-0.5 overflow-hidden`}>
                                        <div className={`w-4 text-center justify-start ${activeSection === section ? 'text-[--Neutrals-NeutralSlate0]' : 'text-[--Neutrals-NeutralSlate950]'} text-xs ${activeSection === section ? 'font-medium' : 'font-normal'} font-['Inter'] leading-none`}>{section}</div>
                                    </div>
                                    <div className={`flex-1 justify-start ${activeSection === section ? 'text-[--Neutrals-NeutralSlate800]' : 'text-[--Neutrals-NeutralSlate500]'} text-xs font-medium font-['Inter'] leading-none`}>
                                        {getSectionTitle(section)}
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>

                    {/* Questions Content */}
                    <div className="flex-1 self-stretch inline-flex flex-col justify-start items-start">
                        <div className="self-stretch p-5 inline-flex justify-start items-center gap-2.5">
                            <div className="flex-1 justify-start text-[--Neutrals-NeutralSlate800] text-base font-medium font-['Inter'] leading-normal">
                                {getSectionTitle(activeSection)}
                            </div>
                        </div>
                        <div className="self-stretch px-5 flex flex-col justify-start items-start gap-4">
                            {getSectionQuestions(activeSection).map((qa, index) => (
                                <div key={qa.field} className="self-stretch p-3 bg-[--Neutrals-NeutralSlate100] rounded-2xl shadow-[0px_1px_2px_0px_rgba(0,0,0,0.02)] flex flex-col justify-center items-start gap-2 overflow-hidden">
                                    <div className="self-stretch px-3 py-px inline-flex justify-start items-center gap-2.5">
                                        <div className="flex-1 flex justify-center items-center gap-3">
                                            <div className="w-3 self-stretch justify-start text-[--Neutrals-NeutralSlate300] text-base font-semibold font-['Inter'] leading-normal">Q</div>
                                            <div className="flex-1 justify-start text-[--Neutrals-NeutralSlate600] text-sm font-medium font-['Inter'] leading-tight">
                                                {qa.question}
                                            </div>
                                        </div>
                                    </div>
                                    <div className="self-stretch px-3 py-2 bg-[--Neutrals-NeutralSlate0] rounded-[10px] inline-flex justify-between items-center">
                                        <div className="flex-1 flex justify-start items-start gap-3">
                                            <div className="w-3.5 h-6 justify-center text-[--$1] text-base font-semibold font-['Inter'] leading-normal">A</div>
                                            <div className="flex-1 justify-start text-[--$1] text-base font-normal font-['Inter'] leading-normal whitespace-pre-wrap">
                                                {qa.answer}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default CompanyWiki;