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}</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}</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}</div>
                                <div className="text-sm text-[--text-secondary]">Risks</div>
                            </div>
                        </div>
                        {companyReport.gradingOverview && (
                            <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}</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 - Onboarding Data */}
            <Card className="mt-6">
                <h3 className="text-lg font-semibold text-[--text-primary] mb-4">Company Profile</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    {org?.mission && (
                        <div>
                            <h4 className="font-medium text-[--text-primary] mb-2">Mission</h4>
                            <p className="text-[--text-secondary] text-sm">{org.mission}</p>
                        </div>
                    )}
                    {org?.vision && (
                        <div>
                            <h4 className="font-medium text-[--text-primary] mb-2">Vision</h4>
                            <p className="text-[--text-secondary] text-sm">{org.vision}</p>
                        </div>
                    )}
                    {org?.evolution && (
                        <div>
                            <h4 className="font-medium text-[--text-primary] mb-2">Company Evolution</h4>
                            <p className="text-[--text-secondary] text-sm">{org.evolution}</p>
                        </div>
                    )}
                    {org?.advantages && (
                        <div>
                            <h4 className="font-medium text-[--text-primary] mb-2">Competitive Advantages</h4>
                            <p className="text-[--text-secondary] text-sm">{org.advantages}</p>
                        </div>
                    )}
                    {org?.vulnerabilities && (
                        <div>
                            <h4 className="font-medium text-[--text-primary] mb-2">Vulnerabilities</h4>
                            <p className="text-[--text-secondary] text-sm">{org.vulnerabilities}</p>
                        </div>
                    )}
                    {org?.shortTermGoals && (
                        <div>
                            <h4 className="font-medium text-[--text-primary] mb-2">Short Term Goals</h4>
                            <p className="text-[--text-secondary] text-sm">{org.shortTermGoals}</p>
                        </div>
                    )}
                    {org?.longTermGoals && (
                        <div>
                            <h4 className="font-medium text-[--text-primary] mb-2">Long Term Goals</h4>
                            <p className="text-[--text-secondary] text-sm">{org.longTermGoals}</p>
                        </div>
                    )}
                    {org?.cultureDescription && (
                        <div>
                            <h4 className="font-medium text-[--text-primary] mb-2">Culture</h4>
                            <p className="text-[--text-secondary] text-sm">{org.cultureDescription}</p>
                        </div>
                    )}
                    {org?.workEnvironment && (
                        <div>
                            <h4 className="font-medium text-[--text-primary] mb-2">Work Environment</h4>
                            <p className="text-[--text-secondary] text-sm">{org.workEnvironment}</p>
                        </div>
                    )}
                    {org?.additionalContext && (
                        <div className="md:col-span-2">
                            <h4 className="font-medium text-[--text-primary] mb-2">Additional Context</h4>
                            <p className="text-[--text-secondary] text-sm">{org.additionalContext}</p>
                        </div>
                    )}
                </div>
            </Card>

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