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

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

const DATE_TYPE_CREATED = 'created_at';
const DATE_TYPE_OBSERVED = 'observed_at';

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';
};

/**
 * Groups audits by auditor (user). Each user gets: total, open, in progress, closed counts and list of audits.
 */
const groupAuditsByUser = (audits) => {
  const map = new Map();
  for (const audit of audits) {
    const uid = audit.auditor_id != null ? audit.auditor_id : 'unknown';
    const name = audit.auditor_name || 'Unknown';
    const employeeId = audit.auditor_employee_id != null ? audit.auditor_employee_id : '';
    if (!map.has(uid)) {
      map.set(uid, {
        userId: uid,
        employeeId,
        userName: name,
        audits: [],
        total: 0,
        open: 0,
        inProgress: 0,
        closed: 0
      });
    }
    const row = map.get(uid);
    row.audits.push(audit);
    row.total += 1;
    const status = (audit.audit_status_name || '').trim();
    if (status === STATUS_OPEN) row.open += 1;
    else if (status === STATUS_IN_PROGRESS) row.inProgress += 1;
    else if (status === STATUS_CLOSED) row.closed += 1;
  }
  return Array.from(map.values());
};

const UserWiseAuditDetails = () => {
  const navigate = useNavigate();
  const [audits, setAudits] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [expandedUserId, setExpandedUserId] = useState(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [entriesPerPage, setEntriesPerPage] = useState(DEFAULT_ENTRIES_PER_PAGE);
  /* Filters: date-wise, timestamp-wise (range), location, country */
  const [dateFrom, setDateFrom] = useState('');
  const [dateTo, setDateTo] = useState('');
  const [dateType, setDateType] = useState(DATE_TYPE_CREATED); // created_at | observed_at
  const [locationId, setLocationId] = useState('');
  const [countryId, setCountryId] = useState('');
  const [locations, setLocations] = useState([]);
  const [countries, setCountries] = useState([]);

  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 fetchCountries = async () => {
    try {
      const countryRes = await axiosInstance.get(COUNTRY_URL).catch(() => ({ data: { data: [] } }));
      setCountries(countryRes.data?.data || []);
    } catch (e) {
      console.error('Error fetching countries:', e);
    }
  };

  // When country is selected, fetch only that country's locations (sites). When no country, fetch all.
  useEffect(() => {
    let cancelled = false;
    const fetchLocations = async () => {
      try {
        const url = countryId
          ? `${LOCATIONS_URL}/country/${countryId}`
          : LOCATIONS_URL;
        const res = await axiosInstance.get(url);
        const list = res.data?.data || [];
        if (!cancelled) {
          setLocations(list);
          if (countryId) setLocationId(''); // clear location when country changes
        }
      } catch (e) {
        console.error('Error fetching locations:', e);
        if (!cancelled) setLocations([]);
      }
    };
    fetchLocations();
    return () => { cancelled = true; };
  }, [countryId]);

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

  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'
    });
  };

  /** Filter audits by date range (timestamp), location, country */
  const filteredAudits = useMemo(() => {
    return audits.filter((audit) => {
      const dateField = dateType === DATE_TYPE_OBSERVED ? audit.observed_at : audit.created_at;
      const dateVal = dateField ? new Date(dateField) : null;
      if (dateFrom && dateVal) {
        const from = new Date(dateFrom);
        from.setHours(0, 0, 0, 0);
        if (dateVal < from) return false;
      }
      if (dateTo && dateVal) {
        const to = new Date(dateTo);
        to.setHours(23, 59, 59, 999);
        if (dateVal > to) return false;
      }
      if (locationId) {
        const audLoc = audit.location != null ? Number(audit.location) : null;
        const selLoc = parseInt(locationId, 10);
        if (audLoc !== selLoc) return false;
      }
      if (countryId) {
        const audCountry = audit.country_id != null ? Number(audit.country_id) : null;
        const selCountry = parseInt(countryId, 10);
        if (audCountry !== selCountry) return false;
      }
      return true;
    });
  }, [audits, dateFrom, dateTo, dateType, locationId, countryId]);

  const userGroups = useMemo(() => groupAuditsByUser(filteredAudits), [filteredAudits]);

  const filteredGroups = useMemo(() => {
    const query = searchQuery.trim().toLowerCase();
    if (!query) return userGroups;
    return userGroups.filter(
      (g) =>
        (g.userName && String(g.userName).toLowerCase().includes(query)) ||
        (g.employeeId != null && String(g.employeeId).toLowerCase().includes(query)) ||
        (g.userId != null && String(g.userId).toString().includes(query))
    );
  }, [userGroups, searchQuery]);

  const sortedGroups = useMemo(() => {
    return [...filteredGroups].sort((a, b) => {
      const nameA = (a.userName || '').toLowerCase();
      const nameB = (b.userName || '').toLowerCase();
      return nameA.localeCompare(nameB);
    });
  }, [filteredGroups]);

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

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

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

  const toggleExpand = (userId) => {
    setExpandedUserId((prev) => (prev === userId ? null : userId));
  };

  const hasActiveFilters = dateFrom || dateTo || locationId || countryId;
  const clearFilters = () => {
    setDateFrom('');
    setDateTo('');
    setLocationId('');
    setCountryId('');
    setCurrentPage(1);
  };

  return (
    <div className="audit-status-container user-wise-audit-details-page">
      <div className="audit-status-header">
        <h1 className="audit-status-title">User-wise Audit Details</h1>
        <div className="audit-status-actions">
          <button
            type="button"
            className="btn btn-secondary"
            onClick={() => navigate('/dashboard')}
          >
            Dashboard
          </button>
          <button
            type="button"
            className="btn btn-secondary"
            onClick={() => navigate('/audit-status')}
          >
            Audit Status
          </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>
      )}

      <p className="user-wise-audit-intro">
        View audit summary per user (auditor). Expand a row to see that user&apos;s audits. Use filters for date range, location, and country.
      </p>

      <div className="user-wise-filters-bar">
        <div className="user-wise-filters-row">
          <div className="user-wise-filter-group">
            <label htmlFor="uw-country" className="user-wise-filter-label">Country</label>
            <select
              id="uw-country"
              className="user-wise-filter-select"
              value={countryId}
              onChange={(e) => { setCountryId(e.target.value); setCurrentPage(1); }}
            >
              <option value="">All countries</option>
              {countries.map((c) => (
                <option key={c.country_id} value={c.country_id}>
                  {c.country_name || `Country ${c.country_id}`}
                </option>
              ))}
            </select>
          </div>
          <div className="user-wise-filter-group">
            <label htmlFor="uw-location" className="user-wise-filter-label">Location</label>
            <select
              id="uw-location"
              className="user-wise-filter-select"
              value={locationId}
              onChange={(e) => { setLocationId(e.target.value); setCurrentPage(1); }}
            >
              <option value="">{countryId ? 'All locations in this country' : 'All locations'}</option>
              {locations.map((loc) => (
                <option key={loc.location_id} value={loc.location_id}>
                  {loc.location_name || `Location ${loc.location_id}`}
                </option>
              ))}
            </select>
          </div>
          <div className="user-wise-filter-group">
            <label htmlFor="uw-date-type" className="user-wise-filter-label">Date type</label>
            <select
              id="uw-date-type"
              className="user-wise-filter-select"
              value={dateType}
              onChange={(e) => setDateType(e.target.value)}
            >
              <option value={DATE_TYPE_CREATED}>Created date</option>
              <option value={DATE_TYPE_OBSERVED}>Observed date</option>
            </select>
          </div>
          <div className="user-wise-filter-group">
            <label htmlFor="uw-date-from" className="user-wise-filter-label">From date</label>
            <input
              id="uw-date-from"
              type="date"
              className="user-wise-filter-input"
              value={dateFrom}
              onChange={(e) => { setDateFrom(e.target.value); setCurrentPage(1); }}
            />
          </div>
          <div className="user-wise-filter-group">
            <label htmlFor="uw-date-to" className="user-wise-filter-label">To date</label>
            <input
              id="uw-date-to"
              type="date"
              className="user-wise-filter-input"
              value={dateTo}
              onChange={(e) => { setDateTo(e.target.value); setCurrentPage(1); }}
            />
          </div>
          {hasActiveFilters && (
            <div className="user-wise-filter-group user-wise-filter-actions">
              <button
                type="button"
                className="btn btn-secondary btn-small"
                onClick={clearFilters}
              >
                Clear filters
              </button>
            </div>
          )}
        </div>
      </div>

      <div className="audit-status-filters">
        <div className="audit-status-search">
          <input
            type="text"
            className="audit-status-search-input"
            placeholder="Search by employee ID or user name…"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
          />
        </div>
        {!loading && sortedGroups.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>
        )}
      </div>

      {loading ? (
        <div className="audit-status-loading">
          <p>Loading audit data…</p>
        </div>
      ) : (
        <div className="audit-status-list-wrap">
          {sortedGroups.length === 0 ? (
            <div className="audit-status-empty">
              <p>No users with audits found.</p>
            </div>
          ) : (
            <>
              <div className="user-wise-audit-table-wrap">
                <table className="audit-status-table user-wise-audit-table">
                  <thead>
                    <tr>
                      <th className="user-wise-col-expand" aria-label="Expand" />
                      <th>Employee ID</th>
                      <th>User (Auditor)</th>
                      <th>Total Audits</th>
                      <th>Open</th>
                      <th>In Progress</th>
                      <th>Closed</th>
                    </tr>
                  </thead>
                  <tbody>
                    {paginatedGroups.map((group) => (
                      <React.Fragment key={group.userId}>
                        <tr
                          className="user-wise-audit-row-main"
                          onClick={() => toggleExpand(group.userId)}
                        >
                          <td className="user-wise-col-expand">
                            <button
                              type="button"
                              className="user-wise-expand-btn"
                              onClick={(e) => {
                                e.stopPropagation();
                                toggleExpand(group.userId);
                              }}
                              aria-expanded={expandedUserId === group.userId}
                              title={expandedUserId === group.userId ? 'Collapse' : 'Expand'}
                            >
                              {expandedUserId === group.userId ? '−' : '+'}
                            </button>
                          </td>
                          <td>{group.employeeId || '—'}</td>
                          <td className="audit-status-table-name">{group.userName}</td>
                          <td>{group.total}</td>
                          <td>{group.open}</td>
                          <td>{group.inProgress}</td>
                          <td>{group.closed}</td>
                        </tr>
                        {expandedUserId === group.userId && (
                          <tr className="user-wise-audit-detail-row">
                            <td colSpan={7} className="user-wise-audit-detail-cell">
                              <div className="user-wise-audit-detail-inner">
                                <table className="audit-status-table user-wise-audit-subtable">
                                  <thead>
                                    <tr>
                                      <th>Audit Name</th>
                                      <th>ID</th>
                                      <th>Status</th>
                                      <th>Location</th>
                                      <th>Created</th>
                                      <th>Observed</th>
                                      <th className="audit-status-table-actions">Actions</th>
                                    </tr>
                                  </thead>
                                  <tbody>
                                    {group.audits.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.location_name || '—'}</td>
                                        <td>{formatDate(audit.created_at)}</td>
                                        <td>{formatDate(audit.observed_at)}</td>
                                        <td className="audit-status-table-actions">
                                          <button
                                            type="button"
                                            className="btn btn-sm btn-forms"
                                            onClick={(e) => {
                                              e.stopPropagation();
                                              navigate(`/audit/${audit.audit_id}/forms`);
                                            }}
                                            title="View Observations"
                                          >
                                            Observations
                                          </button>
                                        </td>
                                      </tr>
                                    ))}
                                  </tbody>
                                </table>
                              </div>
                            </td>
                          </tr>
                        )}
                      </React.Fragment>
                    ))}
                  </tbody>
                </table>
              </div>

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

export default UserWiseAuditDetails;
