import React, { useMemo, useState, useCallback, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { FaPlus, FaSearch, FaSync, FaBullhorn, FaEye, FaFileExport } from 'react-icons/fa';
import projectUpdateService, { type ProjectUpdate } from '../services/projectUpdateService';
import { toast, ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import DynamicExportModal from '../components/DynamicExportModal';
import { fetchAllRowsForExport } from '../utils/frappeListExport';
import { useListPageSelection } from '../hooks/useListPageSelection';

const PAGE_SIZE = 20;

const ProjectUpdateList: React.FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [rows, setRows] = useState<ProjectUpdate[]>([]);
  const [loading, setLoading] = useState(true);
  const [totalCount, setTotalCount] = useState(0);
  const [search, setSearch] = useState('');
  const [page, setPage] = useState(0);
  const [showExportModal, setShowExportModal] = useState(false);

  const apiFilters = useMemo(() => {
    const f: Record<string, unknown> = {};
    if (search.trim()) {
      const q = search.trim();
      f.name = ['like', `%${q}%`];
    }
    return f;
  }, [search]);

  const load = useCallback(async (p = 0) => {
    setLoading(true);
    try {
      const [data, cnt] = await Promise.all([
        projectUpdateService.getProjectUpdates({
          filters: apiFilters,
          limit_start: p * PAGE_SIZE,
          limit_page_length: PAGE_SIZE,
          order_by: 'creation desc',
        }),
        projectUpdateService.getProjectUpdateCount(apiFilters as Record<string, any>),
      ]);
      setRows(data);
      setTotalCount(cnt);
      setPage(p);
    } catch (e) {
      toast.error(e instanceof Error ? e.message : 'Failed to load project updates');
    } finally {
      setLoading(false);
    }
  }, [apiFilters]);

  useEffect(() => { load(0); }, [load]);

  const selectionResetKey = useMemo(() => `${page}|${JSON.stringify(apiFilters)}`, [page, apiFilters]);
  const {
    selectedRows,
    toggleRow,
    toggleAllOnPage,
    allOnPageSelected,
    someOnPageSelected,
  } = useListPageSelection(rows, selectionResetKey);

  const fetchAllForExport = useCallback(
    () => fetchAllRowsForExport({ doctype: 'Project Update', filters: apiFilters as Record<string, any>, orderBy: 'creation desc' }),
    [apiFilters],
  );

  const docStatusLabel = (d?: number) => {
    if (d === 1) return 'Submitted';
    if (d === 2) return 'Cancelled';
    return 'Draft';
  };

  return (
    <div className="p-6">
      <ToastContainer position="top-right" autoClose={3000} />
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
        <div className="flex items-center gap-3">
          <button
            type="button"
            onClick={() => navigate('/projects')}
            className="text-sm text-gray-500 hover:text-violet-600 dark:text-gray-400 dark:hover:text-violet-400"
          >
            {t('projects.moduleTitle', 'Project Management')}
          </button>
          <span className="text-gray-400">/</span>
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white flex items-center gap-2">
            <FaBullhorn className="text-violet-500" /> Project updates
          </h1>
        </div>
        <div className="flex flex-wrap items-center gap-2">
          <button
            type="button"
            onClick={() => setShowExportModal(true)}
            className="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-lg flex items-center gap-2 shadow transition-all text-sm font-medium disabled:opacity-50"
            disabled={totalCount === 0 && selectedRows.size === 0}
          >
            <FaFileExport /> {t('listPages.export')}
            {selectedRows.size > 0 && (
              <span className="bg-white/25 px-1.5 py-0.5 rounded text-xs font-bold">{selectedRows.size}</span>
            )}
          </button>
          <button
            type="button"
            onClick={() => load(page)}
            className="p-2 text-gray-500 border border-gray-200 dark:border-gray-600 rounded-lg hover:text-violet-600"
            aria-label="Refresh"
          >
            <FaSync size={14} className={loading ? 'animate-spin' : ''} />
          </button>
          <button
            type="button"
            onClick={() => navigate('/projects/project-updates/new')}
            className="flex items-center gap-2 px-4 py-2 bg-violet-600 text-white rounded-lg hover:bg-violet-700 text-sm font-medium"
          >
            <FaPlus size={12} /> New project update
          </button>
        </div>
      </div>

      <div className="mb-4 flex flex-wrap gap-3 items-center">
        <div className="relative flex-1 min-w-[200px] max-w-md">
          <FaSearch className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-xs" />
          <input
            value={search}
            onChange={(e) => { setSearch(e.target.value); setPage(0); }}
            placeholder="Search by name or project…"
            className="w-full pl-9 pr-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
          />
        </div>
        <span className="text-xs text-gray-500">{totalCount} total</span>
      </div>

      <DynamicExportModal
        isOpen={showExportModal}
        onClose={() => setShowExportModal(false)}
        doctype="Project Update"
        selectedCount={selectedRows.size}
        pageCount={rows.length}
        totalCount={totalCount}
        pageData={rows}
        selectedRows={selectedRows}
        rowKey="name"
        onFetchAll={fetchAllForExport}
        fileNamePrefix="project_updates"
      />

      <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden">
        <div className="overflow-x-auto">
          <table className="min-w-full text-sm">
            <thead>
              <tr className="border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900/40">
                <th className="w-10 px-2 py-3">
                  <input
                    type="checkbox"
                    className="rounded border-gray-300 dark:border-gray-600 text-violet-600 focus:ring-violet-500"
                    checked={allOnPageSelected}
                    ref={el => {
                      if (el) el.indeterminate = someOnPageSelected;
                    }}
                    onChange={toggleAllOnPage}
                    aria-label="Select all on page"
                  />
                </th>
                <th className="text-left text-[10px] font-semibold text-gray-500 uppercase py-3 px-4">Name</th>
                <th className="text-left text-[10px] font-semibold text-gray-500 uppercase py-3 px-4">Project</th>
                <th className="text-left text-[10px] font-semibold text-gray-500 uppercase py-3 px-4">Date</th>
                <th className="text-left text-[10px] font-semibold text-gray-500 uppercase py-3 px-4">Time</th>
                <th className="text-left text-[10px] font-semibold text-gray-500 uppercase py-3 px-4">Sent</th>
                <th className="text-left text-[10px] font-semibold text-gray-500 uppercase py-3 px-4">Status</th>
                <th className="text-right text-[10px] font-semibold text-gray-500 uppercase py-3 px-4 w-24"> </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100 dark:divide-gray-700">
              {loading ? (
                <tr>
                  <td colSpan={8} className="text-center py-10 text-gray-400">Loading…</td>
                </tr>
              ) : rows.length === 0 ? (
                <tr>
                  <td colSpan={8} className="text-center py-10 text-gray-400">No project updates</td>
                </tr>
              ) : (
                rows.map((r) => (
                  <tr
                    key={r.name}
                    className="hover:bg-gray-50 dark:hover:bg-gray-900/30 cursor-pointer"
                    onClick={() => navigate(`/projects/project-updates/${encodeURIComponent(r.name)}`)}
                    title="Open"
                  >
                    <td className="px-2 py-3">
                      <input
                        type="checkbox"
                        className="rounded border-gray-300 dark:border-gray-600 text-violet-600"
                        checked={selectedRows.has(r.name)}
                        onChange={() => toggleRow(r.name)}
                        onClick={(e) => e.stopPropagation()}
                        aria-label={`Select ${r.name}`}
                      />
                    </td>
                    <td className="px-4 py-3 font-mono text-xs text-gray-800 dark:text-gray-200">{r.name}</td>
                    <td className="px-4 py-3 text-gray-700 dark:text-gray-300">{r.project || '—'}</td>
                    <td className="px-4 py-3 text-gray-600 dark:text-gray-400 font-mono text-xs">{r.date || '—'}</td>
                    <td className="px-4 py-3 text-gray-600 dark:text-gray-400 font-mono text-xs">{r.time || '—'}</td>
                    <td className="px-4 py-3">{r.sent ? <span className="text-green-600 dark:text-green-400 font-medium">Yes</span> : <span className="text-gray-500">No</span>}</td>
                    <td className="px-4 py-3">
                      <span className={`text-xs font-medium px-2 py-0.5 rounded ${r.docstatus === 1 ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300' : 'bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-300'}`}>
                        {docStatusLabel(r.docstatus)}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-right">
                      <button
                        type="button"
                        onClick={(e) => { e.stopPropagation(); navigate(`/projects/project-updates/${encodeURIComponent(r.name)}`); }}
                        className="inline-flex items-center gap-1 text-violet-600 dark:text-violet-400 hover:underline text-xs font-semibold"
                      >
                        <FaEye size={11} /> View
                      </button>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
        {totalCount > PAGE_SIZE && (
          <div className="flex items-center justify-between px-4 py-3 border-t border-gray-200 dark:border-gray-700 text-xs text-gray-500">
            <span>Page {page + 1} of {Math.max(1, Math.ceil(totalCount / PAGE_SIZE))}</span>
            <div className="flex gap-2">
              <button
                type="button"
                disabled={page <= 0 || loading}
                onClick={() => load(page - 1)}
                className="px-3 py-1 rounded border border-gray-200 dark:border-gray-600 disabled:opacity-40"
              >
                Previous
              </button>
              <button
                type="button"
                disabled={(page + 1) * PAGE_SIZE >= totalCount || loading}
                onClick={() => load(page + 1)}
                className="px-3 py-1 rounded border border-gray-200 dark:border-gray-600 disabled:opacity-40"
              >
                Next
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default ProjectUpdateList;
