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

const GuidanceItemTextArea = ({
  draftId,
  insight,
  refreshInsights,
  label,
}: {
  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>('');

  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-textarea guidance-item-textarea--is-loading">
        <div className="guidance-item-textarea__top-pages">
          <strong>{label}:</strong> <SkeletonLoader numberOfLines={1} />
        </div>
        <div className="guidance-item-textarea__buttons">
          <Loader />
        </div>
      </div>
    );
  }

  return (
    <div
      className={clsx('guidance-item-textarea', {
        'guidance-item-textarea--is-saving': saving,
        'guidance-item-textarea--is-editing': editOpen,
      })}
    >
      <div className="guidance-item-textarea__top-pages">
        <strong>{label}:</strong> {!editOpen && !saving && value} {saving && <Loader />}
      </div>
      <div className="guidance-item-textarea__customize">
        {editOpen && (
          <textarea
            value={value}
            onChange={(e) => setValue(e.target.value)}
            rows={4}
            placeholder="Enter custom objective…"
          />
        )}
      </div>
      <div className="guidance-item-textarea__buttons">
        {!editOpen && (
          <button
            disabled={saving}
            className="guidance-item-textarea__button"
            onClick={() => {
              setEditOpen(true);
            }}
          >
            {insight?.value === insight?.initialValue
              ? `Customize ${label.toLowerCase()}`
              : `Customize or reset ${label.toLowerCase()}`}
          </button>
        )}
        {editOpen && (
          <>
            <button
              className="guidance-item-textarea__button"
              onClick={() => {
                setEditOpen(false);
                setValue(insight.value);
              }}
            >
              Cancel
            </button>
            <button
              className="guidance-item-textarea__button"
              onClick={() => {
                setValue(insight.initialValue);
              }}
              title="Reverts your current selection back to the default"
            >
              Reset
            </button>
            <button
              className="guidance-item-textarea__button"
              onClick={saveValue}
              disabled={!value.length}
            >
              Save {label.toLowerCase()}
            </button>
          </>
        )}
      </div>
    </div>
  );
};

export default GuidanceItemTextArea;
