import type { WidgetRegistryMeta } from 'officerdev';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useQueryClient, useQuery } from '@tanstack/react-query';
import { useClient } from 'hooks/useClient';
import { useAuth } from 'hooks/useAuth';
import { StickyNote } from 'lucide-react';
import { Widget } from '../Widget';

const USER_STATE_KEY = ['USER_STATE'];
const NOTES_STATE_KEY = 'quick-notes';

function useQuickNotes() {
  const client = useClient();
  const { isAuthenticated } = useAuth();
  const queryClient = useQueryClient();
  const clientRef = useRef(client);
  clientRef.current = client;

  const { data: userState = {} } = useQuery<Record<string, unknown>>({
    queryKey: USER_STATE_KEY,
    enabled: isAuthenticated,
    queryFn: () => client.get('/user/state'),
    staleTime: Infinity,
  });

  const content = (userState[NOTES_STATE_KEY] as string | undefined) ?? '';

  const setContent = useCallback(
    (text: string) => {
      const currentUserState = queryClient.getQueryData<Record<string, unknown>>(USER_STATE_KEY) ?? {};
      queryClient.setQueryData(USER_STATE_KEY, { ...currentUserState, [NOTES_STATE_KEY]: text });
      clientRef.current.patch('/user/state', { [NOTES_STATE_KEY]: text }).catch(() => {});
    },
    [queryClient],
  );

  return [content, setContent] as const;
}

export const QuickNotes = () => {
  const [content, setContent] = useQuickNotes();
  const [local, setLocal] = useState(content);
  const saveTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const initialized = useRef(false);

  // Sync from server on first meaningful load
  useEffect(() => {
    if (initialized.current) return;
    if (content) {
      setLocal(content);
      initialized.current = true;
    }
  }, [content]);

  const handleChange = (text: string) => {
    setLocal(text);
    if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current);
    saveTimeoutRef.current = setTimeout(() => setContent(text), 500);
  };

  // Flush on unmount
  useEffect(() => {
    return () => {
      if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current);
    };
  }, []);

  return (
    <Widget title="Quick Notes">
      <div className="px-4 pb-4">
        <textarea
          value={local}
          onChange={(ev) => handleChange(ev.target.value)}
          placeholder="Jot something down..."
          className="h-32 w-full resize-y rounded-md border border-border bg-background px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring"
        />
      </div>
    </Widget>
  );
};

export const widgetRegistryMetas: WidgetRegistryMeta[] = [
  { key: 'quick-notes', name: 'Quick Notes', icon: StickyNote, component: QuickNotes },
];
