import React, { useCallback, useEffect, useState } from 'react';

import type { StoreContextResponse } from '../../service/visibility/visibility.interface';
import {
  getStoreContext,
  editStoreContext,
  regenerateStoreContext,
} from '../../service/visibility/visibility.service';

interface StoreContextPanelProps {
  /** Merchant client id. */
  clientId: string;
  /** Merchant JWT. */
  token: string;
  /** Brand whose context is shown. */
  brandId: string;
}

interface ContextDraft {
  identity: string;
  proposes: string;
  does: string;
  topics: string;
  tone: string;
}

const draftFromContext = (context: StoreContextResponse): ContextDraft => ({
  identity: context.identity,
  proposes: context.proposes,
  does: context.does,
  topics: context.topics.join(', '),
  tone: context.tone,
});

const FIELD_CLASS =
  'w-full rounded-md border border-gray-300 px-3 py-1.5 text-sm';

/**
 * "Your Knowledge Base" (Beta): the store's living, article-derived identity
 * that Reco keeps and uses. Self-contained - fetches on mount, lets the
 * merchant edit each field, and re-synthesizes from articles on demand.
 */
const StoreContextPanel: React.FC<StoreContextPanelProps> = ({
  clientId,
  token,
  brandId,
}) => {
  const [context, setContext] = useState<StoreContextResponse | null>(null);
  const [draft, setDraft] = useState<ContextDraft | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [regenerating, setRegenerating] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [status, setStatus] = useState<string | null>(null);

  const apply = useCallback((fresh: StoreContextResponse) => {
    setContext(fresh);
    setDraft(draftFromContext(fresh));
  }, []);

  useEffect(() => {
    let cancelled = false;
    setLoading(true);
    setError(null);
    getStoreContext(clientId, token, brandId)
      .then(fresh => {
        if (!cancelled) apply(fresh);
      })
      .catch(() => {
        if (!cancelled) setError("Couldn't load your knowledge base.");
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, [clientId, token, brandId, apply]);

  const patch = (key: keyof ContextDraft, value: string) => {
    setDraft(prev => (prev ? { ...prev, [key]: value } : prev));
    setStatus(null);
  };

  const handleSave = async () => {
    if (!draft) return;
    setSaving(true);
    setError(null);
    setStatus(null);
    try {
      const fresh = await editStoreContext(clientId, token, brandId, {
        identity: draft.identity.trim(),
        proposes: draft.proposes.trim(),
        does: draft.does.trim(),
        tone: draft.tone.trim(),
        topics: draft.topics
          .split(',')
          .map(topic => topic.trim())
          .filter(Boolean),
      });
      apply(fresh);
      setStatus('Saved. Recomaze Co-pilot will use this.');
    } catch {
      setError("Couldn't save your changes.");
    } finally {
      setSaving(false);
    }
  };

  const handleRegenerate = async () => {
    setRegenerating(true);
    setError(null);
    setStatus(null);
    try {
      const fresh = await regenerateStoreContext(clientId, token, brandId);
      apply(fresh);
      setStatus(
        fresh.exists
          ? 'Rebuilt from your articles.'
          : 'No finished articles yet - publish a few, then regenerate.'
      );
    } catch {
      setError("Couldn't regenerate from your articles.");
    } finally {
      setRegenerating(false);
    }
  };

  return (
    <div className="space-y-3 rounded-lg border border-gray-200 bg-gray-50 p-4">
      <div className="flex items-center justify-between gap-2">
        <div className="flex items-center gap-2">
          <span className="font-medium text-gray-900">Your Knowledge Base</span>
          <span className="rounded-full bg-gray-200 px-2 py-0.5 text-xs text-gray-700">
            Beta
          </span>
        </div>
        <button
          type="button"
          onClick={handleRegenerate}
          disabled={regenerating || loading}
          className="rounded-md border border-gray-300 bg-white px-3 py-1.5 text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50"
        >
          {regenerating ? 'Regenerating...' : 'Regenerate from articles'}
        </button>
      </div>

      <p className="text-sm text-gray-600">
        What Recomaze Co-pilot has learned about your store from the content you
        have published. Recomaze Co-pilot uses this across chat and new
        articles. Edit anything; your words win.
      </p>

      {loading ? (
        <div className="py-4 text-sm text-gray-500">Loading...</div>
      ) : (
        <div className="space-y-3">
          {context && !context.exists && (
            <p className="rounded-md bg-white p-3 text-sm text-gray-600">
              Nothing learned yet. Once you have published articles, use the
              Regenerate from articles button to build this.
            </p>
          )}

          <div className="space-y-1.5">
            <label className="text-sm font-medium text-gray-700">
              You are this
            </label>
            <textarea
              rows={3}
              value={draft?.identity ?? ''}
              onChange={event => patch('identity', event.target.value)}
              placeholder="A short description of who your store is."
              className={FIELD_CLASS}
            />
          </div>

          <div className="grid gap-3 sm:grid-cols-2">
            <div className="space-y-1.5">
              <label className="text-sm font-medium text-gray-700">
                What you propose
              </label>
              <textarea
                rows={3}
                value={draft?.proposes ?? ''}
                onChange={event => patch('proposes', event.target.value)}
                className={FIELD_CLASS}
              />
            </div>
            <div className="space-y-1.5">
              <label className="text-sm font-medium text-gray-700">
                What you do
              </label>
              <textarea
                rows={3}
                value={draft?.does ?? ''}
                onChange={event => patch('does', event.target.value)}
                className={FIELD_CLASS}
              />
            </div>
          </div>

          <div className="space-y-1.5">
            <label className="text-sm font-medium text-gray-700">
              Recurring topics
            </label>
            <input
              value={draft?.topics ?? ''}
              onChange={event => patch('topics', event.target.value)}
              placeholder="Comma-separated topics"
              className={FIELD_CLASS}
            />
          </div>

          <div className="space-y-1.5">
            <label className="text-sm font-medium text-gray-700">Tone</label>
            <input
              value={draft?.tone ?? ''}
              onChange={event => patch('tone', event.target.value)}
              className={FIELD_CLASS}
            />
          </div>

          <div className="flex items-center justify-between gap-2">
            <span className="text-xs text-gray-500">
              {context?.source_article_count
                ? `Learned from ${context.source_article_count} article(s).`
                : ''}
            </span>
            <button
              type="button"
              onClick={handleSave}
              disabled={saving}
              className="rounded-md bg-gray-900 px-3 py-1.5 text-sm font-medium text-white hover:bg-gray-800 disabled:opacity-50"
            >
              {saving ? 'Saving...' : 'Save'}
            </button>
          </div>
        </div>
      )}

      {error && <p className="text-sm text-red-600">{error}</p>}
      {status && <p className="text-sm text-gray-600">{status}</p>}
    </div>
  );
};

export default StoreContextPanel;
