import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useOrg } from '../contexts/OrgContext';
import { useAuth } from '../contexts/AuthContext';
import { secureApi } from '../services/secureApi';
import { Employee } from '../types';
import { EMPLOYEE_QUESTIONS } from '../employeeQuestions';

interface EmployeeSubmission {
    employeeId: string;
    answers: Record<string, string>;
    submittedAt: number;
    employee?: Employee;
}

const Submissions: React.FC = () => {
    const navigate = useNavigate();
    const { employees, user, isOwner, orgId } = useOrg();
    const [submissions, setSubmissions] = useState<Record<string, EmployeeSubmission>>({});
    const [selectedEmployee, setSelectedEmployee] = useState<Employee | null>(null);
    const [searchQuery, setSearchQuery] = useState('');
    const [loading, setLoading] = useState(true);

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

    // Load submissions on component mount
    useEffect(() => {
        const loadSubmissions = async () => {
            try {
                setLoading(true);
                // Use the secure API service to get submissions
                const data = await secureApi.getSubmissions();

                if (data && data.submissions) {
                    // Transform submissions to include employee data
                    const submissionsWithEmployees: Record<string, EmployeeSubmission> = {};

                    Object.entries(data.submissions).forEach(([employeeId, submission]) => {
                        const employee = employees.find(emp => emp.id === employeeId);
                        if (employee) {
                            submissionsWithEmployees[employeeId] = {
                                ...submission as EmployeeSubmission,
                                employee
                            };
                        }
                    });

                    setSubmissions(submissionsWithEmployees);

                    // Auto-select first employee with submission
                    const employeesWithSubmissions = employees.filter(emp => submissionsWithEmployees[emp.id]);
                    if (employeesWithSubmissions.length > 0) {
                        setSelectedEmployee(employeesWithSubmissions[0]);
                    }
                } else {
                    console.warn('No submissions data received from API');
                    // Load demo data for development if no real data
                    loadDemoSubmissions();
                }
            } catch (error) {
                console.error('Error loading submissions:', error);
                // Load demo data for development
                loadDemoSubmissions();
            } finally {
                setLoading(false);
            }
        };

        if (employees.length > 0) {
            loadSubmissions();
        } else {
            setLoading(false);
        }
    }, [employees]);

    const loadDemoSubmissions = () => {
        // Demo submission data for testing
        const demoSubmissions: Record<string, EmployeeSubmission> = {};

        employees.forEach((employee, index) => {
            if (index < 3) { // Only add submissions for first 3 employees
                console.log(employee);
                demoSubmissions[employee.id] = {
                    employeeId: employee.id,
                    employee,
                    submittedAt: Date.now() - (index * 86400000), // Stagger dates
                    answers: {
                        full_name: employee.name,
                        email: employee.email,
                        title_department: employee.role || 'Team Member',
                        mission: 'To empower small businesses with AI-driven automation tools that increase efficiency and reduce operational overhead.',
                        mission_evolution: 'We shifted from general SaaS tools to vertical-specific solutions, with deeper integrations and onboarding support.',
                        vision: 'To become the leading AI operations platform for SMBs in North America, serving over 100,000 customers.',
                        advantages: 'Fast product iteration enabled by in-house AI capabilities\nDeep customer understanding from vertical specialization\nHigh customer retention due to integrated onboarding',
                        vulnerabilities: 'Dependence on a single marketing channel, weak middle management, and rising customer acquisition costs.',
                        role_clarity: 'I understand my role clearly and feel aligned with company objectives.',
                        performance_output: 'I consistently deliver high-quality work and meet deadlines.',
                        collaboration: 'I work well with my team and communicate effectively.',
                        additional_feedback: 'I would appreciate more structured processes and clearer communication channels.'
                    }
                };
            }
        });

        setSubmissions(demoSubmissions);
        const employeesWithSubmissions = employees.filter(emp => demoSubmissions[emp.id]);
        if (employeesWithSubmissions.length > 0) {
            setSelectedEmployee(employeesWithSubmissions[0]);
        }
    };

    // Filter employees: show only those with submissions, and apply search
    const visibleEmployees = employees
        .filter(emp => submissions[emp.id]) // Only employees with submissions
        .filter(emp => emp.name.toLowerCase().includes(searchQuery.toLowerCase()))
        .sort((a, b) => a.name.localeCompare(b.name));

    const handleEmployeeSelect = (employee: Employee) => {
        setSelectedEmployee(employee);
    };

    const handleViewReport = () => {
        if (selectedEmployee) {
            // Navigate to reports page with the selected employee
            navigate('/reports', { state: { selectedEmployeeId: selectedEmployee.id } });
        }
    };

    const handleChatWithAI = () => {
        if (selectedEmployee) {
            // Navigate to chat page with employee context
            navigate('/chat', { state: { employeeContext: selectedEmployee } });
        }
    };

    // Get questions and answers for selected employee
    const getEmployeeQuestionsAndAnswers = () => {
        if (!selectedEmployee || !submissions[selectedEmployee.id]) {
            return [];
        }

        const submission = submissions[selectedEmployee.id];
        const questionsAndAnswers: Array<{ question: string; answer: string; isLong?: boolean }> = [];

        // Handle different submission formats
        let submissionAnswers: Record<string, string> = {};

        if (submission.answers) {
            if (Array.isArray(submission.answers)) {
                // If answers is an array of {question, answer} objects
                submissionAnswers = submission.answers.reduce((acc, item: any) => {
                    if (item.question && item.answer) {
                        acc[item.question] = item.answer;
                    }
                    return acc;
                }, {} as Record<string, string>);
            } else {
                // If answers is already a key-value object
                submissionAnswers = submission.answers as Record<string, string>;
            }
        }

        // If we have structured answers, map them to questions
        if (Object.keys(submissionAnswers).length > 0) {
            // Try to match with EMPLOYEE_QUESTIONS first
            EMPLOYEE_QUESTIONS.forEach(q => {
                const answer = submissionAnswers[q.id];
                if (answer && answer.trim()) {
                    questionsAndAnswers.push({
                        question: q.prompt,
                        answer: answer,
                        isLong: answer.length > 150
                    });
                }
            });

            // Add any additional answers not in EMPLOYEE_QUESTIONS
            Object.entries(submissionAnswers).forEach(([key, answer]) => {
                if (answer && ((typeof answer === 'string' && answer.trim()) || typeof answer === 'boolean' || typeof answer === 'number') && !EMPLOYEE_QUESTIONS.find(q => q.id === key)) {
                    // Format the key as a readable question
                    const formattedQuestion = key.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
                    questionsAndAnswers.push({
                        question: formattedQuestion,
                        answer: answer,
                        isLong: answer.length > 150
                    });
                }
            });
        }

        return questionsAndAnswers;
    };

    if (loading) {
        return (
            <div className="flex-1 flex items-center justify-center">
                <div className="text-center">
                    <h3 className="text-lg font-semibold text-[--Neutrals-NeutralSlate950] mb-2">
                        Loading Submissions...
                    </h3>
                </div>
            </div>
        );
    }

    return (
        <div className="h-full flex-1 self-stretch rounded-3xl shadow-[0px_0px_15px_0px_rgba(0,0,0,0.08)] flex justify-between items-start overflow-hidden">
            {/* Middle Section - Employee List */}
            <div className="flex-1 self-stretch bg-[--Neutrals-NeutralSlate0] flex justify-start items-center">
                <div className="flex-1 self-stretch max-w-64 min-w-64 border-r border-[--Neutrals-NeutralSlate200] 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-[--Neutrals-NeutralSlate950] text-base font-medium font-['Inter'] leading-normal">Employees</div>
                    </div>
                    <div className="self-stretch flex flex-col justify-start items-start gap-2">
                        {/* Search */}
                        <div className="self-stretch px-2.5 flex flex-col justify-start items-start gap-2">
                            <div className="self-stretch flex flex-col justify-start items-start gap-1">
                                <div className="self-stretch px-4 py-3 bg-[--Neutrals-NeutralSlate100] rounded-[999px] inline-flex justify-start items-center gap-2 overflow-hidden">
                                    <div className="relative">
                                        <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                                            <path d="M17.5 17.5L14.5834 14.5833M16.6667 9.58333C16.6667 13.4954 13.4954 16.6667 9.58333 16.6667C5.67132 16.6667 2.5 13.4954 2.5 9.58333C2.5 5.67132 5.67132 2.5 9.58333 2.5C13.4954 2.5 16.6667 5.67132 16.6667 9.58333Z" stroke="var(--Neutrals-NeutralSlate500, #717680)" strokeWidth="1.5" strokeMiterlimit="10" strokeLinecap="round" strokeLinejoin="round" />
                                        </svg>
                                    </div>
                                    <input
                                        type="text"
                                        placeholder="search team"
                                        value={searchQuery}
                                        onChange={(e) => setSearchQuery(e.target.value)}
                                        className="flex-1 bg-transparent text-[--Neutrals-NeutralSlate500] text-sm font-normal font-['Inter'] leading-tight outline-none"
                                    />
                                </div>
                            </div>
                        </div>

                        {/* Employee List */}
                        <div className="self-stretch px-3 flex flex-col justify-start items-start">
                            {visibleEmployees.length === 0 ? (
                                <div className="self-stretch p-4 text-center text-[--Neutrals-NeutralSlate500] text-sm">
                                    {searchQuery ? 'No employees found matching your search.' : 'No employee submissions found.'}
                                </div>
                            ) : (
                                visibleEmployees.map((employee) => (
                                    <div
                                        key={employee.id}
                                        className={`self-stretch p-2 rounded-full shadow-[0px_1px_2px_0px_rgba(10,13,20,0.03)] inline-flex justify-start items-center gap-2 overflow-hidden cursor-pointer ${selectedEmployee?.id === employee.id ? 'bg-[--Neutrals-NeutralSlate100]' : ''
                                            }`}
                                        onClick={() => handleEmployeeSelect(employee)}
                                    >
                                        <div className="w-7 h-7 p-1 bg-[--Neutrals-NeutralSlate700] rounded-[666.67px] flex justify-center items-center">
                                            <div className="text-center justify-start text-[--Neutrals-NeutralSlate0] text-xs font-medium font-['Inter'] leading-none">
                                                {employee.initials}
                                            </div>
                                        </div>
                                        <div className="flex-1 justify-start text-[--Neutrals-NeutralSlate800] text-sm font-normal font-['Inter'] leading-tight">
                                            {employee.name}
                                        </div>
                                    </div>
                                ))
                            )}
                        </div>
                    </div>
                </div>

                {/* Main Content Area */}
                <div className="flex-1 self-stretch inline-flex flex-col justify-start items-start">
                    {selectedEmployee ? (
                        <SubmissionContent
                            employee={selectedEmployee}
                            submission={submissions[selectedEmployee.id]}
                            onViewReport={handleViewReport}
                            onChatWithAI={handleChatWithAI}
                            questionsAndAnswers={getEmployeeQuestionsAndAnswers()}
                        />
                    ) : (
                        <div className="flex-1 self-stretch flex items-center justify-center">
                            <div className="text-center">
                                <h3 className="text-lg font-semibold text-[--Neutrals-NeutralSlate950] mb-2">
                                    Select an Employee
                                </h3>
                                <p className="text-[--Neutrals-NeutralSlate500]">
                                    Choose an employee from the list to view their submission answers.
                                </p>
                            </div>
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
};

// Component for displaying submission content
const SubmissionContent: React.FC<{
    employee: Employee;
    submission: EmployeeSubmission;
    onViewReport: () => void;
    onChatWithAI: () => void;
    questionsAndAnswers: Array<{ question: string; answer: string; isLong?: boolean }>;
}> = ({ employee, submission, onViewReport, onChatWithAI, questionsAndAnswers }) => {
    return (
        <>
            {/* Header */}
            <div className="self-stretch px-5 py-3 inline-flex justify-start items-center gap-2.5">
                <div className="flex-1 justify-start text-[--Neutrals-NeutralSlate800] text-base font-medium font-['Inter'] leading-normal">
                    {employee.name}'s Answers
                </div>
                <div className="flex justify-start items-center gap-3">
                    <button
                        onClick={onChatWithAI}
                        className="px-3 py-2.5 bg-[--Neutrals-NeutralSlate100] rounded-[999px] flex justify-center items-center gap-1 overflow-hidden hover:bg-[--Neutrals-NeutralSlate200] transition-colors"
                    >
                        <div className="relative">
                            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <path d="M13.9997 7.66667C13.9997 10.7963 11.4627 13.3333 8.33304 13.3333C7.61519 13.3333 6.92851 13.1999 6.29648 12.9564C6.18092 12.9118 6.12314 12.8896 6.0772 12.879C6.03201 12.8686 5.99929 12.8642 5.95295 12.8624C5.90583 12.8606 5.85414 12.866 5.75075 12.8767L2.33674 13.2296C2.01124 13.2632 1.84849 13.2801 1.75249 13.2215C1.66887 13.1705 1.61192 13.0853 1.59676 12.9885C1.57936 12.8774 1.65713 12.7335 1.81267 12.4456L2.9031 10.4272C2.99291 10.261 3.03781 10.1779 3.05814 10.098C3.07823 10.019 3.08309 9.96213 3.07666 9.88095C3.07016 9.79875 3.03409 9.69175 2.96196 9.47774C2.77027 8.90906 2.66638 8.3 2.66638 7.66667C2.66638 4.53705 5.20343 2 8.33304 2C11.4627 2 13.9997 4.53705 13.9997 7.66667Z" stroke="var(--Neutrals-NeutralSlate800, #252B37)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                            </svg>
                        </div>
                        <div className="px-1 flex justify-center items-center">
                            <div className="justify-center text-[--Neutrals-NeutralSlate800] text-sm font-medium font-['Inter'] leading-tight">Chat With AI</div>
                        </div>
                    </button>
                    <button
                        onClick={onViewReport}
                        className="px-3 py-2.5 bg-[--Neutrals-NeutralSlate100] rounded-[999px] flex justify-center items-center gap-1 overflow-hidden hover:bg-[--Neutrals-NeutralSlate200] transition-colors"
                    >
                        <div className="relative">
                            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <g clipPath="url(#clip0_1042_7203)">
                                    <path d="M8.00004 1.33398C8.87552 1.33398 9.74243 1.50642 10.5513 1.84145C11.3601 2.17649 12.095 2.66755 12.7141 3.28661C13.3331 3.90567 13.8242 4.64059 14.1592 5.44943C14.4943 6.25827 14.6667 7.12518 14.6667 8.00066M8.00004 1.33398V8.00065M8.00004 1.33398C4.31814 1.33398 1.33337 4.31875 1.33337 8.00065C1.33337 11.6825 4.31814 14.6673 8.00004 14.6673C11.6819 14.6673 14.6667 11.6826 14.6667 8.00066M8.00004 1.33398C11.6819 1.33398 14.6667 4.31876 14.6667 8.00066M14.6667 8.00066L8.00004 8.00065M14.6667 8.00066C14.6667 9.05273 14.4177 10.0899 13.9401 11.0273C13.4625 11.9647 12.7698 12.7757 11.9186 13.3941L8.00004 8.00065" stroke="var(--Neutrals-NeutralSlate800, #252B37)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                                </g>
                                <defs>
                                    <clipPath id="clip0_1042_7203">
                                        <rect width="16" height="16" fill="white" />
                                    </clipPath>
                                </defs>
                            </svg>
                        </div>
                        <div className="px-1 flex justify-center items-center">
                            <div className="justify-center text-[--Neutrals-NeutralSlate800] text-sm font-medium font-['Inter'] leading-tight">View Report</div>
                        </div>
                    </button>
                </div>
            </div>

            {/* Content */}
            <div className="self-stretch px-5 py-2 flex flex-col justify-start items-start gap-4 overflow-y-auto">
                {questionsAndAnswers.length === 0 ? (
                    <div className="self-stretch text-center py-8">
                        <p className="text-[--Neutrals-NeutralSlate500]">No submission data available for this employee.</p>
                    </div>
                ) : (
                    questionsAndAnswers.map((qa, index) => (
                        <div
                            key={index}
                            className={`self-stretch p-3 rounded-2xl shadow-[0px_1px_2px_0px_rgba(0,0,0,0.02)] flex flex-col justify-center items-start gap-2 ${qa.isLong ? 'bg-[--Neutrals-NeutralSlate100]' : 'bg-[--Neutrals-NeutralSlate100]'
                                }`}
                        >
                            <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-[--Neutrals-NeutralSlate300] text-base font-semibold font-['Inter'] leading-normal">Q</div>
                                    <div className="flex-1 justify-start text-[--Neutrals-NeutralSlate600] 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-[--Neutrals-NeutralSlate300] text-base font-semibold font-['Inter'] leading-normal">A</div>
                                    <div className="flex-1 justify-start text-[--Neutrals-NeutralSlate800] text-base font-normal font-['Inter'] leading-normal">
                                        {qa.answer}
                                    </div>
                                </div>
                            </div>
                        </div>
                    ))
                )}
            </div>
        </>
    );
};

export default Submissions;