import React from 'react';
import { BarChart3 } from 'lucide-react';
import { SearchableSelect } from '@nexuscrm/salesforce-crm-standard-frontend/platform/components/ui';
import type { WidgetConfig } from './platform/types';
import { useReports, type ReportSummary } from './platform/features/analytics';
import {
  CRM_REPORT_COMPONENT_TYPE,
  getCrmDashboardWidgetApiMapping,
} from './dashboard-widget-types';

export interface CrmDashboardWidgetInspectorProps {
  selectedWidget: WidgetConfig;
  onUpdate: (updates: Partial<WidgetConfig>) => void;
}

export function isCrmReportBackedDashboardWidget(type: string): boolean {
  return getCrmDashboardWidgetApiMapping(type).componentType === CRM_REPORT_COMPONENT_TYPE;
}

export const CrmDashboardWidgetInspector: React.FC<CrmDashboardWidgetInspectorProps> = ({
  selectedWidget,
  onUpdate,
}) => {
  const { data: reports = [], isLoading: reportsLoading } = useReports();

  if (!isCrmReportBackedDashboardWidget(selectedWidget.type)) {
    return null;
  }

  return (
    <div className="space-y-4 pt-4 border-t border-slate-100">
      <h4 className="text-xs font-bold text-slate-400 uppercase tracking-wider flex items-center gap-2">
        <BarChart3 size={12} />
        Report
      </h4>

      <div>
        <label className="block text-sm font-medium text-slate-700 mb-1">Source Report</label>
        <SearchableSelect
          options={reports.map((r: ReportSummary) => ({ value: r.id, label: r.name, detail: r.folderName || '' }))}
          value={selectedWidget.reportId || ''}
          onChange={(v) => {
            const report = reports.find((r: ReportSummary) => r.id === v);
            const updates: Partial<WidgetConfig> = { reportId: v || undefined };
            if (selectedWidget.title === 'New Widget' && report) {
              updates.title = report.name;
            }
            onUpdate(updates);
          }}
          placeholder="-- Select Report --"
          disabled={reportsLoading}
        />
        <p className="text-xs text-slate-500 mt-1">
          Reports define data source, filters, and grouping.
        </p>
      </div>
    </div>
  );
};
