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

interface OnboardingData {
    [key: string]: string;
}

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.getOnboardingQuestions();

            if (!response.completed && response.lastStep) {
                navigate(`/onboarding?step=${response.lastStep}`);
                return;
            }

            if (!response.completed) {
                navigate('/onboarding');
                return;
            }

            setOnboardingData(response.questions);
            setOnboardingCompleted(response.completed);
            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: ['mission', 'missionEvolution', 'vision', 'successDefinition', 'coreValues'],
            2: ['leadershipStructure', 'criticalPeople', 'leadershipGaps', 'delegationOpportunities'],
            3: ['businessSystems', 'personalDependencies', 'operationalFriction', 'workflowEfficiency'],
            4: ['cultureDescription', 'livedValues', 'internalFriction', 'speakUpCulture'],
            5: ['customerAcquisition', 'competitiveAdvantage', 'customerLoss', 'customerLoyalty'],
            6: ['newProducts', 'innovationProcess', 'uniquePosition', 'industryDirection'],
            7: ['businessWorries', 'leadershipBlindSpots', 'stressManagement', 'regretfulDecisions']
        };

        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 = {
            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?',
            successDefinition: 'What does success look like for your company?',
            coreValues: 'What are your core company values?',
            leadershipStructure: 'Describe your current leadership structure.',
            criticalPeople: 'Who are the most critical people in the business today?',
            leadershipGaps: 'Where are leadership gaps or weak links?',
            delegationOpportunities: 'What decisions are you still involved in that someone else should own?',
            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?',
            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?',
            customerAcquisition: 'How do customers typically find you?',
            competitiveAdvantage: 'What is your competitive advantage?',
            customerLoss: 'Where do you lose potential customers?',
            customerLoyalty: 'What drives customer loyalty and retention?',
            newProducts: 'What new products or services are you considering?',
            innovationProcess: 'How do you stay innovative and ahead of trends?',
            uniquePosition: 'What customer problems are you uniquely positioned to solve?',
            industryDirection: 'Where do you see your industry heading?',
            businessWorries: 'What keeps you up at night about the business?',
            leadershipBlindSpots: 'What are your biggest blind spots as a leader?',
            stressManagement: 'How do you handle stress and pressure?',
            regretfulDecisions: 'What decisions do you most regret or would do differently?'
        };
        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="w-[1440px] h-[810px] p-4 bg-[--Neutrals-NeutralSlate200] inline-flex justify-start items-start overflow-hidden">
            <div className="flex-1 self-stretch rounded-3xl shadow-[0px_0px_15px_0px_rgba(0,0,0,0.08)] flex justify-between items-start overflow-hidden">
                {/* Left Sidebar - Company Navigation */}
                <div className="w-64 self-stretch max-w-64 min-w-64 px-3 pt-4 pb-3 bg-[--Neutrals-NeutralSlate0] border-r border-[--$1] inline-flex flex-col justify-between items-center overflow-hidden">
                    {/* Company Header */}
                    <div className="self-stretch flex flex-col justify-start items-start gap-5">
                        <div className="w-60 pl-2 pr-4 py-2 bg-[--Neutrals-NeutralSlate0] rounded-3xl outline outline-1 outline-offset-[-1px] outline-[--$1] inline-flex justify-between items-center overflow-hidden">
                            <div className="flex-1 flex justify-start items-center gap-2">
                                <div className="w-8 h-8 rounded-full flex justify-start items-center gap-2.5">
                                    <div className="w-8 h-8 relative bg-Brand-Orange rounded-full outline outline-[1.60px] outline-offset-[-1.60px] outline-white/10 overflow-hidden">
                                        <div className="w-8 h-8 left-0 top-0 absolute bg-gradient-to-b from-white/0 to-white/10" />
                                    </div>
                                </div>
                                <div className="flex-1 inline-flex flex-col justify-start items-start gap-0.5">
                                    <div className="self-stretch justify-start text-[--$1] text-base font-medium font-['Inter'] leading-normal">
                                        {onboardingData?.companyName || 'Company Name'}
                                    </div>
                                </div>
                            </div>
                        </div>

                        {/* Navigation Items */}
                        <div className="self-stretch flex flex-col justify-start items-start gap-5">
                            <div className="self-stretch flex flex-col justify-start items-start gap-1.5">
                                <div className="w-60 px-4 py-2.5 bg-[--Neutrals-NeutralSlate100] rounded-[34px] inline-flex justify-start items-center gap-2">
                                    <div className="justify-start text-[--$1] text-sm font-medium font-['Inter'] leading-tight">Company Wiki</div>
                                </div>
                                <div className="w-60 px-4 py-2.5 rounded-[34px] inline-flex justify-start items-center gap-2">
                                    <div className="justify-start text-[--$1] text-sm font-medium font-['Inter'] leading-tight">Submissions</div>
                                </div>
                                <div className="w-60 px-4 py-2.5 rounded-[34px] inline-flex justify-start items-center gap-2">
                                    <div className="justify-start text-[--$1] text-sm font-medium font-['Inter'] leading-tight">Reports</div>
                                </div>
                                <div className="w-60 px-4 py-2.5 rounded-[34px] inline-flex justify-start items-center gap-2">
                                    <div className="justify-start text-[--$1] text-sm font-medium font-['Inter'] leading-tight">Chat</div>
                                </div>
                                <div className="w-60 px-4 py-2.5 rounded-[34px] inline-flex justify-start items-center gap-2">
                                    <div className="justify-start text-[--$1] text-sm font-medium font-['Inter'] leading-tight">Help</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* Bottom Section */}
                    <div className="self-stretch flex flex-col justify-start items-start gap-3">
                        <div className="w-60 px-4 py-2.5 rounded-[34px] inline-flex justify-start items-center gap-2">
                            <div className="flex-1 justify-start text-[--$1] text-sm font-medium font-['Inter'] leading-tight">Settings</div>
                        </div>
                    </div>
                </div>

                {/* 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-Outline-Outline-Gray-200 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-Main-BG-Gray-100 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-Text-Gray-100'} 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-[--$1]' : 'text-Text-Dark-950'} text-xs ${activeSection === section ? 'font-medium' : 'font-normal'} font-['Inter'] leading-none`}>{section}</div>
                                        </div>
                                        <div className={`flex-1 justify-start ${activeSection === section ? 'text-[--$1]' : 'text-Text-Gray-500'} 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-[--$1] 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-[--$1] text-base font-semibold font-['Inter'] leading-normal">Q</div>
                                                <div className="flex-1 justify-start text-[--$1] 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>
        </div>
    );
};

export default CompanyWiki;