import React, { useState, useEffect, useRef, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import axiosInstance from '../../../utils/axiosConfig';
import { SUBMISSIONS_URL } from '../../../utils/config';
import Pagination from '../../common/Pagination';
import '../activitylog/styles/ActivityLogControls.css';
import './styles/SubmissionsList.css';

const ENTRIES_PER_PAGE_OPTIONS = [10, 25, 50, 100];
const DEFAULT_ENTRIES_PER_PAGE = 10;

const VIEW_LIST = 'list';
const VIEW_CARD = 'card';

const SubmissionsList = () => {
    const navigate = useNavigate();
    const [submissions, setSubmissions] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [viewMode, setViewMode] = useState(VIEW_LIST);
    const [searchQuery, setSearchQuery] = useState('');
    const searchInputRef = useRef(null);
    const [currentPage, setCurrentPage] = useState(1);
    const [entriesPerPage, setEntriesPerPage] = useState(DEFAULT_ENTRIES_PER_PAGE);

    const handleEntriesPerPageChange = (e) => {
        setEntriesPerPage(Number(e.target.value));
        setCurrentPage(1);
    };

    useEffect(() => {
        const fetchSubmissions = async () => {
            try {
                setLoading(true);
                const response = await axiosInstance.get(SUBMISSIONS_URL);

                if (response.data.success) {
                    const data = response.data.data || [];
                    // Last (most recent) submission first in the list
                    data.sort((a, b) => new Date(b.created_at || 0) - new Date(a.created_at || 0));
                    setSubmissions(data);
                } else {
                    setError('Failed to load submissions.');
                }
            } catch (error) {
                console.error('Error fetching submissions:', error);
                setError('Failed to load submissions. Please refresh the page.');
            } finally {
                setLoading(false);
            }
        };

        fetchSubmissions();
    }, []);

    const formatDate = (dateString) => {
        if (!dateString) return 'N/A';
        const date = new Date(dateString);
        return date.toLocaleDateString('en-US', {
            year: 'numeric',
            month: 'short',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
        });
    };

    // Filter submissions by search (ID, form title, audit name, submitter)
    const filteredSubmissions = searchQuery.trim() === ''
        ? submissions
        : submissions.filter(sub => {
            const q = searchQuery.trim().toLowerCase();
            const idMatch = String(sub.submission_id || '').toLowerCase().includes(q);
            const formMatch = (sub.form_title || '').toLowerCase().includes(q);
            const auditMatch = (sub.audit_name || '').toLowerCase().includes(q);
            const submitterMatch = (sub.submitter_name || '').toLowerCase().includes(q);
            return idMatch || formMatch || auditMatch || submitterMatch;
        });

    const totalEntries = filteredSubmissions.length;
    const totalPages = Math.max(1, Math.ceil(totalEntries / entriesPerPage));
    const paginatedSubmissions = useMemo(() => {
        const start = (currentPage - 1) * entriesPerPage;
        return filteredSubmissions.slice(start, start + entriesPerPage);
    }, [filteredSubmissions, currentPage, entriesPerPage]);

    useEffect(() => {
        if (currentPage > totalPages) setCurrentPage(1);
    }, [totalPages, currentPage]);

    const renderTableBody = (list, startIndex = 0) => (
        list.map((submission, index) => (
            <tr key={submission.submission_id}>
                <td>{startIndex + index + 1}</td>
                <td>{submission.form_title || 'N/A'}</td>
                <td>{submission.audit_name || 'N/A'}</td>
                <td>{submission.submitter_name || 'N/A'}</td>
                <td>{formatDate(submission.created_at)}</td>
                <td>
                    <button
                        className="btn btn-primary btn-small"
                        onClick={() => navigate(`/view-submission/${submission.submission_id}`)}
                    >
                        View
                    </button>
                </td>
            </tr>
        ))
    );

    if (loading) {
        return (
            <div className="submissions-list-container">
                <div className="submissions-loading">
                    <p>Loading submissions...</p>
                </div>
            </div>
        );
    }

    return (
        <div className="submissions-list-container">
            <div className="submissions-list-header">
                <h1 className="submissions-list-title">Observation Submissions</h1>
                <button
                    className="btn btn-secondary"
                    onClick={() => navigate('/create-audit')}
                >
                    Back to Create Audit
                </button>
            </div>

            {submissions.length > 0 && (
                <>
                <div className="activity-log-controls-bar submissions-list-controls">
                    <div className="activity-log-controls-left">
                        <div className="show-entries">
                            <label>Show</label>
                            <select
                                className="entries-select"
                                value={entriesPerPage}
                                onChange={handleEntriesPerPageChange}
                                aria-label="Entries per page"
                            >
                                {ENTRIES_PER_PAGE_OPTIONS.map((n) => (
                                    <option key={n} value={n}>{n}</option>
                                ))}
                            </select>
                            <span>entries</span>
                        </div>
                    </div>
                </div>
                <div className="submissions-search-bar">
                    <input
                        ref={searchInputRef}
                        type="text"
                        className="submissions-search-input"
                        placeholder="Search by ID, observation, audit, or submitter..."
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        onKeyDown={(e) => e.key === 'Enter' && e.target.blur()}
                    />
                    <button
                        type="button"
                        className="btn btn-primary submissions-search-btn"
                        onClick={() => searchInputRef.current?.focus()}
                        aria-label="Search"
                    >
                        Search
                    </button>
                    {searchQuery.trim() !== '' && (
                        <button
                            type="button"
                            className="btn btn-secondary submissions-clear-btn"
                            onClick={() => setSearchQuery('')}
                        >
                            Clear
                        </button>
                    )}
                </div>
                <div className="submissions-view-tabs">
                    <button
                        type="button"
                        className={`submissions-tab ${viewMode === VIEW_LIST ? 'active' : ''}`}
                        onClick={() => setViewMode(VIEW_LIST)}
                    >
                        <span className="submissions-tab-label">List view</span>
                        <span className="submissions-tab-desc">Table layout for detailed scanning</span>
                    </button>
                    <button
                        type="button"
                        className={`submissions-tab ${viewMode === VIEW_CARD ? 'active' : ''}`}
                        onClick={() => setViewMode(VIEW_CARD)}
                    >
                        <span className="submissions-tab-label">Card view</span>
                        <span className="submissions-tab-desc">Grid of submission cards</span>
                    </button>
                </div>
                </>
            )}

            {error && (
                <div className="error-message">
                    {error}
                </div>
            )}

            {submissions.length === 0 ? (
                <div className="no-submissions">
                    <p>No submissions found.</p>
                </div>
            ) : viewMode === VIEW_LIST ? (
                <>
                    {searchQuery.trim() !== '' && (
                        <p className="submissions-search-result-hint">
                            {filteredSubmissions.length === 0
                                ? 'No submissions match your search.'
                                : `Showing ${filteredSubmissions.length} of ${submissions.length} submission${submissions.length !== 1 ? 's' : ''}.`
                            }
                        </p>
                    )}
                    <div className="submissions-table-container">
                        <table className="submissions-table">
                            <thead>
                                <tr>
                                    <th>S.No.</th>
                                    <th>Observation Title</th>
                                    <th>Audit Name</th>
                                    <th>Submitted By</th>
                                    <th>Submitted Date</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                {filteredSubmissions.length === 0 ? (
                                    <tr>
                                        <td colSpan={6} className="submissions-empty-row">
                                            No submissions to show.
                                        </td>
                                    </tr>
                                ) : (
                                    renderTableBody(paginatedSubmissions, (currentPage - 1) * entriesPerPage)
                                )}
                            </tbody>
                        </table>
                    </div>
                    {filteredSubmissions.length > 0 && (
                        <Pagination
                            currentPage={currentPage}
                            totalPages={totalPages}
                            totalEntries={totalEntries}
                            entriesPerPage={entriesPerPage}
                            onPageChange={setCurrentPage}
                        />
                    )}
                </>
            ) : (
                <div className="submissions-cards">
                    {searchQuery.trim() !== '' && (
                        <p className="submissions-search-result-hint">
                            {filteredSubmissions.length === 0
                                ? 'No submissions match your search.'
                                : `Showing ${filteredSubmissions.length} of ${submissions.length} submission${submissions.length !== 1 ? 's' : ''}.`
                            }
                        </p>
                    )}
                    {filteredSubmissions.length === 0 ? (
                        <div className="no-submissions">
                            <p>No submissions to show.</p>
                        </div>
                    ) : (
                        <div className="submissions-card-grid">
                            {paginatedSubmissions.map((submission) => (
                                <article key={submission.submission_id} className="submission-card">
                                    <div className="submission-card-header">
                                        <h3 className="submission-card-title">
                                            {submission.form_title || 'N/A'}
                                        </h3>
                                        <span className="submission-card-id">
                                            #{submission.submission_id}
                                        </span>
                                    </div>
                                    <div className="submission-card-body">
                                        <div className="submission-card-row">
                                            <span className="submission-card-label">Audit</span>
                                            <span className="submission-card-value">
                                                {submission.audit_name || 'N/A'}
                                            </span>
                                        </div>
                                        <div className="submission-card-row">
                                            <span className="submission-card-label">Submitted by</span>
                                            <span className="submission-card-value">
                                                {submission.submitter_name || 'N/A'}
                                            </span>
                                        </div>
                                        <div className="submission-card-row">
                                            <span className="submission-card-label">Date</span>
                                            <span className="submission-card-value">
                                                {formatDate(submission.created_at)}
                                            </span>
                                        </div>
                                    </div>
                                    <div className="submission-card-actions">
                                        <button
                                            className="btn btn-primary btn-small"
                                            onClick={() => navigate(`/view-submission/${submission.submission_id}`)}
                                        >
                                            View
                                        </button>
                                    </div>
                                </article>
                            ))}
                        </div>
                    )}
                    {filteredSubmissions.length > 0 && (
                        <Pagination
                            currentPage={currentPage}
                            totalPages={totalPages}
                            totalEntries={totalEntries}
                            entriesPerPage={entriesPerPage}
                            onPageChange={setCurrentPage}
                        />
                    )}
                </div>
            )}
        </div>
    );
};

export default SubmissionsList;
