import React, { useState, useEffect } from 'react';
import { useOrg } from '../contexts/OrgContext';
import { Card, Button } from '../components/UiKit';
import { CompanyReport, Employee, Report } from '../types';
import RadarPerformanceChart from '../components/charts/RadarPerformanceChart';
import ScoreBarList from '../components/charts/ScoreBarList';
import { SAMPLE_COMPANY_REPORT } from '../constants';
import ReportDetail from './ReportDetail';

interface EmployeeDataProps {
    mode: 'submissions' | 'reports';
}

const CompanyReportCard: React.FC<{ report: CompanyReport }> = ({ report }) => {
    const [isExpanded, setIsExpanded] = useState(false);

    return (
        <Card className="mb-6 border-l-4 border-blue-500">
            <div className="flex justify-between items-start mb-4">
                <div className="flex items-center space-x-3">
                    <div className="w-10 h-10 bg-gradient-to-r from-blue-500 to-blue-600 rounded-full flex items-center justify-center text-white font-bold text-sm">
                        ZM
                    </div>
                    <div>
                        <h2 className="text-xl font-bold text-[--text-primary]">Company Report</h2>
                        <p className="text-sm text-[--text-secondary]">
                            Last updated: {new Date(report.createdAt).toLocaleDateString()}
                        </p>
                    </div>
                </div>
                <div className="flex space-x-2">
                    <Button
                        size="sm"
                        variant="secondary"
                        onClick={() => setIsExpanded(!isExpanded)}
                    >
                        {isExpanded ? 'Collapse' : 'View Details'}
                    </Button>
                    <Button size="sm">Download as PDF</Button>
                </div>
            </div>

            {/* Overview Section - Always Visible */}
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-4">
                <div className="bg-[--background-tertiary] p-4 rounded-lg">
                    <h3 className="text-sm font-medium text-[--text-secondary]">Total Employees</h3>
                    <p className="text-2xl font-bold text-[--text-primary]">{report.overview.totalEmployees}</p>
                </div>
                <div className="bg-[--background-tertiary] p-4 rounded-lg">
                    <h3 className="text-sm font-medium text-[--text-secondary]">Departments</h3>
                    <p className="text-2xl font-bold text-[--text-primary]">{report.overview.departmentBreakdown.length}</p>
                </div>
                <div className="bg-[--background-tertiary] p-4 rounded-lg">
                    <h3 className="text-sm font-medium text-[--text-secondary]">Avg Performance</h3>
                    <p className="text-2xl font-bold text-[--text-primary]">{report.overview.averagePerformanceScore}/5</p>
                </div>
                <div className="bg-[--background-tertiary] p-4 rounded-lg">
                    <h3 className="text-sm font-medium text-[--text-secondary]">Risk Level</h3>
                    <p className="text-2xl font-bold text-[--text-primary]">{report.overview.riskLevel}</p>
                </div>
            </div>

            {isExpanded && (
                <div className="mt-6 space-y-6">
                    {/* Key Personnel Changes */}
                    {report.keyPersonnelChanges && report.keyPersonnelChanges.length > 0 && (
                        <div>
                            <h3 className="text-lg font-semibold text-[--text-primary] mb-3 flex items-center">
                                <span className="w-2 h-2 bg-orange-500 rounded-full mr-2"></span>
                                Key Personnel Changes
                            </h3>
                            <div className="space-y-2">
                                {report.keyPersonnelChanges.map((change, idx) => (
                                    <div key={idx} className="p-3 bg-[--background-tertiary] rounded-lg">
                                        <div className="flex justify-between items-start">
                                            <div>
                                                <p className="font-medium text-[--text-primary]">{change.employeeName}</p>
                                                <p className="text-sm text-[--text-secondary]">{change.role} - {change.department}</p>
                                            </div>
                                            <span className={`px-2 py-1 text-xs rounded-full ${change.changeType === 'departure' ? 'bg-red-100 text-red-800' :
                                                change.changeType === 'promotion' ? 'bg-green-100 text-green-800' :
                                                    'bg-blue-100 text-blue-800'
                                                }`}>
                                                {change.changeType}
                                            </span>
                                        </div>
                                        <p className="text-sm text-[--text-secondary] mt-2">{change.impact}</p>
                                    </div>
                                ))}
                            </div>
                        </div>
                    )}

                    {/* Immediate Hiring Needs */}
                    {report.immediateHiringNeeds && report.immediateHiringNeeds.length > 0 && (
                        <div>
                            <h3 className="text-lg font-semibold text-[--text-primary] mb-3 flex items-center">
                                <span className="w-2 h-2 bg-red-500 rounded-full mr-2"></span>
                                Immediate Hiring Needs
                            </h3>
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                {report.immediateHiringNeeds.map((need, idx) => (
                                    <div key={idx} className="p-4 bg-[--background-tertiary] rounded-lg">
                                        <div className="flex justify-between items-start mb-2">
                                            <h4 className="font-medium text-[--text-primary]">{need.role}</h4>
                                            <span className={`px-2 py-1 text-xs rounded-full ${need.urgency === 'high' ? 'bg-red-100 text-red-800' :
                                                need.urgency === 'medium' ? 'bg-yellow-100 text-yellow-800' :
                                                    'bg-green-100 text-green-800'
                                                }`}>
                                                {need.urgency} priority
                                            </span>
                                        </div>
                                        <p className="text-sm text-[--text-secondary] mb-2">{need.department}</p>
                                        <p className="text-sm text-[--text-secondary]">{need.reason}</p>
                                    </div>
                                ))}
                            </div>
                        </div>
                    )}

                    {/* Forward Operating Plan */}
                    {report.forwardOperatingPlan && (
                        <div>
                            <h3 className="text-lg font-semibold text-[--text-primary] mb-3 flex items-center">
                                <span className="w-2 h-2 bg-blue-500 rounded-full mr-2"></span>
                                Forward Operating Plan
                            </h3>
                            <div className="space-y-4">
                                <div className="p-4 bg-[--background-tertiary] rounded-lg">
                                    <h4 className="font-medium text-[--text-primary] mb-2">Next Quarter Goals</h4>
                                    <ul className="space-y-1">
                                        {report.forwardOperatingPlan.nextQuarterGoals.map((goal, idx) => (
                                            <li key={idx} className="text-sm text-[--text-secondary] flex items-start">
                                                <span className="w-1.5 h-1.5 bg-blue-500 rounded-full mt-2 mr-2 flex-shrink-0"></span>
                                                {goal}
                                            </li>
                                        ))}
                                    </ul>
                                </div>
                                <div className="p-4 bg-[--background-tertiary] rounded-lg">
                                    <h4 className="font-medium text-[--text-primary] mb-2">Key Initiatives</h4>
                                    <ul className="space-y-1">
                                        {report.forwardOperatingPlan.keyInitiatives.map((initiative, idx) => (
                                            <li key={idx} className="text-sm text-[--text-secondary] flex items-start">
                                                <span className="w-1.5 h-1.5 bg-green-500 rounded-full mt-2 mr-2 flex-shrink-0"></span>
                                                {initiative}
                                            </li>
                                        ))}
                                    </ul>
                                </div>
                            </div>
                        </div>
                    )}

                    {/* Organizational Strengths */}
                    {report.organizationalStrengths && report.organizationalStrengths.length > 0 && (
                        <div>
                            <h3 className="text-lg font-semibold text-[--text-primary] mb-3 flex items-center">
                                <span className="w-2 h-2 bg-green-500 rounded-full mr-2"></span>
                                Organizational Strengths
                            </h3>
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                {report.organizationalStrengths.map((strength, idx) => (
                                    <div key={idx} className="p-3 bg-[--background-tertiary] rounded-lg">
                                        <div className="flex items-start space-x-3">
                                            <span className="text-2xl">{strength.icon}</span>
                                            <div>
                                                <h4 className="font-medium text-[--text-primary]">{strength.area}</h4>
                                                <p className="text-sm text-[--text-secondary]">{strength.description}</p>
                                            </div>
                                        </div>
                                    </div>
                                ))}
                            </div>
                        </div>
                    )}

                    {/* Organizational Impact Summary */}
                    {report.organizationalImpactSummary && (
                        <div>
                            <h3 className="text-lg font-semibold text-[--text-primary] mb-3 flex items-center">
                                <span className="w-2 h-2 bg-purple-500 rounded-full mr-2"></span>
                                Organizational Impact Summary
                            </h3>
                            <div className="p-4 bg-[--background-tertiary] rounded-lg">
                                <p className="text-[--text-secondary] text-sm leading-relaxed">
                                    {report.organizationalImpactSummary}
                                </p>
                            </div>
                        </div>
                    )}

                    {/* Grading Overview */}
                    {report.gradingOverview && (
                        <div>
                            <h3 className="text-lg font-semibold text-[--text-primary] mb-3 flex items-center">
                                <span className="w-2 h-2 bg-indigo-500 rounded-full mr-2"></span>
                                Grading Overview
                            </h3>
                            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                                {Object.entries(report.gradingOverview).map(([category, score], idx) => (
                                    <div key={idx} className="text-center p-4 bg-[--background-tertiary] rounded-lg">
                                        <div className="text-2xl font-bold text-[--text-primary] mb-1">{score}/5</div>
                                        <div className="text-sm text-[--text-secondary] capitalize">{category.replace(/([A-Z])/g, ' $1').trim()}</div>
                                    </div>
                                ))}
                            </div>
                        </div>
                    )}
                </div>
            )}
        </Card>
    );
};

