import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { FaExternalLinkAlt, FaFileExport, FaStar, FaTimes } from 'react-icons/fa';
import { useTranslation } from 'react-i18next';
import LinkField from './LinkField';
import QueryReportExportModal from './QueryReportExportModal';
import woFeedbackReportService, {
  type WoFeedbackReportFilters,
} from '../services/woFeedbackReportService';
import { WO_FEEDBACK_RATING_OPTIONS } from '../utils/woFeedbackChartUtils';
import { buildMobileTeamSiteFilters, isSiteEnabledHospital } from '../utils/hospitalUtils';

interface WoFeedbackReportModalProps {
  isOpen: boolean;
  onClose: () => void;
  defaultCompany?: string;
  defaultSiteName?: string;
  companyLocked?: boolean;
  siteLocked?: boolean;
  hospitalLinkFilters?: Record<string, unknown>;
}

type AppliedFilters = WoFeedbackReportFilters;

const EMPTY_FILTERS: AppliedFilters = {
  work_order: '',
  requester_name: '',
  rating: '',
  company: '',
  site_name: '',
};

const compactFilterLabelClass =
  'block font-medium text-gray-700 dark:text-gray-300 text-[10px] mb-0.5';
const compactFilterInputClass =
  'w-full px-2 py-1 text-xs border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-1 focus:ring-emerald-500 disabled:bg-gray-100 dark:disabled:bg-gray-700';

