import React from 'react';
import { ArrowLeft, Clock, Edit, Plus, RefreshCw } from 'lucide-react';
import { useParams } from 'react-router-dom';
import {
  ConfirmationModal,
  DashboardWidgetSkeleton,
  SearchableSelect,
} from '@nexuscrm/salesforce-crm-standard-frontend/platform/components/ui';
import { useApp } from '@nexuscrm/host-sdk';
import { tryBuildAppNavigationPath } from './platform/core/navigation/appNavigationCapabilities';
import { tryGetSetupCapabilityPagePath } from './platform/core/navigation/setupPagePaths';
import {
  ChartWidget,
  DashboardLibrary,
  DashboardViewer,
  DashboardWidgetRegistry,
  FunnelWidget,
  GaugeWidget,
  IcicleWidget,
  MetricWidget,
  useDashboard,
} from './platform/features/dashboard';
import {
  CRM_BAR_CHART_WIDGET_TYPE,
  CRM_DASHBOARD_WIDGET_POLICY_SCOPE,
  CRM_FUNNEL_CHART_WIDGET_TYPE,
  CRM_GAUGE_CHART_WIDGET_TYPE,
  CRM_ICICLE_CHART_WIDGET_TYPE,
  CRM_LINE_CHART_WIDGET_TYPE,
  CRM_METRIC_WIDGET_TYPE,
  CRM_PIE_CHART_WIDGET_TYPE,
  CRM_REPORT_WIDGET_TYPE,
} from './dashboard-widget-types';
import { registerCrmDashboardWidgetContribution } from './host-contributions';

export const crmDashboardWidgets = DashboardWidgetRegistry.forScope(CRM_DASHBOARD_WIDGET_POLICY_SCOPE);

let crmDashboardWidgetsRegistered = false;
const CRM_DASHBOARD_WIDGET_COMPONENT_TYPES = [
  CRM_METRIC_WIDGET_TYPE,
  CRM_BAR_CHART_WIDGET_TYPE,
  CRM_LINE_CHART_WIDGET_TYPE,
  CRM_PIE_CHART_WIDGET_TYPE,
  CRM_FUNNEL_CHART_WIDGET_TYPE,
  CRM_GAUGE_CHART_WIDGET_TYPE,
  CRM_ICICLE_CHART_WIDGET_TYPE,
  CRM_REPORT_WIDGET_TYPE,
] as const;

export function ensureCrmDashboardWidgetsRegistered(): void {
  if (crmDashboardWidgetsRegistered) return;
  if (CRM_DASHBOARD_WIDGET_COMPONENT_TYPES.every(type => crmDashboardWidgets.getWidget(type))) {
    crmDashboardWidgetsRegistered = true;
    return;
  }
  registerCrmDashboardWidgetContribution({
    registry: crmDashboardWidgets,
    widgets: {
      MetricWidget,
      ChartWidget,
      FunnelWidget,
      GaugeWidget,
      IcicleWidget,
    },
  });
  crmDashboardWidgetsRegistered = true;
}

export interface CrmDashboardPageProps {
  dashboardId?: string;
}

