import React, { useState } from 'react';
import type { FlaggedItem, ResolvedItem, ErrorItem } from '../types';

interface AuditingProps {
    flaggedItems: FlaggedItem[];
    resolvedItems: ResolvedItem[];
    errorItems: ErrorItem[];
    onNavigate: (item: { campaignName: string, proofName: string, version: number }) => void;
}

const formatDate = (isoString: string) => {
    try {
        return new Date(isoString).toLocaleDateString('en-GB', {
            day: '2-digit',
            month: 'short',
            year: 'numeric',
        });
    } catch (e) {
        return 'Invalid Date';
    }
};

const FlagsTable: React.FC<{ items: FlaggedItem[], onNavigate: AuditingProps['onNavigate'] }> = ({ items, onNavigate }) => (
    <div className="overflow-x-auto">
        <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
                <tr>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">Proof Name</th>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">Proof Version</th>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">Submitter</th>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">Submit Agency</th>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">Agent Flagged</th>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">User Comments</th>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">Date</th>
                </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
                {items.length > 0 ? items.map((item) => (
                    <tr
                        key={item.id}
                        className="hover:bg-gray-100 cursor-pointer"
                        onClick={() => onNavigate(item)}
                        title={`Click to view Version ${item.version} of ${item.proofName}`}
                    >
                        <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-brand-dark-blue">{item.proofName}</td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700">Version {item.version}</td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700">{item.submitter}</td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700">{item.submitAgency}</td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700">{item.agentFlagged}</td>
                        <td className="px-6 py-4 text-sm text-gray-700">
                            <div className="max-w-xs break-words" title={item.comments}>
                                {item.comments || <span className="italic text-gray-400">No comment</span>}
                            </div>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700">{formatDate(item.timestamp)}</td>
                    </tr>
                )) : (
                    <tr>
                        <td colSpan={7} className="text-center py-10 text-gray-500">
                            There are currently no flagged items to audit.
                        </td>
                    </tr>
                )}
            </tbody>
        </table>
    </div>
);

const ResolutionsTable: React.FC<{ items: ResolvedItem[], onNavigate: AuditingProps['onNavigate'] }> = ({ items, onNavigate }) => (
    <div className="overflow-x-auto">
        <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
                <tr>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">Proof Name</th>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">Proof Version</th>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">Submitter</th>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">Submit Agency</th>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">Agent</th>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">Agent Issue</th>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">User Comments</th>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">Date</th>
                </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
                {items.length > 0 ? items.map((item) => (
                    <tr
                        key={item.id}
                        className="hover:bg-gray-100 cursor-pointer"
                        onClick={() => onNavigate(item)}
                        title={`Click to view Version ${item.version} of ${item.proofName}`}
                    >
                        <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-brand-dark-blue">{item.proofName}</td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700">Version {item.version}</td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700">{item.submitter}</td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700">{item.submitAgency}</td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700">{item.agent}</td>
                        <td className="px-6 py-4 text-sm text-gray-700">
                             <div className="max-w-xs break-words" title={item.issue}>{item.issue}</div>
                        </td>
                        <td className="px-6 py-4 text-sm text-gray-700">
                             <div className="max-w-xs break-words" title={item.resolution}>{item.resolution}</div>
                        </td>
                         <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700">{formatDate(item.timestamp)}</td>
                    </tr>
                )) : (
                    <tr>
                        <td colSpan={8} className="text-center py-10 text-gray-500">
                            There are currently no resolved items to audit.
                        </td>
                    </tr>
                )}
            </tbody>
        </table>
    </div>
);

const ErrorsTable: React.FC<{ items: ErrorItem[], onNavigate: AuditingProps['onNavigate'] }> = ({ items, onNavigate }) => (
    <div className="overflow-x-auto">
        <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
                <tr>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">Proof Name</th>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">Proof Version</th>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">Submitter</th>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">Submit Agency</th>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">Error Summary</th>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">Date</th>
                </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
                {items.length > 0 ? items.map((item) => (
                    <tr
                        key={item.id}
                        className="hover:bg-gray-100 cursor-pointer"
                        onClick={() => onNavigate(item)}
                        title={`Click to view Version ${item.version} of ${item.proofName}`}
                    >
                        <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-brand-dark-blue">{item.proofName}</td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700">Version {item.version}</td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700">{item.submitter}</td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700">{item.submitAgency}</td>
                        <td className="px-6 py-4 text-sm text-gray-700">
                            <div className="max-w-md break-words" title={item.errorSummary}>
                                {item.errorSummary}
                            </div>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700">{formatDate(item.timestamp)}</td>
                    </tr>
                )) : (
                    <tr>
                        <td colSpan={6} className="text-center py-10 text-gray-500">
                            There are currently no analysis errors to audit.
                        </td>
                    </tr>
                )}
            </tbody>
        </table>
    </div>
);


export const Auditing: React.FC<AuditingProps> = ({ flaggedItems, resolvedItems, errorItems, onNavigate }) => {
    const [activeTab, setActiveTab] = useState<'Flags' | 'Resolutions' | 'Errors'>('Flags');

    return (
        <div className="p-4 sm:p-6 lg:p-8 h-full bg-brand-gray">
            <header className="mb-8">
                <h1 className="text-3xl lg:text-4xl font-bold text-brand-dark-blue">Auditing</h1>
                <p className="text-base lg:text-lg text-gray-600 mt-1">Review and investigate all user-flagged feedback.</p>
            </header>

            <div className="mb-6 border-b border-gray-200">
                <nav className="-mb-px flex space-x-6" aria-label="Tabs">
                    <button
                        onClick={() => setActiveTab('Flags')}
                        className={`whitespace-nowrap py-3 px-1 border-b-2 font-semibold text-sm transition-colors ${
                            activeTab === 'Flags'
                                ? 'border-brand-accent text-brand-accent'
                                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                        }`}
                        aria-current={activeTab === 'Flags' ? 'page' : undefined}
                    >
                        Flags
                    </button>
                    <button
                        onClick={() => setActiveTab('Resolutions')}
                        className={`whitespace-nowrap py-3 px-1 border-b-2 font-semibold text-sm transition-colors ${
                            activeTab === 'Resolutions'
                                ? 'border-brand-accent text-brand-accent'
                                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                        }`}
                         aria-current={activeTab === 'Resolutions' ? 'page' : undefined}
                    >
                        Resolutions
                    </button>
                    <button
                        onClick={() => setActiveTab('Errors')}
                        className={`whitespace-nowrap py-3 px-1 border-b-2 font-semibold text-sm transition-colors ${
                            activeTab === 'Errors'
                                ? 'border-brand-accent text-brand-accent'
                                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                        }`}
                         aria-current={activeTab === 'Errors' ? 'page' : undefined}
                    >
                        Errors
                    </button>
                </nav>
            </div>

            <section>
                <div className="bg-white rounded-lg shadow-md overflow-hidden border border-gray-200">
                    {activeTab === 'Flags' && <FlagsTable items={flaggedItems} onNavigate={onNavigate} />}
                    {activeTab === 'Resolutions' && <ResolutionsTable items={resolvedItems} onNavigate={onNavigate} />}
                    {activeTab === 'Errors' && <ErrorsTable items={errorItems} onNavigate={onNavigate} />}
                </div>
            </section>
        </div>
    );
};