const EmployeeCard: React.FC<{
    employee: Employee;
    report?: Report;
    mode: 'submissions' | 'reports';
    isOwner: boolean;
    onGenerateReport?: (employee: Employee) => void;
    isGeneratingReport?: boolean;
    onViewReport?: (report: Report, employeeName: string) => void;
}> = ({ employee, report, mode, isOwner, onGenerateReport, isGeneratingReport, onViewReport }) => {
    const [isExpanded, setIsExpanded] = useState(false);

    return (
        <Card className="hover:shadow-md transition-shadow">
            <div className="flex items-center justify-between">
                <div className="flex items-center space-x-3">
                    <div className="w-10 h-10 bg-gradient-to-r from-blue-500 to-purple-500 rounded-full flex items-center justify-center text-white font-bold text-sm">
                        {employee.initials}
                    </div>
                    <div>
                        <h3 className="font-semibold text-[--text-primary]">{employee.name}</h3>
                        <p className="text-sm text-[--text-secondary]">
                            {employee.role} {employee.department && `• ${employee.department}`}
                        </p>
                    </div>
                    {employee.isOwner && (
                        <span className="px-2 py-1 bg-yellow-100 text-yellow-800 text-xs rounded-full">
                            Owner
                        </span>
                    )}
                </div>
                <div className="flex space-x-2">
                    {report && (
                        <>
                            <Button
                                size="sm"
                                variant="secondary"
                                onClick={() => onViewReport?.(report, employee.name)}
                            >
                                View Full Report
                            </Button>
                            <Button
                                size="sm"
                                variant="secondary"
                                onClick={() => setIsExpanded(!isExpanded)}
                            >
                                {isExpanded ? 'Hide' : 'View'} Summary
                            </Button>
                        </>
                    )}
                    {isOwner && mode === 'reports' && (
                        <Button
                            size="sm"
                            onClick={() => onGenerateReport?.(employee)}
                            disabled={isGeneratingReport}
                        >
                            {isGeneratingReport ? 'Generating...' : report ? 'Regenerate Report' : 'Generate Report'}
                        </Button>
                    )}
                </div>
            </div>

            {isExpanded && report && (
                <div className="mt-4 pt-4 border-t border-[--border-color] space-y-4">
                    <div>
                        <h4 className="font-medium text-[--text-primary] mb-2">Role & Output</h4>
                        <p className="text-sm text-[--text-secondary]">{report.roleAndOutput.responsibilities}</p>
                    </div>

                    {report.grading?.[0]?.scores && (
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div className="bg-[--background-tertiary] rounded-lg p-4">
                                <RadarPerformanceChart
                                    title="Performance Profile"
                                    data={report.grading[0].scores.map(s => ({ label: s.subject, value: (s.value / s.fullMark) * 100 }))}
                                />
                            </div>
                            <div className="bg-[--background-tertiary] rounded-lg p-4">
                                <ScoreBarList
                                    title="Score Breakdown"
                                    items={report.grading[0].scores.map(s => ({ label: s.subject, value: s.value, max: s.fullMark }))}
                                />
                            </div>
                        </div>
                    )}

                    <div>
                        <h4 className="font-medium text-[--text-primary] mb-2">Key Strengths</h4>
                        <div className="flex flex-wrap gap-2">
                            {report.insights.strengths.map((strength, idx) => (
                                <span key={idx} className="px-2 py-1 bg-green-100 text-green-800 text-xs rounded-full">
                                    {strength}
                                </span>
                            ))}
                        </div>
                    </div>

                    <div>
                        <h4 className="font-medium text-[--text-primary] mb-2">Development Areas</h4>
                        <div className="flex flex-wrap gap-2">
                            {report.insights.weaknesses.map((weakness, idx) => (
                                <span key={idx} className="px-2 py-1 bg-orange-100 text-orange-800 text-xs rounded-full">
                                    {weakness}
                                </span>
                            ))}
                        </div>
                    </div>

                    <div>
                        <h4 className="font-medium text-[--text-primary] mb-2">Recommendations</h4>
                        <ul className="space-y-1">
                            {report.recommendations.map((rec, idx) => (
                                <li key={idx} className="text-sm text-[--text-secondary] flex items-start">
                                    <span className="w-1.5 h-1.5 bg-blue-500 rounded-full mt-2 mr-2 flex-shrink-0"></span>
                                    {rec}
                                </li>
                            ))}
                        </ul>
                    </div>
                </div>
            )}
        </Card>
    );
};

