import React, { useState } from 'react';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import {
    FaCheckCircle,
    FaTimesCircle,
    FaExclamationCircle,
    FaInfoCircle,
    FaUsers,
    FaExclamationTriangle,
    FaLock
} from 'react-icons/fa';
import Modal from '../Modal';
import UserTable from '../Tables/UserTable';
import ParseExcelErrors from './ExcelError';
import { errorsByRows } from '@/utils/excel.errors';
import { ClassroomTransferState } from '../Imports/StudentClassroomTransfer';

const ClassroomImportSummary: React.FC<{ state: ClassroomTransferState }> = ({ state }) => {
    const [showErrorsModal, setShowErrorsModal] = useState(false);
    const [showDuplicatesModal, setShowDuplicatesModal] = useState(false);
    const [showNotFoundModal, setShowNotFoundModal] = useState(false);
    const [showOtherEntityModal, setShowOtherEntityModal] = useState(false);
    const [showAlreadyInClassModal, setShowAlreadyInClassModal] = useState(false);
    const [showMismatchesModal, setShowMismatchesModal] = useState(false);

    const errorCount = state.parsedExcel?.errors ?
        Object.entries(errorsByRows(state.parsedExcel.errors)).length : 0;

    const fieldMapper: { [key: string]: string } = {
        "firstName": "First Name",
        "lastName": "Last Name",
        "studentID": "Student ID",
        "phone": "Phone Number",
        "passport_id": "Passport/National ID",
        "country": "Country"
    }

    return (
        <>
            <Card>
                <CardHeader>
                    <CardTitle className="flex justify-center font-semibold text-xl">
                        Import Summary
                    </CardTitle>
                </CardHeader>
                <CardContent>
                    <div className="space-y-4">
                        <div className="flex items-center gap-2">
                            <FaInfoCircle className="h-5 w-5 text-blue-500" />
                            <span>
                                {`${state.parsedExcel?.rows?.length || 0} total spreadsheet rows`}
                                {state.parsedExcel && state.parsedExcel.rows && state.parsedExcel.rows.filter(row => row === null).length > 0 && (
                                    <span className="text-gray-500">
                                        {` (${state.parsedExcel.rows.filter((row: any) => row === null).length} empty)`}
                                    </span>
                                )}
                            </span>
                        </div>

                        <div className="flex items-center justify-between">
                            <div className="flex items-center gap-2">
                                {state.imports.length > 0 ? (
                                    <FaCheckCircle className="h-5 w-5 text-green-500" />
                                ) : (
                                    <FaTimesCircle className="h-5 w-5 text-red-500" />
                                )}
                                <span>{`${state.imports.length} user${state.imports.length !== 1 ? 's' : ''} ready for transfer`}</span>
                            </div>
                        </div>

                        {state.notFoundUsers.length > 0 && (
                            <div className="flex items-center justify-between">
                                <div className="flex items-center gap-2">
                                    <FaTimesCircle className="h-5 w-5 text-red-500" />
                                    <span>{`${state.notFoundUsers.length} user${state.notFoundUsers.length !== 1 ? 's' : ''} not found`}</span>
                                </div>
                                <button
                                    onClick={() => setShowNotFoundModal(true)}
                                    className="inline-flex items-center justify-center px-3 py-1.5 text-sm font-medium text-gray-700 hover:text-gray-900 hover:bg-gray-100 rounded-md transition-colors"
                                >
                                    View details
                                </button>
                            </div>
                        )}

                        {state.otherEntityUsers.length > 0 && (
                            <div className="flex items-center justify-between">
                                <div className="flex items-center gap-2">
                                    <FaExclamationCircle className="h-5 w-5 text-yellow-500" />
                                    <span>{`${state.otherEntityUsers.length} user${state.otherEntityUsers.length !== 1 ? 's' : ''} from different entities`}</span>
                                </div>
                                <button
                                    onClick={() => setShowOtherEntityModal(true)}
                                    className="inline-flex items-center justify-center px-3 py-1.5 text-sm font-medium text-gray-700 hover:text-gray-900 hover:bg-gray-100 rounded-md transition-colors"
                                >
                                    View details
                                </button>
                            </div>
                        )}

                        {state.alreadyInClass.length > 0 && (
                            <div className="flex items-center justify-between">
                                <div className="flex items-center gap-2">
                                    <FaUsers className="h-5 w-5 text-blue-500" />
                                    <span>{`${state.alreadyInClass.length} user${state.alreadyInClass.length !== 1 ? 's' : ''} already in class`}</span>
                                </div>
                                <button
                                    onClick={() => setShowAlreadyInClassModal(true)}
                                    className="inline-flex items-center justify-center px-3 py-1.5 text-sm font-medium text-gray-700 hover:text-gray-900 hover:bg-gray-100 rounded-md transition-colors"
                                >
                                    View details
                                </button>
                            </div>
                        )}

                        {state.duplicatedRows.length > 0 && (
                            <div className="flex items-center justify-between">
                                <div className="flex items-center gap-2">
                                    <FaExclamationCircle className="h-5 w-5 text-yellow-500" />
                                    <span>{state.duplicatedRows.length} duplicate entries in file</span>
                                </div>
                                <button
                                    onClick={() => setShowDuplicatesModal(true)}
                                    className="inline-flex items-center justify-center px-3 py-1.5 text-sm font-medium text-gray-700 hover:text-gray-900 hover:bg-gray-100 rounded-md transition-colors"
                                >
                                    View duplicates
                                </button>
                            </div>
                        )}

                        {state.userMismatches.length > 0 && (
                            <div className="flex items-center justify-between">
                                <div className="flex items-center gap-2">
                                    <FaExclamationTriangle className="h-5 w-5 text-orange-500" />
                                    <span>{state.userMismatches.length} users with mismatched information</span>
                                </div>
                                <button
                                    onClick={() => setShowMismatchesModal(true)}
                                    className="inline-flex items-center justify-center px-3 py-1.5 text-sm font-medium text-gray-700 hover:text-gray-900 hover:bg-gray-100 rounded-md transition-colors"
                                >
                                    View mismatches
                                </button>
                            </div>
                        )}

                        {errorCount > 0 && (
                            <div className="flex items-center justify-between">
                                <div className="flex items-center gap-2">
                                    <FaTimesCircle className="h-5 w-5 text-red-500" />
                                    <span>{errorCount} invalid rows</span>
                                </div>
                                <button
                                    onClick={() => setShowErrorsModal(true)}
                                    className="inline-flex items-center justify-center px-3 py-1.5 text-sm font-medium text-gray-700 hover:text-gray-900 hover:bg-gray-100 rounded-md transition-colors"
                                >
                                    View errors
                                </button>
                            </div>
                        )}
                    </div>

                    {(state.duplicatedRows.length > 0 || state.userMismatches.length > 0 || errorCount > 0 ||
                        state.notFoundUsers.length > 0 || state.otherEntityUsers.length > 0) && (
                            <div className="mt-6 rounded-lg border border-red-100 bg-white p-6">
                                <div className="flex items-start gap-4">
                                    <div className="mt-1">
                                        <FaExclamationTriangle className="h-5 w-5 text-red-400" />
                                    </div>
                                    <div className="flex-1 space-y-3">
                                        <p className="font-medium text-gray-900">
                                            The following will be excluded from transfer:
                                        </p>
                                        <ul className="space-y-4">
                                            {state.notFoundUsers.length > 0 && (
                                                <li>
                                                    <div className="text-gray-700">
                                                        <span className="font-medium">{state.notFoundUsers.length}</span> users not found
                                                    </div>
                                                </li>
                                            )}
                                            {state.otherEntityUsers.length > 0 && (
                                                <li>
                                                    <div className="text-gray-700">
                                                        <span className="font-medium">{state.otherEntityUsers.length}</span> users from different entities
                                                    </div>
                                                </li>
                                            )}
                                            {state.duplicatedRows.length > 0 && (
                                                <li>
                                                    <div className="text-gray-700">
                                                        <span className="font-medium">{state.duplicatedRows.length}</span> duplicate entries
                                                    </div>
                                                </li>
                                            )}

                                            {state.userMismatches.length > 0 && (
                                                <li>
                                                    <div className="text-gray-700">
                                                        <span className="font-medium">{state.userMismatches.length}</span> users with mismatched information
                                                    </div>
                                                </li>
                                            )}
                                            {state.alreadyInClass && state.alreadyInClass.length > 0 && (
                                                <li>
                                                    <div className="text-gray-700">
                                                        <span className="font-medium">{state.alreadyInClass.length}</span> users that are already assigned to the classroom
                                                    </div>
                                                </li>
                                            )}
                                            {errorCount > 0 && (
                                                <li>
                                                    <div className="text-gray-700">
                                                        <span className="font-medium">{errorCount}</span> rows with invalid information
                                                    </div>
                                                </li>
                                            )}
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        )}
                </CardContent>
            </Card>
            <Modal isOpen={showErrorsModal} onClose={() => setShowErrorsModal(false)}>
                <>
                    <div className="flex items-center gap-2 mb-6">
                        <FaTimesCircle className="w-5 h-5 text-red-500" />
                        <h2 className="text-lg font-semibold text-gray-900">Validation Errors</h2>
                    </div>
                    <ParseExcelErrors errors={state.parsedExcel?.errors || []} />
                </>
            </Modal>

            <Modal isOpen={showNotFoundModal} onClose={() => setShowNotFoundModal(false)} maxWidth="max-w-[85%]">
                <>
                    <div className="flex items-center gap-2 mb-6">
                        <FaTimesCircle className="w-5 h-5 text-red-500" />
                        <h2 className="text-lg font-semibold text-gray-900">Users Not Found</h2>
                    </div>
                    <UserTable users={state.notFoundUsers} />
                </>
            </Modal>

            <Modal isOpen={showOtherEntityModal} onClose={() => setShowOtherEntityModal(false)} maxWidth="max-w-[85%]">
                <>
                    <div className="flex items-center gap-2 mb-6">
                        <FaExclamationCircle className="w-5 h-5 text-yellow-500" />
                        <h2 className="text-lg font-semibold text-gray-900">Users from Different Entities</h2>
                    </div>
                    <UserTable users={state.otherEntityUsers} />
                </>
            </Modal>

            <Modal isOpen={showAlreadyInClassModal} onClose={() => setShowAlreadyInClassModal(false)} maxWidth="max-w-[85%]">
                <>
                    <div className="flex items-center gap-2 mb-6">
                        <FaUsers className="w-5 h-5 text-blue-500" />
                        <h2 className="text-lg font-semibold text-gray-900">Users Already in Class</h2>
                    </div>
                    <UserTable users={state.alreadyInClass} />
                </>
            </Modal>

            <Modal isOpen={showDuplicatesModal} onClose={() => setShowDuplicatesModal(false)}>
                <>
                    <div className="flex items-center gap-2 mb-6">
                        <FaExclamationCircle className="w-5 h-5 text-yellow-500" />
                        <h2 className="text-lg font-semibold text-gray-900">Duplicate Entries</h2>
                    </div>
                    <div className="space-y-3">
                        {state.duplicatedRows.map((duplicate) => (
                            <div
                                key={`${duplicate.email}-${duplicate.classroom}-${duplicate.rowNumber}`}
                                className="group relative rounded-lg border border-gray-200 bg-gray-50 p-3 hover:bg-gray-100 transition-colors"
                            >
                                <div className="flex items-start justify-between">
                                    <div>
                                        <span className="font-medium text-gray-900">Row {duplicate.rowNumber}</span>
                                        <div className="mt-1 text-sm text-gray-600">
                                            Email: <span className="text-blue-600 font-medium">{duplicate.email}</span>
                                        </div>
                                        <div className="mt-1 text-sm text-gray-600">
                                            Classroom: <span className="text-blue-600 font-medium">{duplicate.classroom}</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>
                </>
            </Modal>
            <Modal isOpen={showMismatchesModal} onClose={() => setShowMismatchesModal(false)}>
                <>
                    <div className="flex items-center gap-2 mb-6">
                        <FaExclamationTriangle className="w-5 h-5 text-orange-500" />
                        <h2 className="text-lg font-semibold text-gray-900">Mismatched User Information</h2>
                    </div>
                    <div className="space-y-6">
                        {state.userMismatches.map((mismatch) => (
                            <div
                                key={mismatch.email}
                                className="relative rounded-lg border border-gray-200 bg-gray-50 p-4"
                            >
                                <div className="mb-2 font-medium text-gray-900">
                                    Email: {mismatch.email}
                                </div>
                                <div className="text-sm text-gray-600">
                                    Rows: {mismatch.rows.join(', ')}
                                </div>
                                <div className="mt-3 space-y-2">
                                    {mismatch.mismatches.map((field) => (
                                        <div key={field.field} className="pl-4 border-l-2 border-orange-500">
                                            <div className="font-medium text-gray-700">{fieldMapper[field.field]}:</div>
                                            <div className="mt-1 text-sm text-gray-600">
                                                Values: {field.values.join(', ')}
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        ))}
                    </div>
                </>
            </Modal>
        </>
    );
};

export default ClassroomImportSummary;
