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

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

const STATUS_FILTER_ALL = 'all';
const STATUS_OPEN = 'Open';
const STATUS_IN_PROGRESS = 'In Progress';
const STATUS_CLOSED = 'Closed';

const getStatusBadgeClass = (statusName) => {
  if (!statusName) return 'audit-status-badge audit-status-unknown';
  const normalized = String(statusName).trim().toLowerCase();
  if (normalized === 'open') return 'audit-status-badge audit-status-open';
  if (normalized === 'in progress') return 'audit-status-badge audit-status-in-progress';
  if (normalized === 'closed') return 'audit-status-badge audit-status-closed';
  return 'audit-status-badge audit-status-unknown';
};

const AUDIT_STATUS_IN_PROGRESS_ID = 3;

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

const AuditStatus = () => {
  const navigate = useNavigate();
  const [audits, setAudits] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [statusFilter, setStatusFilter] = useState(STATUS_FILTER_ALL);
  const [searchQuery, setSearchQuery] = useState('');
  const [settingInProgressId, setSettingInProgressId] = useState(null);
  const [viewMode, setViewMode] = useState(VIEW_LIST);
  const [currentPage, setCurrentPage] = useState(1);
  const [entriesPerPage, setEntriesPerPage] = useState(DEFAULT_ENTRIES_PER_PAGE);

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

  const fetchAudits = async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await axiosInstance.get(AUDITS_URL);
      if (response.data.success && Array.isArray(response.data.data)) {
        setAudits(response.data.data);
      } else {
        setAudits([]);
      }
    } catch (err) {
      console.error('Error fetching audits:', err);
      setError('Failed to load audits. Please try again.');
      setAudits([]);
    } finally {
      setLoading(false);
    }
  };

  const handleSetInProgress = async (auditId) => {
    try {
      setSettingInProgressId(auditId);
      setError(null);
      const response = await axiosInstance.patch(`${AUDITS_URL}/${auditId}/status`, {
        audit_status_id: AUDIT_STATUS_IN_PROGRESS_ID
      });
      if (response.data.success) {
        await fetchAudits();
      } else {
        setError(response.data.message || 'Failed to update status.');
      }
    } catch (err) {
      console.error('Error setting audit in progress:', err);
      setError(err.response?.data?.message || 'Failed to set audit to In Progress. Please try again.');
    } finally {
      setSettingInProgressId(null);
    }
  };

  useEffect(() => {
    fetchAudits();
  }, []);

  const formatDate = (dateStr) => {
    if (!dateStr) return '—';
    const d = new Date(dateStr);
    return d.toLocaleDateString(undefined, {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  const filteredAudits = audits.filter((audit) => {
    const matchesStatus =
      statusFilter === STATUS_FILTER_ALL ||
      (audit.audit_status_name && String(audit.audit_status_name).trim() === statusFilter);
    const query = searchQuery.trim().toLowerCase();
    const matchesSearch =
      !query ||
      (audit.audit_name && String(audit.audit_name).toLowerCase().includes(query)) ||
      (audit.auditor_name && String(audit.auditor_name).toLowerCase().includes(query)) ||
      (audit.location_name && String(audit.location_name).toLowerCase().includes(query)) ||
      (audit.audit_id && String(audit.audit_id).includes(query));
    return matchesStatus && matchesSearch;
  });

  /* Latest first: sort by created_at descending */
  const sortedAudits = useMemo(() => {
    return [...filteredAudits].sort((a, b) => {
      const dateA = a.created_at ? new Date(a.created_at).getTime() : 0;
      const dateB = b.created_at ? new Date(b.created_at).getTime() : 0;
      return dateB - dateA;
    });
  }, [filteredAudits]);

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

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

  const counts = {
    all: audits.length,
    [STATUS_OPEN]: audits.filter((a) => a.audit_status_name && String(a.audit_status_name).trim() === STATUS_OPEN).length,
    [STATUS_IN_PROGRESS]: audits.filter((a) => a.audit_status_name && String(a.audit_status_name).trim() === STATUS_IN_PROGRESS).length,
    [STATUS_CLOSED]: audits.filter((a) => a.audit_status_name && String(a.audit_status_name).trim() === STATUS_CLOSED).length
  };

  return (
    <div className="audit-status-container">
      <div className="audit-status-header">
        <h1 className="audit-status-title">Audit Status</h1>
        <div className="audit-status-actions">
          <button
            type="button"
            className="btn btn-secondary"
            onClick={() => navigate('/dashboard')}
          >
            Dashboard
          </button>
          <button
            type="button"
            className="btn btn-primary"
            onClick={fetchAudits}
            disabled={loading}
          >
            {loading ? 'Loading…' : 'Refresh'}
          </button>
        </div>
      </div>

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

      <div className="audit-status-filters">
        <div className="audit-status-filter-tabs">
          <button
            type="button"
            className={`filter-tab ${statusFilter === STATUS_FILTER_ALL ? 'active' : ''}`}
            onClick={() => setStatusFilter(STATUS_FILTER_ALL)}
          >
            All <span className="filter-count">{counts.all}</span>
          </button>
          <button
            type="button"
            className={`filter-tab ${statusFilter === STATUS_OPEN ? 'active' : ''}`}
            onClick={() => setStatusFilter(STATUS_OPEN)}
          >
            Open <span className="filter-count">{counts[STATUS_OPEN]}</span>
          </button>
          <button
            type="button"
            className={`filter-tab ${statusFilter === STATUS_IN_PROGRESS ? 'active' : ''}`}
            onClick={() => setStatusFilter(STATUS_IN_PROGRESS)}
          >
            In Progress <span className="filter-count">{counts[STATUS_IN_PROGRESS]}</span>
          </button>
          <button
            type="button"
            className={`filter-tab ${statusFilter === STATUS_CLOSED ? 'active' : ''}`}
            onClick={() => setStatusFilter(STATUS_CLOSED)}
          >
            Closed <span className="filter-count">{counts[STATUS_CLOSED]}</span>
          </button>
        </div>
        <div className="audit-status-search">
          <input
            type="text"
            className="audit-status-search-input"
            placeholder="Search by audit name, auditor, location or ID…"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
          />
        </div>
        <div className="audit-status-view-toggle" title="Switch view">
          <button
            type="button"
            className={`audit-status-view-btn ${viewMode === VIEW_LIST ? 'active' : ''}`}
            onClick={() => setViewMode(VIEW_LIST)}
            title="List view"
            aria-label="List view"
          >
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <line x1="8" y1="6" x2="21" y2="6" />
              <line x1="8" y1="12" x2="21" y2="12" />
              <line x1="8" y1="18" x2="21" y2="18" />
              <line x1="3" y1="6" x2="3.01" y2="6" />
              <line x1="3" y1="12" x2="3.01" y2="12" />
              <line x1="3" y1="18" x2="3.01" y2="18" />
            </svg>
            List
          </button>
          <button
            type="button"
            className={`audit-status-view-btn ${viewMode === VIEW_CARD ? 'active' : ''}`}
            onClick={() => setViewMode(VIEW_CARD)}
            title="Card view"
            aria-label="Card view"
          >
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <rect x="3" y="3" width="7" height="7" rx="1" />
              <rect x="14" y="3" width="7" height="7" rx="1" />
              <rect x="3" y="14" width="7" height="7" rx="1" />
              <rect x="14" y="14" width="7" height="7" rx="1" />
            </svg>
            Card
          </button>
        </div>
      </div>

      {!loading && filteredAudits.length > 0 && (
        <div className="activity-log-controls-bar audit-status-table-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>
      )}

      {loading ? (
        <div className="audit-status-loading">
          <p>Loading audits…</p>
        </div>
      ) : (
        <div className="audit-status-list-wrap">
          {filteredAudits.length === 0 ? (
            <div className="audit-status-empty">
              <p>No audits found.</p>
              {audits.length === 0 ? (
                <button
                  type="button"
                  className="btn btn-primary"
                  onClick={() => navigate('/create-audit')}
                >
                  Create Audit
                </button>
              ) : null}
            </div>
          ) : viewMode === VIEW_LIST ? (
            <div className="audit-status-table-wrap">
              <table className="audit-status-table">
                <thead>
                  <tr>
                    <th>Name</th>
                    <th>ID</th>
                    <th>Status</th>
                    <th>Auditor</th>
                    <th>Location</th>
                    <th>Created</th>
                    <th>Observed</th>
                    <th className="audit-status-table-actions">Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {paginatedAudits.map((audit) => (
                    <tr key={audit.audit_id}>
                      <td className="audit-status-table-name">{audit.audit_name || '—'}</td>
                      <td>#{audit.audit_id}</td>
                      <td>
                        <span className={getStatusBadgeClass(audit.audit_status_name)}>
                          {audit.audit_status_name || 'N/A'}
                        </span>
                      </td>
                      <td>{audit.auditor_name || '—'}</td>
                      <td>{audit.location_name || '—'}</td>
                      <td>{formatDate(audit.created_at)}</td>
                      <td>{formatDate(audit.observed_at)}</td>
                      <td className="audit-status-table-actions">
                        <div className="audit-status-row-actions">
                          <button
                            type="button"
                            className="btn btn-sm btn-forms"
                            onClick={() => navigate(`/audit/${audit.audit_id}/forms`)}
                            title="View Observations"
                          >
                            Observations
                          </button>
{audit.audit_status_name && String(audit.audit_status_name).trim() !== STATUS_IN_PROGRESS && String(audit.audit_status_name || '').trim().toLowerCase() !== 'closed' && (
                              <button
                              type="button"
                              className="btn btn-sm btn-in-progress"
                              onClick={() => handleSetInProgress(audit.audit_id)}
                              disabled={settingInProgressId === audit.audit_id}
                              title="Mark as In Progress"
                            >
                              {settingInProgressId === audit.audit_id ? 'Updating…' : 'In Progress'}
                            </button>
                          )}
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          ) : (
            <div className="audit-status-cards">
              {paginatedAudits.map((audit) => (
                <article key={audit.audit_id} className="audit-status-card">
                  <div className="audit-status-card-header">
                    <h3 className="audit-status-card-title">{audit.audit_name || '—'}</h3>
                    <span className="audit-status-card-id">#{audit.audit_id}</span>
                    <span className={getStatusBadgeClass(audit.audit_status_name)}>
                      {audit.audit_status_name || 'N/A'}
                    </span>
                  </div>
                  <div className="audit-status-card-meta">
                    <div className="audit-status-card-row">
                      <span className="audit-status-card-label">Auditor</span>
                      <span className="audit-status-card-value">{audit.auditor_name || '—'}</span>
                    </div>
                    <div className="audit-status-card-row">
                      <span className="audit-status-card-label">Location</span>
                      <span className="audit-status-card-value">{audit.location_name || '—'}</span>
                    </div>
                    <div className="audit-status-card-row">
                      <span className="audit-status-card-label">Created</span>
                      <span className="audit-status-card-value">{formatDate(audit.created_at)}</span>
                    </div>
                    <div className="audit-status-card-row">
                      <span className="audit-status-card-label">Observed</span>
                      <span className="audit-status-card-value">{formatDate(audit.observed_at)}</span>
                    </div>
                  </div>
                  <div className="audit-status-card-actions">
                    <button
                      type="button"
                      className="btn btn-sm btn-forms"
                      onClick={() => navigate(`/audit/${audit.audit_id}/forms`)}
                      title="View Observations"
                    >
                      Observations
                    </button>
                    {audit.audit_status_name && String(audit.audit_status_name).trim() !== STATUS_IN_PROGRESS && String(audit.audit_status_name || '').trim().toLowerCase() !== 'closed' && (
                      <button
                        type="button"
                        className="btn btn-sm btn-in-progress"
                        onClick={() => handleSetInProgress(audit.audit_id)}
                        disabled={settingInProgressId === audit.audit_id}
                        title="Mark this audit as In Progress manually"
                      >
                        {settingInProgressId === audit.audit_id ? 'Updating…' : 'Set to In Progress'}
                      </button>
                    )}
                  </div>
                </article>
              ))}
            </div>
          )}

          {filteredAudits.length > 0 && (
            <Pagination
              currentPage={currentPage}
              totalPages={totalPages}
              totalEntries={totalEntries}
              entriesPerPage={entriesPerPage}
              onPageChange={setCurrentPage}
            />
          )}
        </div>
      )}
    </div>
  );
};

export default AuditStatus;