const EmployeeData: React.FC<EmployeeDataProps> = ({ mode }) => {
    const { employees, reports, user, isOwner, getFullCompanyReportHistory, generateEmployeeReport, generateCompanyReport, saveReport, orgId } = useOrg();
    const [companyReport, setCompanyReport] = useState<CompanyReport | null>(null);
    const [generatingReports, setGeneratingReports] = useState<Set<string>>(new Set());
    const [generatingCompanyReport, setGeneratingCompanyReport] = useState(false);
    const [selectedReport, setSelectedReport] = useState<{ report: CompanyReport | Report; type: 'company' | 'employee'; employeeName?: string } | null>(null);

    useEffect(() => {
        // Load company report for owners
        const loadCompanyReport = async () => {
            if (isOwner(user?.uid || '') && mode === 'reports') {
                try {
                    const history = await getFullCompanyReportHistory();
                    if (history.length > 0) {
                        setCompanyReport(history[0]);
                    } else {
                        // Fallback to sample report if no real report exists
                        setCompanyReport(SAMPLE_COMPANY_REPORT);
                    }
                } catch (error) {
                    console.error('Failed to load company report:', error);
                    setCompanyReport(SAMPLE_COMPANY_REPORT);
                }
            }
        };
        loadCompanyReport();
    }, [isOwner, user?.uid, mode, getFullCompanyReportHistory]);

    const handleGenerateReport = async (employee: Employee) => {
        setGeneratingReports(prev => new Set(prev).add(employee.id));

        try {
            console.log('Generating report for employee:', employee.name, 'in org:', orgId);

            // Use the OrgContext method instead of direct API call
            const report = await generateEmployeeReport(employee);
            
            if (report) {
                console.log('Report generated and saved successfully for:', employee.name);
            } else {
                console.error('Report generation failed for:', employee.name);
                // Show user-friendly error
                alert(`Failed to generate report for ${employee.name}. Please try again.`);
            }
        } catch (error) {
            console.error('Error generating report:', error);
            alert(`Error generating report for ${employee.name}: ${error.message}`);
        } finally {
            setGeneratingReports(prev => {
                const newSet = new Set(prev);
                newSet.delete(employee.id);
                return newSet;
            });
        }
    };

    const handleGenerateCompanyReport = async () => {
        setGeneratingCompanyReport(true);
        
        try {
            console.log('Generating company report for org:', orgId);
            const newReport = await generateCompanyReport();
            console.log('Received new company report:', newReport);
            setCompanyReport(newReport);
            console.log('Company report generated and state updated successfully');
        } catch (error) {
            console.error('Error generating company report:', error);
            alert(`Error generating company report: ${error.message}`);
        } finally {
            setGeneratingCompanyReport(false);
        }
    };

    const currentUserIsOwner = isOwner(user?.uid || '');

    // Filter employees based on user access
    const visibleEmployees = currentUserIsOwner
        ? employees
        : employees.filter(emp => emp.id === user?.uid);

    return (
        <div className="p-6 max-w-6xl mx-auto">
            <div className="mb-6">
                <h1 className="text-3xl font-bold text-[--text-primary]">
                    {mode === 'submissions' ? 'Employee Submissions' : 'Employee Reports'}
                </h1>
                <p className="text-[--text-secondary] mt-1">
                    {mode === 'submissions'
                        ? 'Manage employee data and submissions'
                        : 'View AI-generated insights and reports'}
                </p>
            </div>

            {/* Company Report - Only visible to owners in reports mode */}
            {currentUserIsOwner && mode === 'reports' && (
                <div className="mb-6">
                    {companyReport ? (
                        <div>
                            <div className="flex justify-between items-center mb-4">
                                <h2 className="text-xl font-semibold text-[--text-primary]">Company Report</h2>
                                <div className="flex space-x-2">
                                    <Button
                                        size="sm"
                                        variant="secondary"
                                        onClick={() => setSelectedReport({ report: companyReport, type: 'company' })}
                                    >
                                        View Full Report
                                    </Button>
                                    <Button
                                        size="sm"
                                        onClick={handleGenerateCompanyReport}
                                        disabled={generatingCompanyReport}
                                    >
                                        {generatingCompanyReport ? 'Regenerating...' : 'Regenerate Report'}
                                    </Button>
                                </div>
                            </div>
                            <CompanyReportCard report={companyReport} />
                        </div>
                    ) : (
                        <Card>
                            <div className="text-center py-8">
                                <h3 className="text-lg font-semibold text-[--text-primary] mb-2">
                                    Generate Company Report
                                </h3>
                                <p className="text-[--text-secondary] mb-4">
                                    Create a comprehensive AI-powered report analyzing your organization's performance, 
                                    strengths, and recommendations based on employee data.
                                </p>
                                <Button
                                    onClick={handleGenerateCompanyReport}
                                    disabled={generatingCompanyReport}
                                >
                                    {generatingCompanyReport ? 'Generating Report...' : 'Generate Company Report'}
                                </Button>
                            </div>
                        </Card>
                    )}
                </div>
            )}

            {/* Employee Cards */}
            <div className="space-y-4">
                <h2 className="text-xl font-semibold text-[--text-primary]">
                    {currentUserIsOwner ? 'All Employees' : 'Your Information'}
                </h2>
                {visibleEmployees.length === 0 ? (
                    <Card>
                        <div className="text-center py-8">
                            <p className="text-[--text-secondary]">No employees found.</p>
                            {currentUserIsOwner && (
                                <Button className="mt-4" size="sm">
                                    Invite First Employee
                                </Button>
                            )}
                        </div>
                    </Card>
                ) : (
                    visibleEmployees.map(employee => (
                        <EmployeeCard
                            key={employee.id}
                            employee={employee}
                            report={reports[employee.id]}
                            mode={mode}
                            isOwner={currentUserIsOwner}
                            onGenerateReport={handleGenerateReport}
                            isGeneratingReport={generatingReports.has(employee.id)}
                            onViewReport={(report, employeeName) => setSelectedReport({ report, type: 'employee', employeeName })}
                        />
                    ))
                )}
            </div>

            {/* Report Detail Modal */}
            {selectedReport && (
                <ReportDetail
                    report={selectedReport.report}
                    type={selectedReport.type}
                    employeeName={selectedReport.employeeName}
                    onClose={() => setSelectedReport(null)}
                />
            )}
        </div>
    );
};

export default EmployeeData;
