import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { FaBoxes, FaPlus, FaSync, FaChevronDown, FaChevronUp, FaTimes, FaSearch, FaFileExport } from 'react-icons/fa';
import { toast, ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import materialRequestService, { MaterialRequest } from '../services/materialRequestService';
import DynamicExportModal from '../components/DynamicExportModal';
import { fetchAllRowsForExport } from '../utils/frappeListExport';
import { useListPageSelection } from '../hooks/useListPageSelection';

const PAGE_SIZE = 20;

function buildMaterialRequestExportFilters(f: { search: string; status: string; type: string }) {
  const filters: any[] = [];
  if (f.search) filters.push(['Material Request', 'name', 'like', `%${f.search}%`]);
  if (f.status === 'Draft') filters.push(['Material Request', 'docstatus', '=', 0]);
  if (f.status === 'Submitted') filters.push(['Material Request', 'docstatus', '=', 1]);
  if (f.status === 'Cancelled') filters.push(['Material Request', 'docstatus', '=', 2]);
  if (f.type) filters.push(['Material Request', 'material_request_type', '=', f.type]);
  return filters;
}

function getStatusStyle(mr: MaterialRequest) {
  if (mr.docstatus === 2) return 'bg-red-100 text-red-700';
  if (mr.docstatus === 1) return 'bg-green-100 text-green-700';
  return 'bg-yellow-100 text-yellow-800';
}
function getStatusLabel(mr: MaterialRequest) {
  if (mr.docstatus === 2) return 'Cancelled';
  if (mr.docstatus === 1) return mr.status || 'Submitted';
  return mr.status || 'Draft';
}

const MaterialRequestList: React.FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [reqs, setReqs] = useState<MaterialRequest[]>([]);
  const [loading, setLoading] = useState(true);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(0);
  const [filtersOpen, setFiltersOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const [typeFilter, setTypeFilter] = useState('');
  const [applied, setApplied] = useState({ search: '', status: '', type: '' });
  const [showExportModal, setShowExportModal] = useState(false);

  const load = useCallback(async (off: number, f: typeof applied) => {
    setLoading(true);
    try {
      const filters: any[] = [];
      if (f.search) filters.push(['Material Request', 'name', 'like', `%${f.search}%`]);
      if (f.status === 'Draft')     filters.push(['Material Request', 'docstatus', '=', 0]);
      if (f.status === 'Submitted') filters.push(['Material Request', 'docstatus', '=', 1]);
      if (f.status === 'Cancelled') filters.push(['Material Request', 'docstatus', '=', 2]);
      if (f.type) filters.push(['Material Request', 'material_request_type', '=', f.type]);
      const [rows, cnt] = await Promise.all([
        materialRequestService.getMaterialRequests({ filters, limit_start: off, limit_page_length: PAGE_SIZE }),
        materialRequestService.getMaterialRequestCount(filters),
      ]);
      setReqs(rows); setTotal(cnt);
    } catch (e: any) { toast.error(e.message || 'Failed to load'); }
    finally { setLoading(false); }
  }, []);

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

  const selectionResetKey = useMemo(
    () => `${page}|${applied.search}|${applied.status}|${applied.type}`,
    [page, applied.search, applied.status, applied.type],
  );
  const {
    selectedRows,
    toggleRow,
    toggleAllOnPage,
    allOnPageSelected,
    someOnPageSelected,
  } = useListPageSelection(reqs, selectionResetKey);

  const apply = () => { const f = { search: searchQuery, status: statusFilter, type: typeFilter }; setApplied(f); setPage(0); };
  const clear = () => { setSearchQuery(''); setStatusFilter(''); setTypeFilter(''); setApplied({ search: '', status: '', type: '' }); setPage(0); };
  const hasActive = !!(applied.search || applied.status || applied.type);
  const goPage = (p: number) => { setPage(p); load(p * PAGE_SIZE, applied); };

  const fetchAllForExport = useCallback(
    () =>
      fetchAllRowsForExport({
        doctype: 'Material Request',
        filters: buildMaterialRequestExportFilters(applied),
        orderBy: 'modified desc',
      }),
    [applied],
  );

  return (
    <div className="p-6">
      <ToastContainer position="top-right" autoClose={3000} />
      <div className="flex items-center justify-between mb-6 gap-4 flex-wrap">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-xl bg-orange-500 flex items-center justify-center"><FaBoxes className="text-white text-base" /></div>
          <div><h1 className="text-xl font-bold text-gray-900 dark:text-white">Material Requests</h1><p className="text-xs text-gray-500">{total} total</p></div>
        </div>
        <div className="flex items-center gap-2 flex-wrap">
          <button onClick={() => load(page * PAGE_SIZE, applied)} className="p-2 text-gray-500 hover:text-indigo-600 border border-gray-200 rounded-lg"><FaSync size={13} /></button>
          <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={total === 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 onClick={() => navigate('/material-requests/new')} className="flex items-center gap-2 px-4 py-2 bg-orange-500 text-white rounded-lg hover:bg-orange-600 text-sm font-medium"><FaPlus size={11} /> New Request</button>
        </div>
      </div>

      <DynamicExportModal
        isOpen={showExportModal}
        onClose={() => setShowExportModal(false)}
        doctype="Material Request"
        selectedCount={selectedRows.size}
        pageCount={reqs.length}
        totalCount={total}
        pageData={reqs}
        selectedRows={selectedRows}
        rowKey="name"
        onFetchAll={fetchAllForExport}
        fileNamePrefix="material_requests"
      />

      <div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-xl mb-5 overflow-hidden">
        <button onClick={() => setFiltersOpen(o => !o)} className="w-full flex items-center justify-between px-4 py-3 bg-gradient-to-r from-indigo-600 to-indigo-700 text-white">
          <div className="flex items-center gap-2 text-sm font-semibold"><FaSearch size={12} /> Filters {hasActive && <span className="bg-white/30 text-white text-xs px-2 py-0.5 rounded-full">Active</span>}</div>
          {filtersOpen ? <FaChevronUp size={11} /> : <FaChevronDown size={11} />}
        </button>
        {hasActive && (
          <div className="px-4 py-2 bg-indigo-50 dark:bg-indigo-900/20 flex flex-wrap gap-2 items-center border-b border-indigo-100">
            {applied.search && <span className="flex items-center gap-1 text-xs bg-indigo-100 text-indigo-700 px-2 py-1 rounded-full">ID: {applied.search}<button onClick={() => { setSearchQuery(''); setApplied(a => ({ ...a, search: '' })); }}><FaTimes size={9} /></button></span>}
            {applied.status && <span className="flex items-center gap-1 text-xs bg-indigo-100 text-indigo-700 px-2 py-1 rounded-full">Status: {applied.status}<button onClick={() => { setStatusFilter(''); setApplied(a => ({ ...a, status: '' })); }}><FaTimes size={9} /></button></span>}
            {applied.type && <span className="flex items-center gap-1 text-xs bg-indigo-100 text-indigo-700 px-2 py-1 rounded-full">Type: {applied.type}<button onClick={() => { setTypeFilter(''); setApplied(a => ({ ...a, type: '' })); }}><FaTimes size={9} /></button></span>}
            <button onClick={clear} className="text-xs text-indigo-600 hover:underline ml-auto">Clear All</button>
          </div>
        )}
        {filtersOpen && (
          <div className="px-4 py-3 grid grid-cols-1 sm:grid-cols-4 gap-3">
            <div><label className="block text-[11px] font-semibold text-gray-500 uppercase tracking-wide mb-1">Request ID</label>
              <input value={searchQuery} onChange={e => setSearchQuery(e.target.value)} onKeyDown={e => e.key === 'Enter' && apply()} placeholder="Search…" className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 focus:outline-none focus:ring-1 focus:ring-indigo-400" /></div>
            <div><label className="block text-[11px] font-semibold text-gray-500 uppercase tracking-wide mb-1">Type</label>
              <select value={typeFilter} onChange={e => setTypeFilter(e.target.value)} className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 focus:outline-none focus:ring-1 focus:ring-indigo-400">
                <option value="">All</option><option value="Purchase">Purchase</option><option value="Material Transfer">Material Transfer</option><option value="Manufacture">Manufacture</option>
              </select></div>
            <div><label className="block text-[11px] font-semibold text-gray-500 uppercase tracking-wide mb-1">Status</label>
              <select value={statusFilter} onChange={e => setStatusFilter(e.target.value)} className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 focus:outline-none focus:ring-1 focus:ring-indigo-400">
                <option value="">All</option><option value="Draft">Draft</option><option value="Submitted">Submitted</option><option value="Cancelled">Cancelled</option>
              </select></div>
            <div className="flex items-end gap-2">
              <button onClick={apply} className="px-4 py-2 bg-indigo-600 text-white text-sm rounded hover:bg-indigo-700">Apply</button>
              <button onClick={clear} className="px-4 py-2 border border-gray-300 text-gray-600 text-sm rounded hover:bg-gray-50">Clear</button>
            </div>
          </div>
        )}
      </div>

      <div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-xl 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-orange-600 focus:ring-orange-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">Request ID</th>
                <th className="text-left text-[10px] font-semibold text-gray-500 uppercase py-3 px-4">Type</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">Company</th>
                <th className="text-left text-[10px] font-semibold text-gray-500 uppercase py-3 px-4">Status</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100 dark:divide-gray-700">
              {loading ? <tr><td colSpan={6} className="text-center py-10 text-gray-400">Loading…</td></tr>
                : reqs.length === 0 ? <tr><td colSpan={6} className="text-center py-10 text-gray-400">No material requests found</td></tr>
                : reqs.map(mr => (
                  <tr key={mr.name} onClick={() => navigate(`/material-requests/${mr.name}`)} className={`cursor-pointer hover:bg-orange-50 dark:hover:bg-orange-900/10 transition-colors ${selectedRows.has(mr.name) ? 'bg-orange-50/90 dark:bg-orange-900/20' : ''}`}>
                    <td className="w-10 px-2 py-3" onClick={e => e.stopPropagation()}>
                      <input
                        type="checkbox"
                        className="rounded border-gray-300 dark:border-gray-600 text-orange-600 focus:ring-orange-500"
                        checked={selectedRows.has(mr.name)}
                        onChange={() => toggleRow(mr.name)}
                        aria-label={`Select ${mr.name}`}
                      />
                    </td>
                    <td className="py-3 px-4 font-medium text-orange-600">{mr.name}</td>
                    <td className="py-3 px-4 text-gray-700 dark:text-gray-300">{mr.material_request_type || '-'}</td>
                    <td className="py-3 px-4 text-gray-500">{mr.transaction_date || '-'}</td>
                    <td className="py-3 px-4 text-gray-500">{mr.company || '-'}</td>
                    <td className="py-3 px-4"><span className={`px-2 py-0.5 rounded text-xs font-semibold ${getStatusStyle(mr)}`}>{getStatusLabel(mr)}</span></td>
                  </tr>
                ))}
            </tbody>
          </table>
        </div>
        {total > PAGE_SIZE && (
          <div className="flex items-center justify-between px-4 py-3 border-t border-gray-100 dark:border-gray-700">
            <span className="text-xs text-gray-500">{page * PAGE_SIZE + 1}–{Math.min((page + 1) * PAGE_SIZE, total)} of {total}</span>
            <div className="flex gap-2">
              <button disabled={page === 0} onClick={() => goPage(page - 1)} className="px-3 py-1 text-xs border border-gray-300 rounded disabled:opacity-40">Prev</button>
              <button disabled={(page + 1) * PAGE_SIZE >= total} onClick={() => goPage(page + 1)} className="px-3 py-1 text-xs border border-gray-300 rounded disabled:opacity-40">Next</button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default MaterialRequestList;
