'use client';

import { useState } from 'react';
import { Field, FormDrawer } from '@/components/crm/FormDrawer';
import { useOpenCount } from '@/features/contacts/ui/actions/shared';
import {
  DASHBOARD_DATE_RANGES,
  DASHBOARD_GRID_COLUMNS,
  DASHBOARD_REPORT_IDS,
  DATE_RANGE_LABEL,
  REPORT_LABEL,
  type DashboardReportId,
  type DashboardBuiltInWidget,
  type DashboardWidgetFilters,
} from '../types';
import { usePipelines } from '../ui/panels';
import { DEFAULT_WIDGET_RANGE, takesDateRange } from '../ui/WidgetView';

const HALF = DASHBOARD_GRID_COLUMNS / 2;

export function newWidgetId(): string {
  try {
    return crypto.randomUUID();
  } catch {
    return `w-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
  }
}

/**
 * "Add report from library" (the 7 reports a widget can show), and a widget's "Report settings"
 * (`widget` set): title, date range, forecast period and pipeline (QA #570), width.
 */
export function WidgetDrawer({
  open,
  widget,
  onClose,
  onSave,
}: {
  open: boolean;
  /** Set: change this widget; otherwise add a new one. */
  widget: DashboardBuiltInWidget | null;
  onClose: () => void;
  onSave: (widget: DashboardBuiltInWidget) => Promise<boolean>;
}) {
  const [reportId, setReportId] = useState<DashboardReportId>('won_by_month');
  const openCount = useOpenCount(open, () => setReportId(widget?.reportId ?? 'won_by_month'));
  const { pipelines } = usePipelines();
  const f = widget?.filters ?? {};

  const onSubmit = async (d: Record<string, string>) => {
    // Keep the filters this form doesn't show (owner, group by, types…) when editing.
    const filters: DashboardWidgetFilters = widget && widget.reportId === reportId ? { ...f } : {};
    if (takesDateRange(reportId)) {
      if (d.dateRange) filters.dateRange = d.dateRange as DashboardWidgetFilters['dateRange'];
    }
    if (reportId === 'forecast') {
      if (d.period) filters.period = d.period;
      if (d.pipelineId) filters.pipelineId = d.pipelineId;
      else delete filters.pipelineId;
    }
    const title = (d.title ?? '').trim();
    const width = d.width === 'full' ? DASHBOARD_GRID_COLUMNS : HALF;
    return onSave({
      id: widget?.id ?? newWidgetId(),
      reportId,
      title: title || null,
      filters,
      position: widget ? { ...widget.position, w: width } : { x: 0, y: 1000, w: width, h: 4 },
    });
  };

  const currentWidth = widget
    ? widget.position.w >= DASHBOARD_GRID_COLUMNS
      ? 'full'
      : 'half'
    : reportId === 'activity'
      ? 'full'
      : 'half';

  return (
    <FormDrawer
      id="addWidgetDrawer"
      title={widget ? 'Report settings' : 'Add report from library'}
      submitLabel={widget ? 'Save' : 'Add report'}
      open={open}
      onClose={onClose}
      onSubmit={onSubmit}
    >
      <div className="form-grid" key={openCount}>
        <Field label="Report" htmlFor="widgetReport" className="span-2">
          <select
            className="input"
            id="widgetReport"
            value={reportId}
            disabled={widget !== null}
            onChange={(e) => setReportId(e.target.value as DashboardReportId)}
          >
            {DASHBOARD_REPORT_IDS.map((r) => (
              <option key={r} value={r}>
                {REPORT_LABEL[r]}
              </option>
            ))}
          </select>
        </Field>
        <Field label="Title (optional)" htmlFor="widgetTitle" className="span-2">
          <input
            className="input"
            id="widgetTitle"
            name="title"
            maxLength={191}
            placeholder={REPORT_LABEL[reportId]}
            defaultValue={widget?.title ?? ''}
          />
        </Field>
        {takesDateRange(reportId) ? (
          <Field label="Date range" htmlFor="widgetRange">
            <select
              key={reportId}
              className="input"
              id="widgetRange"
              name="dateRange"
              defaultValue={f.dateRange ?? DEFAULT_WIDGET_RANGE[reportId]}
            >
              {DASHBOARD_DATE_RANGES.map((r) => (
                <option key={r} value={r}>
                  {DATE_RANGE_LABEL[r]}
                </option>
              ))}
            </select>
          </Field>
        ) : reportId === 'forecast' ? (
          <Field label="Forecast by" htmlFor="widgetPeriod">
            <select
              className="input"
              id="widgetPeriod"
              name="period"
              defaultValue={f.period ?? 'month'}
            >
              <option value="month">Month</option>
              <option value="quarter">Quarter</option>
            </select>
          </Field>
        ) : (
          <div />
        )}
        <Field label="Width" htmlFor="widgetWidth">
          <select
            className="input"
            id="widgetWidth"
            name="width"
            defaultValue={currentWidth}
            key={`w-${reportId}`}
          >
            <option value="half">Half width</option>
            <option value="full">Full width</option>
          </select>
        </Field>
        {reportId === 'forecast' ? (
          <Field label="Pipeline" htmlFor="widgetPipeline" className="span-2">
            <select
              className="input"
              id="widgetPipeline"
              name="pipelineId"
              defaultValue={f.pipelineId ?? ''}
              key={`p-${pipelines.length}`}
            >
              <option value="">All pipelines</option>
              {pipelines.map((p) => (
                <option key={p.id} value={p.id}>
                  {p.name}
                </option>
              ))}
            </select>
          </Field>
        ) : null}
      </div>
    </FormDrawer>
  );
}
