import React, { useEffect, useState } from 'react';
import { useOrg } from '../contexts/OrgContext';
import { CompanyReport } from '../types';
import { CompanyWikiManager } from '../components/CompanyWiki';

const CompanyWiki: React.FC = () => {
    const { org, employees, getFullCompanyReportHistory, generateCompanyWiki } = useOrg();
    const [isGenerating, setIsGenerating] = useState(false);
    const [companyReport, setCompanyReport] = useState<CompanyReport | null>(null);
    const [error, setError] = useState<string | null>(null);
    const [onboardingProgress, setOnboardingProgress] = useState(60);

    useEffect(() => {
        (async () => {
            try {
                const history = await getFullCompanyReportHistory();
                if (history.length) {
                    setCompanyReport(history[0]);
                }
            } catch (e) {
                console.error('Failed loading company report history', e);
            }
        })();
    }, [getFullCompanyReportHistory]);

    // Determine wiki state based on company data
    const wikiState = companyReport ? 'completed' : 'empty';

    // Create Q&A items from company report or org data
    const qaItems = companyReport ? [
        {
            question: "What is the mission of your company?",
            answer: org?.mission || "To empower small businesses with AI-driven automation tools that increase efficiency and reduce operational overhead."
        },
        {
            question: "How has your mission evolved in the last 1–3 years?",
            answer: org?.evolution || "We shifted from general SaaS tools to vertical-specific solutions, with deeper integrations and onboarding support."
        },
        {
            question: "What is your 5-year vision for the company?",
            answer: org?.vision || "To become the leading AI operations platform for SMBs in North America, serving over 100,000 customers."
        },
        {
            question: "What are your company's top 3 strategic advantages?",
            answer: org?.advantages || "Fast product iteration enabled by in-house AI capabilities\nDeep customer understanding from vertical specialization\nHigh customer retention due to integrated onboarding"
        },
        {
            question: "What are your biggest vulnerabilities or threats?",
            answer: org?.vulnerabilities || "Dependence on a single marketing channel, weak middle management, and rising customer acquisition costs."
        }
    ] : undefined;

    // Convert employees to suggested format for invitations
    const suggestedEmployees = employees?.map(emp => ({
        id: emp.id,
        name: emp.name || emp.email,
        email: emp.email
    })) || [];

    const handleCompleteOnboarding = async () => {
        setIsGenerating(true);
        setError(null);
        try {
            const report = await generateCompanyWiki();
            setCompanyReport(report);
            setOnboardingProgress(100);
        } catch (e: any) {
            console.error(e);
            setError('Failed to generate company wiki');
        } finally {
            setIsGenerating(false);
        }
    };

    return (
        <div className="flex-1 self-stretch bg-Neutrals-NeutralSlate0 rounded-tr-3xl rounded-br-3xl inline-flex flex-col justify-start items-start">
            {error && (
                <div className="self-stretch p-4 bg-red-50 border-l-4 border-red-400 text-red-700 text-sm">
                    {error}
                </div>
            )}

            <CompanyWikiManager
                initialState={wikiState}
                onboardingProgress={onboardingProgress}
                onCompleteOnboarding={handleCompleteOnboarding}
                qaItems={qaItems}
                suggestedEmployees={suggestedEmployees}
            />
        </div>
    );
};

export default CompanyWiki;