export const CrmDashboardPage: React.FC<CrmDashboardPageProps> = ({ dashboardId }) => {
  ensureCrmDashboardWidgetsRegistered();
  const { currentFrontendAppId } = useApp();
  const dashboardListPath = tryBuildAppNavigationPath(currentFrontendAppId, 'dashboardList') ?? '/';
  const {
    dashboards, currentDashboard, loading,
    dashboardToDelete, setDashboardToDelete,
    showAppContextModal, setShowAppContextModal,
    lastRefresh, refreshing,
    executionResults,
    isCreateModalOpen, setIsCreateModalOpen,
    newDashboardName, setNewDashboardName,
    newDashboardDesc, setNewDashboardDesc,
    creating, dashboardFolders, selectedFolderId, setSelectedFolderId,
    handleRefresh, handleCreateDashboard,
    handleDelete, executeDelete, handleEdit,
    navigate,
  } = useDashboard(dashboardId, crmDashboardWidgets);

  if (loading && !dashboards.length) return (
    <div className="p-8 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
      <DashboardWidgetSkeleton />
      <DashboardWidgetSkeleton />
      <DashboardWidgetSkeleton />
    </div>
  );

  return (
    <div className="flex-1 overflow-auto bg-slate-50/50 min-h-screen flex flex-col">
      <div className="sticky top-0 z-20 bg-white/80 backdrop-blur-md border-b border-slate-200 px-8 py-4 flex items-center justify-between shadow-sm">
        <div className="flex items-center gap-4">
          {currentDashboard ? (
            <>
              <button
                onClick={() => navigate(dashboardListPath)}
                className="p-2 hover:bg-slate-100 rounded-lg text-slate-500 hover:text-slate-700 transition-colors"
                title="Back to Dashboards"
              >
                <ArrowLeft size={20} />
              </button>
              <div>
                <h1 className="text-xl font-bold text-slate-800">{currentDashboard.label}</h1>
                <p className="text-sm text-slate-500 hidden sm:block">Viewing Dashboard</p>
              </div>
            </>
          ) : (
            <div>
              <h1 className="text-xl font-bold text-slate-800">My Dashboards</h1>
              <p className="text-sm text-slate-500 hidden sm:block">Manage and view your analytics</p>
            </div>
          )}
        </div>

        <div className="flex gap-3">
          {!currentDashboard && (
            <button
              onClick={() => setIsCreateModalOpen(true)}
              className="px-4 py-2 bg-blue-600 text-white rounded-lg shadow-sm hover:bg-blue-700 hover:shadow font-medium flex items-center gap-2 transition-all"
            >
              <Plus size={18} /> New Dashboard
            </button>
          )}
          {currentDashboard && (
            <>
              <div className="flex items-center gap-2 text-sm text-slate-500 mr-2">
                <Clock size={14} />
                <span>Updated {lastRefresh.toLocaleTimeString()}</span>
              </div>
              <button
                onClick={handleRefresh}
                disabled={refreshing}
                className="p-2 bg-white border border-slate-200 text-slate-700 rounded-lg shadow-sm hover:bg-slate-50 transition-all disabled:opacity-50"
                title="Refresh Dashboard"
              >
                <RefreshCw size={16} className={refreshing ? 'animate-spin' : ''} />
              </button>
              <button
                onClick={(e) => handleEdit(e, currentDashboard.id)}
                className="px-4 py-2 bg-white border border-slate-200 text-slate-700 rounded-lg shadow-sm hover:bg-slate-50 font-medium flex items-center gap-2 transition-all"
              >
                <Edit size={16} /> Edit
              </button>
            </>
          )}
        </div>
      </div>

      <div className="p-8">
        {!currentDashboard ? (
          <DashboardLibrary
            dashboards={dashboards}
            onCreateClick={() => setIsCreateModalOpen(true)}
            onEditClick={handleEdit}
            onDeleteClick={handleDelete}
            dashboardDetailPath={(id) => tryBuildAppNavigationPath(currentFrontendAppId, 'dashboardDetail', { dashboardId: id }) ?? dashboardListPath}
          />
        ) : (
          <DashboardViewer
            dashboard={currentDashboard}
            executionResults={executionResults}
            refreshing={refreshing}
            dashboardWidgets={crmDashboardWidgets}
          />
        )}
      </div>

      <ConfirmationModal
        isOpen={!!dashboardToDelete}
        onClose={() => setDashboardToDelete(null)}
        onConfirm={executeDelete}
        title="Delete Dashboard"
        message="Are you sure you want to delete this dashboard? This action cannot be undone."
        confirmLabel="Delete"
        variant="danger"
      />
      <ConfirmationModal
        isOpen={showAppContextModal}
        onClose={() => setShowAppContextModal(false)}
        onConfirm={() => {
          setShowAppContextModal(false);
          navigate(tryGetSetupCapabilityPagePath(currentFrontendAppId, 'appManager') ?? '/');
        }}
        title="App Context Required"
        message="You need to be in an App context to create a dashboard. Would you like to go to App Manager?"
        confirmLabel="Go to App Manager"
        variant="info"
      />

      {isCreateModalOpen && (
        <div className="fixed inset-0 z-[100] flex items-center justify-center bg-slate-900/50 backdrop-blur-sm p-4">
          <div className="bg-white rounded-xl shadow-2xl w-full max-w-md overflow-hidden animate-in fade-in zoom-in duration-200">
            <div className="px-6 py-4 border-b border-slate-100 flex justify-between items-center bg-slate-50/50">
              <h3 className="font-semibold text-slate-800">Create New Dashboard</h3>
              <button onClick={() => setIsCreateModalOpen(false)} className="text-slate-400 hover:text-slate-600">
                <Plus size={20} className="rotate-45" />
              </button>
            </div>

            <div className="p-6 space-y-4">
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">Dashboard Name</label>
                <input
                  type="text"
                  value={newDashboardName}
                  onChange={(e) => setNewDashboardName(e.target.value)}
                  className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition-all"
                  placeholder="e.g., Q1 Sales Overview"
                  autoFocus
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">Folder</label>
                <SearchableSelect
                  options={dashboardFolders.map(f => ({ value: f.id, label: f.label, detail: f.id }))}
                  value={selectedFolderId}
                  onChange={(v) => setSelectedFolderId(v)}
                  placeholder="Select a folder..."
                />
                {dashboardFolders.length === 0 && (
                  <div className="text-xs text-amber-600 mt-1">No folders found. Using default/user folder.</div>
                )}
              </div>
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">Description</label>
                <textarea
                  value={newDashboardDesc}
                  onChange={(e) => setNewDashboardDesc(e.target.value)}
                  className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition-all resize-none h-24"
                  placeholder="Optional description..."
                />
              </div>
            </div>

            <div className="px-6 py-4 bg-slate-50/50 flex justify-end gap-3 border-t border-slate-100">
              <button
                onClick={() => setIsCreateModalOpen(false)}
                className="px-4 py-2 text-slate-600 font-medium hover:bg-slate-100 rounded-lg transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={handleCreateDashboard}
                disabled={!newDashboardName.trim() || creating}
                className="px-4 py-2 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 shadow-sm shadow-blue-500/20 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
              >
                {creating ? <RefreshCw className="animate-spin" size={16} /> : null}
                Create Dashboard
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export const CrmDashboardRoute: React.FC = () => {
  const { dashboardId } = useParams();
  return <CrmDashboardPage dashboardId={dashboardId} />;
};