const WoFeedbackReportModal: React.FC<WoFeedbackReportModalProps> = ({
  isOpen,
  onClose,
  defaultCompany = '',
  defaultSiteName = '',
  companyLocked = false,
  siteLocked = false,
  hospitalLinkFilters,
}) => {
  const { t } = useTranslation();
  const [reportData, setReportData] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [refreshing, setRefreshing] = useState(false);

  const [workOrder, setWorkOrder] = useState('');
  const [requesterNameDraft, setRequesterNameDraft] = useState('');
  const [rating, setRating] = useState('');
  const [company, setCompany] = useState(defaultCompany);
  const [siteName, setSiteName] = useState(defaultSiteName);
  const [appliedFilters, setAppliedFilters] = useState<AppliedFilters>(EMPTY_FILTERS);
  const [showExportModal, setShowExportModal] = useState(false);

  const hasLoadedOnce = useRef(false);
  const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const showSiteFilter = isSiteEnabledHospital(company);
  const mobileTeamSiteFilters = useMemo(
    () => buildMobileTeamSiteFilters(company, siteLocked ? siteName : undefined),
    [company, siteName, siteLocked]
  );

  useEffect(() => {
    if (!isOpen) {
      setWorkOrder('');
      setRequesterNameDraft('');
      setRating('');
      setCompany(defaultCompany);
      setSiteName(defaultSiteName);
      setAppliedFilters(EMPTY_FILTERS);
      setReportData(null);
      setLoading(false);
      setRefreshing(false);
      hasLoadedOnce.current = false;
      setShowExportModal(false);
      if (debounceRef.current) clearTimeout(debounceRef.current);
    }
  }, [isOpen, defaultCompany, defaultSiteName]);

  useEffect(() => {
    if (!isOpen) return;
    setCompany(defaultCompany);
    setSiteName(defaultSiteName);
  }, [isOpen, defaultCompany, defaultSiteName]);

  useEffect(() => {
    if (!isOpen) return;
    if (debounceRef.current) clearTimeout(debounceRef.current);
    debounceRef.current = setTimeout(() => {
      setAppliedFilters({
        work_order: workOrder.trim(),
        requester_name: requesterNameDraft.trim(),
        rating,
        company: company.trim(),
        site_name: showSiteFilter ? siteName.trim() : '',
      });
    }, 450);
    return () => {
      if (debounceRef.current) clearTimeout(debounceRef.current);
    };
  }, [isOpen, workOrder, requesterNameDraft, rating, company, siteName, showSiteFilter]);

  const fetchReport = useCallback(async (filters: AppliedFilters) => {
    const isRefresh = hasLoadedOnce.current;
    if (isRefresh) setRefreshing(true);
    else setLoading(true);

    try {
      const data = await woFeedbackReportService.runWoFeedbackReport(filters);
      setReportData(data || null);
      hasLoadedOnce.current = true;
    } catch (e) {
      console.error('WO feedback report error:', e);
      if (!isRefresh) setReportData(null);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  }, []);

  useEffect(() => {
    if (!isOpen) return;
    fetchReport(appliedFilters);
  }, [isOpen, appliedFilters, fetchReport]);

  if (!isOpen) return null;

  const columns: any[] = reportData?.columns || [];
  const rows: any[] = (reportData?.result || []).filter(
    (r: any) => r && typeof r === 'object' && !r.is_total_row,
  );
  const hasActiveFilter = Boolean(
    workOrder.trim() ||
      requesterNameDraft.trim() ||
      rating ||
      company.trim() ||
      (showSiteFilter && siteName.trim())
  );
  const showInitialLoader = loading && !hasLoadedOnce.current;
  const showEmpty = !showInitialLoader && rows.length === 0;

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-[70] p-4">
      <div className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl max-w-5xl w-full max-h-[90vh] overflow-hidden flex flex-col">
        <div className="bg-gradient-to-r from-emerald-600 to-teal-600 px-6 py-4 flex items-center justify-between shrink-0">
          <div className="flex items-center gap-3">
            <FaStar className="text-white text-xl" />
            <h3 className="text-lg font-semibold text-white">
              {t('dashboard.woFeedbackReport', { defaultValue: 'WO Feedback Report' })}
            </h3>
          </div>
          <div className="flex items-center gap-2">
            <button
              type="button"
              onClick={() => setShowExportModal(true)}
              disabled={showInitialLoader || rows.length === 0}
              className="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-emerald-700 bg-white hover:bg-emerald-50 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <FaFileExport size={12} /> Export
            </button>
            <button
              type="button"
              onClick={onClose}
              className="text-white/80 hover:text-white p-1 rounded-lg hover:bg-white/20 transition-colors"
            >
              <FaTimes className="w-5 h-5" />
            </button>
          </div>
        </div>

        <div className="px-6 py-3 border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900/30 shrink-0">
          <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-5 gap-3">
            <LinkField
              label={t('commonFields.hospital', { defaultValue: 'Hospital' })}
              doctype="Company"
              value={company}
              onChange={value => {
                setCompany(value);
                if (!isSiteEnabledHospital(value)) setSiteName('');
              }}
              placeholder={t('dashboard.allHospitals', { defaultValue: 'All Hospitals' })}
              disabled={companyLocked}
              compact
              filters={hospitalLinkFilters}
            />
            {showSiteFilter && (
              <LinkField
                label={t('commonFields.siteName', { defaultValue: 'PHCC Site' })}
                doctype="Mobile Team Site"
                value={siteName}
                onChange={setSiteName}
                placeholder={t('dashboard.allSites', { defaultValue: 'All Sites' })}
                disabled={siteLocked}
                compact
                filters={mobileTeamSiteFilters}
              />
            )}
            <LinkField
              label={t('commonFields.workOrder', { defaultValue: 'Work Order' })}
              doctype="Work_Order"
              value={workOrder}
              onChange={setWorkOrder}
              placeholder="Filter by work order…"
              compact
            />
            <div className="relative w-full mb-2">
              <label className={compactFilterLabelClass}>Requester Name</label>
              <input
                type="text"
                value={requesterNameDraft}
                onChange={e => setRequesterNameDraft(e.target.value)}
                placeholder="Filter by requester…"
                className={compactFilterInputClass}
              />
            </div>
            <div className="relative w-full mb-2">
              <label className={compactFilterLabelClass}>Rating</label>
              <select
                value={rating}
                onChange={e => setRating(e.target.value)}
                className={compactFilterInputClass}
              >
                <option value="">All ratings</option>
                {WO_FEEDBACK_RATING_OPTIONS.map(opt => (
                  <option key={opt} value={opt}>{opt}</option>
                ))}
              </select>
            </div>
          </div>
          {hasActiveFilter && (
            <button
              type="button"
              onClick={() => {
                setWorkOrder('');
                setRequesterNameDraft('');
                setRating('');
                setCompany(defaultCompany);
                setSiteName(defaultSiteName);
              }}
              className="mt-3 text-xs text-red-500 hover:text-red-700 flex items-center gap-1 px-2 py-1 rounded-lg hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors"
            >
              <FaTimes size={10} /> {t('dashboard.clearFilters', { defaultValue: 'Clear filters' })}
            </button>
          )}
        </div>

        <div className="p-6 overflow-auto flex-1 relative min-h-[240px]">
          {showInitialLoader ? (
            <div className="flex items-center justify-center py-16">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-emerald-600" />
            </div>
          ) : showEmpty ? (
            <div className="text-center text-gray-400 py-16">No feedback records found</div>
          ) : (
            <div className={`overflow-x-auto transition-opacity duration-200 ${refreshing ? 'opacity-60' : 'opacity-100'}`}>
              {refreshing && (
                <div className="absolute top-6 right-6 z-10">
                  <div className="animate-spin rounded-full h-5 w-5 border-2 border-emerald-600 border-t-transparent" />
                </div>
              )}
              <table className="w-full text-sm border-collapse">
                <thead>
                  <tr className="border-b border-gray-200 dark:border-gray-700">
                    {columns.map((col: any, i: number) => (
                      <th
                        key={i}
                        className="py-3 px-4 font-semibold text-gray-700 dark:text-gray-300 bg-gray-50 dark:bg-gray-900/50 text-left"
                      >
                        {col.label || col.fieldname}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {rows.map((row: any, ri: number) => (
                    <tr
                      key={ri}
                      className="border-b border-gray-100 dark:border-gray-700/50 hover:bg-emerald-50/40 dark:hover:bg-emerald-900/10 transition-colors"
                    >
                      {columns.map((col: any, ci: number) => {
                        const fieldLower = (col.fieldname || '').toLowerCase();
                        const isWoCol = fieldLower === 'work_order';
                        const cellVal = row[col.fieldname] ?? '—';
                        const woId = isWoCol ? String(cellVal) : '';
                        const isClickable = isWoCol && woId && woId !== '—';

                        return (
                          <td
                            key={ci}
                            className={`py-2.5 px-4 align-top ${
                              isClickable
                                ? 'cursor-pointer text-emerald-600 dark:text-emerald-400 font-semibold hover:underline'
                                : 'text-gray-800 dark:text-gray-200'
                            }`}
                            onClick={isClickable
                              ? () => { window.location.href = `/asm_app/work-orders/${encodeURIComponent(woId)}`; }
                              : undefined}
                            title={isClickable ? `Open Work Order ${woId}` : undefined}
                          >
                            {isClickable ? (
                              <span className="inline-flex items-center gap-1.5">
                                {cellVal}
                                <FaExternalLinkAlt size={9} className="opacity-50 shrink-0" />
                              </span>
                            ) : (
                              cellVal
                            )}
                          </td>
                        );
                      })}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>

      <QueryReportExportModal
        isOpen={showExportModal}
        onClose={() => setShowExportModal(false)}
        title={t('dashboard.woFeedbackReport', { defaultValue: 'WO Feedback Report' })}
        columns={columns}
        rows={rows}
        fileNamePrefix="wo_feedback_report"
      />
    </div>
  );
};

export default WoFeedbackReportModal;
