import React, { useEffect, useState } from 'react';
import { useOrg } from '../contexts/OrgContext';
import { Card, Button } from '../components/UiKit';
import { FigmaAlert } from '../components/figma/FigmaAlert';
import { CompanyReport } from '../types';
import RadarPerformanceChart from '../components/charts/RadarPerformanceChart';

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);

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

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

    return (
        <div className="p-6 max-w-6xl mx-auto">
            <div className="mb-6">
                <h1 className="text-3xl font-bold text-[--text-primary]">Company Wiki</h1>
                <p className="text-[--text-secondary] mt-1">
                    Organization overview and insights
                </p>
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-6">
                <Card>
                    <h3 className="text-lg font-semibold text-[--text-primary] mb-3">Company Info</h3>
                    <div className="space-y-2">
                        <div>
                            <span className="text-sm text-[--text-secondary]">Name:</span>
                            <div className="font-medium text-[--text-primary]">{org?.name}</div>
                        </div>
                        <div>
                            <span className="text-sm text-[--text-secondary]">Industry:</span>
                            <div className="font-medium text-[--text-primary]">{org?.industry}</div>
                        </div>
                        <div>
                            <span className="text-sm text-[--text-secondary]">Size:</span>
                            <div className="font-medium text-[--text-primary]">{org?.size}</div>
                        </div>
                    </div>
                </Card>

                <Card>
                    <h3 className="text-lg font-semibold text-[--text-primary] mb-3">Team Stats</h3>
                    <div className="space-y-2">
                        <div>
                            <span className="text-sm text-[--text-secondary]">Total Employees:</span>
                            <div className="font-medium text-[--text-primary]">{employees.length}</div>
                        </div>
                        <div>
                            <span className="text-sm text-[--text-secondary]">Departments:</span>
                            <div className="font-medium text-[--text-primary]">
                                {[...new Set(employees.map(e => e.department))].length}
                            </div>
                        </div>
                        <div>
                            <span className="text-sm text-[--text-secondary]">Roles:</span>
                            <div className="font-medium text-[--text-primary]">
                                {[...new Set(employees.map(e => e.role))].length}
                            </div>
                        </div>
                    </div>
                </Card>

                <Card>
                    <h3 className="text-lg font-semibold text-[--text-primary] mb-3">Quick Actions</h3>
                    <div className="space-y-3">
                        <Button onClick={generateReport} disabled={isGenerating} className="w-full">
                            {isGenerating ? 'Generating...' : companyReport ? 'Regenerate Company Wiki' : 'Generate Company Wiki'}
                        </Button>
                        {error && <FigmaAlert type="error" message={error} />}
                        {!companyReport && !isGenerating && (
                            <FigmaAlert type="info" message="No company wiki generated yet. Use the button above to create one." />
                        )}
                        <Button variant="secondary" className="w-full" disabled={!companyReport}>
                            Export Data
                        </Button>
                    </div>
                </Card>
            </div>
            {companyReport && (
                <div className="space-y-6">
                    <Card>
                        <h3 className="text-xl font-semibold text-[--text-primary] mb-4">Executive Summary</h3>
                        <p className="text-[--text-secondary] whitespace-pre-line mb-4">{companyReport.executiveSummary}</p>
                        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                            <div className="text-center p-4 bg-[--background-secondary] rounded-lg">
                                <div className="text-2xl font-bold text-blue-500">{companyReport.overview.totalEmployees}</div>
                                <div className="text-sm text-[--text-secondary]">Employees</div>
                            </div>
                            <div className="text-center p-4 bg-[--background-secondary] rounded-lg">
                                <div className="text-2xl font-bold text-green-500">{companyReport.overview?.departmentBreakdown?.length || 0}</div>
                                <div className="text-sm text-[--text-secondary]">Departments</div>
                            </div>
                            <div className="text-center p-4 bg-[--background-secondary] rounded-lg">
                                <div className="text-2xl font-bold text-purple-500">{companyReport.organizationalStrengths?.length || 0}</div>
                                <div className="text-sm text-[--text-secondary]">Strength Areas</div>
                            </div>
                            <div className="text-center p-4 bg-[--background-secondary] rounded-lg">
                                <div className="text-2xl font-bold text-orange-500">{companyReport.organizationalRisks?.length || 0}</div>
                                <div className="text-sm text-[--text-secondary]">Risks</div>
                            </div>
                        </div>
                        {(Array.isArray(companyReport.gradingOverview) && companyReport.gradingOverview.length > 0) && (
                            <div className="mt-6 p-4 bg-[--background-tertiary] rounded-lg">
                                <RadarPerformanceChart
                                    title="Organizational Grading"
                                    data={companyReport.gradingOverview.map((g: any) => ({
                                        label: g.category || g.department || g.subject || 'Metric',
                                        value: g.value ?? g.averageScore ?? 0
                                    }))}
                                />
                            </div>
                        )}
                    </Card>

                    <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                        <Card>
                            <h4 className="text-lg font-semibold text-[--text-primary] mb-3">Strengths</h4>
                            <ul className="space-y-2">
                                {(companyReport.organizationalStrengths || []).map((s: any, i) => <li key={i} className="text-[--text-secondary] text-sm">• {s.area || s}</li>)}
                            </ul>
                        </Card>
                        <Card>
                            <h4 className="text-lg font-semibold text-[--text-primary] mb-3">Risks</h4>
                            <ul className="space-y-2">
                                {(companyReport.organizationalRisks || []).map((r, i) => <li key={i} className="text-[--text-secondary] text-sm">• {r}</li>)}
                            </ul>
                        </Card>
                        <Card>
                            <h4 className="text-lg font-semibold text-[--text-primary] mb-3">Forward Plan</h4>
                            <div>
                                <h5 className="font-medium text-[--text-primary] text-sm mb-1">Goals</h5>
                                <ul className="mb-2 list-disc list-inside text-[--text-secondary] text-sm space-y-1">
                                    {(companyReport.operatingPlan?.nextQuarterGoals || companyReport.forwardOperatingPlan?.quarterlyGoals || []).map((g: string, i: number) => <li key={i}>{g}</li>)}
                                </ul>
                                <h5 className="font-medium text-[--text-primary] text-sm mb-1">Resource Needs</h5>
                                <ul className="mb-2 list-disc list-inside text-[--text-secondary] text-sm space-y-1">
                                    {(companyReport.operatingPlan?.resourceNeeds || companyReport.forwardOperatingPlan?.resourceNeeds || []).map((g: string, i: number) => <li key={i}>{g}</li>)}
                                </ul>
                                <h5 className="font-medium text-[--text-primary] text-sm mb-1">Risk Mitigation</h5>
                                <ul className="list-disc list-inside text-[--text-secondary] text-sm space-y-1">
                                    {(companyReport.operatingPlan?.riskMitigation || companyReport.forwardOperatingPlan?.riskMitigation || []).map((g: string, i: number) => <li key={i}>{g}</li>)}
                                </ul>
                            </div>
                        </Card>
                    </div>
                </div>
            )}

            {/* Company Profile - Q&A Format from Onboarding */}
            <div className="mt-6">
                <h3 className="text-2xl font-semibold text-[--text-primary] mb-6">Company Profile</h3>
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                    {org?.mission && (
                        <Card className="p-4">
                            <div className="space-y-3">
                                <div>
                                    <h4 className="text-sm font-medium text-[--text-secondary] mb-1">Question:</h4>
                                    <p className="text-[--text-primary] font-medium">What is your company's mission?</p>
                                </div>
                                <div>
                                    <h4 className="text-sm font-medium text-[--text-secondary] mb-1">Answer:</h4>
                                    <p className="text-[--text-primary] text-sm leading-relaxed">{org.mission}</p>
                                </div>
                            </div>
                        </Card>
                    )}
                    {org?.vision && (
                        <Card className="p-4">
                            <div className="space-y-3">
                                <div>
                                    <h4 className="text-sm font-medium text-[--text-secondary] mb-1">Question:</h4>
                                    <p className="text-[--text-primary] font-medium">What is your company's vision?</p>
                                </div>
                                <div>
                                    <h4 className="text-sm font-medium text-[--text-secondary] mb-1">Answer:</h4>
                                    <p className="text-[--text-primary] text-sm leading-relaxed">{org.vision}</p>
                                </div>
                            </div>
                        </Card>
                    )}
                    {org?.evolution && (
                        <Card className="p-4">
                            <div className="space-y-3">
                                <div>
                                    <h4 className="text-sm font-medium text-[--text-secondary] mb-1">Question:</h4>
                                    <p className="text-[--text-primary] font-medium">How has your company evolved over time?</p>
                                </div>
                                <div>
                                    <h4 className="text-sm font-medium text-[--text-secondary] mb-1">Answer:</h4>
                                    <p className="text-[--text-primary] text-sm leading-relaxed">{org.evolution}</p>
                                </div>
                            </div>
                        </Card>
                    )}
                    {org?.advantages && (
                        <Card className="p-4">
                            <div className="space-y-3">
                                <div>
                                    <h4 className="text-sm font-medium text-[--text-secondary] mb-1">Question:</h4>
                                    <p className="text-[--text-primary] font-medium">What are your competitive advantages?</p>
                                </div>
                                <div>
                                    <h4 className="text-sm font-medium text-[--text-secondary] mb-1">Answer:</h4>
                                    <p className="text-[--text-primary] text-sm leading-relaxed">{org.advantages}</p>
                                </div>
                            </div>
                        </Card>
                    )}
                    {org?.vulnerabilities && (
                        <Card className="p-4">
                            <div className="space-y-3">
                                <div>
                                    <h4 className="text-sm font-medium text-[--text-secondary] mb-1">Question:</h4>
                                    <p className="text-[--text-primary] font-medium">What are your key vulnerabilities?</p>
                                </div>
                                <div>
                                    <h4 className="text-sm font-medium text-[--text-secondary] mb-1">Answer:</h4>
                                    <p className="text-[--text-primary] text-sm leading-relaxed">{org.vulnerabilities}</p>
                                </div>
                            </div>
                        </Card>
                    )}
                    {org?.shortTermGoals && (
                        <Card className="p-4">
                            <div className="space-y-3">
                                <div>
                                    <h4 className="text-sm font-medium text-[--text-secondary] mb-1">Question:</h4>
                                    <p className="text-[--text-primary] font-medium">What are your short-term goals?</p>
                                </div>
                                <div>
                                    <h4 className="text-sm font-medium text-[--text-secondary] mb-1">Answer:</h4>
                                    <p className="text-[--text-primary] text-sm leading-relaxed">{org.shortTermGoals}</p>
                                </div>
                            </div>
                        </Card>
                    )}
                    {org?.longTermGoals && (
                        <Card className="p-4">
                            <div className="space-y-3">
                                <div>
                                    <h4 className="text-sm font-medium text-[--text-secondary] mb-1">Question:</h4>
                                    <p className="text-[--text-primary] font-medium">What are your long-term goals?</p>
                                </div>
                                <div>
                                    <h4 className="text-sm font-medium text-[--text-secondary] mb-1">Answer:</h4>
                                    <p className="text-[--text-primary] text-sm leading-relaxed">{org.longTermGoals}</p>
                                </div>
                            </div>
                        </Card>
                    )}
                    {org?.cultureDescription && (
                        <Card className="p-4">
                            <div className="space-y-3">
                                <div>
                                    <h4 className="text-sm font-medium text-[--text-secondary] mb-1">Question:</h4>
                                    <p className="text-[--text-primary] font-medium">How would you describe your company culture?</p>
                                </div>
                                <div>
                                    <h4 className="text-sm font-medium text-[--text-secondary] mb-1">Answer:</h4>
                                    <p className="text-[--text-primary] text-sm leading-relaxed">{org.cultureDescription}</p>
                                </div>
                            </div>
                        </Card>
                    )}
                    {org?.workEnvironment && (
                        <Card className="p-4">
                            <div className="space-y-3">
                                <div>
                                    <h4 className="text-sm font-medium text-[--text-secondary] mb-1">Question:</h4>
                                    <p className="text-[--text-primary] font-medium">What is your work environment like?</p>
                                </div>
                                <div>
                                    <h4 className="text-sm font-medium text-[--text-secondary] mb-1">Answer:</h4>
                                    <p className="text-[--text-primary] text-sm leading-relaxed">{org.workEnvironment}</p>
                                </div>
                            </div>
                        </Card>
                    )}
                    {org?.additionalContext && (
                        <Card className="p-4 lg:col-span-2">
                            <div className="space-y-3">
                                <div>
                                    <h4 className="text-sm font-medium text-[--text-secondary] mb-1">Question:</h4>
                                    <p className="text-[--text-primary] font-medium">Any additional context about your company?</p>
                                </div>
                                <div>
                                    <h4 className="text-sm font-medium text-[--text-secondary] mb-1">Answer:</h4>
                                    <p className="text-[--text-primary] text-sm leading-relaxed">{org.additionalContext}</p>
                                </div>
                            </div>
                        </Card>
                    )}
                </div>
            </div>

            {org?.description && (
                <Card className="mt-6">
                    <h3 className="text-lg font-semibold text-[--text-primary] mb-3">About</h3>
                    <p className="text-[--text-secondary]">{org.description}</p>
                </Card>
            )}
        </div>
    );
};

export default CompanyWiki;
