import React, { useEffect, useState } from 'react';
import { type SimpleInsight } from '../Context.js';
import { updateInsight } from '../utilities/insight.js';
import { Loader } from 'lucide-react';
import './GuidanceItemSelect.css';
import clsx from 'clsx';
import SkeletonLoader from './SkeletonLoader.js';

const GuidanceItemSelect = ({
  draftId,
  insight,
  refreshInsights,
  label,
  topPagesText = 'Top pages',
}: {
  draftId: string;
  insight: SimpleInsight | undefined;
  refreshInsights: () => Promise<void> | undefined;
  label: string;
  topPagesText?: string;
}) => {
  const [editOpen, setEditOpen] = useState<boolean>(false);
  const [saving, setSaving] = useState<boolean>(false);
  const [value, setValue] = useState<string>('');
  const options = insight?.options?.length ? insight.options : [];

  useEffect(() => {
    if (insight?.value !== undefined) {
      setValue(insight.value);
    }
  }, [insight?.value]);

  const saveValue = async () => {
    setSaving(true);
    setEditOpen(false);
    try {
      if (value && value.length && insight?.key) {
        await updateInsight({ draftId, type: insight.key, value });
      }
    } finally {
      await refreshInsights();
      setSaving(false);
    }
  };

  // Replicate the HTML structure to minimise layout shift when the data loads.
  if (!insight) {
    return (
      <div className="guidance-item-select guidance-item-select--is-loading">
        <div>
          {topPagesText}: <SkeletonLoader numberOfLines={1} />
        </div>
        <div className="guidance-item-select__value">
          <strong>{label}: </strong>
          <SkeletonLoader numberOfLines={1} />
        </div>
        <div className="guidance-item-select__buttons">
          <Loader />
        </div>
      </div>
    );
  }

  return (
    <div
      className={clsx('guidance-item-select', {
        'guidance-item-select--is-saving': saving,
        'guidance-item-select--is-editing': editOpen,
      })}
    >
      <div className="guidance-item-select__top-pages">
        {topPagesText}: <strong>{insight.initialValue}</strong>
      </div>
      <div>
        {label}: {!editOpen && !saving && insight.value} {saving && <Loader />}
      </div>
      <div className="guidance-item-select__customize">
        {editOpen && (
          <select value={value} onChange={(e) => setValue(e.target.value)}>
            {options.map((option) => (
              <option key={option} value={option}>
                {option}
              </option>
            ))}
          </select>
        )}
      </div>
      <div className="guidance-item-select__buttons">
        {!editOpen && (
          <button
            disabled={saving}
            className="guidance-item-select__button"
            onClick={() => {
              setEditOpen(true);
            }}
          >
            Customize {label.toLowerCase()}
          </button>
        )}
        {''}
        {editOpen && (
          <>
            <button
              className="guidance-item-select__button"
              onClick={() => {
                setEditOpen(false);
                setValue(insight.value);
              }}
            >
              Cancel
            </button>
            <button className="guidance-item-select__button" onClick={saveValue}>
              Save {label.toLowerCase()}
            </button>
          </>
        )}
      </div>
    </div>
  );
};

export default GuidanceItemSelect;
