import { useQuery } from '@tanstack/react-query';
import { useNavigate, useParams } from 'react-router';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import rehypeRaw from 'rehype-raw';
import { useClient } from 'hooks/useClient';
import { Card } from '@/components/Card';

/**
 * A plan is a markdown document on disk, so it gets an address: `/plans/:name`. No redirect guard — the
 * bare route is "no plan open" and a name that no longer exists gets the empty pane, not a rewritten URL.
 *
 * The picker stays a native `<select>` rather than becoming a link list. It is chrome for one document,
 * not a master list, and a `<select>` is the right control for that on a phone; it navigates instead of
 * setting state, which is what M4 was actually about.
 */
export const Plans = () => {
  const client = useClient();
  const navigate = useNavigate();
  const selected = useParams<{ name: string }>().name ?? null;

  const { data: plans = [] } = useQuery<string[]>({
    queryKey: ['plans'],
    queryFn: () => client.get<string[]>('/plans'),
  });

  const { data: content = '' } = useQuery<string>({
    queryKey: ['plans', selected],
    queryFn: () => client.getText(`/plans/${encodeURIComponent(selected!)}`),
    enabled: !!selected,
  });

  return (
    <div className="flex flex-col h-full p-4">
      <Card className="flex-1 overflow-hidden">
        <div className="shrink-0 flex items-center gap-3 px-4 py-2 border-b border-duck-dark/10 bg-background/60">
          <span className="text-sm font-medium text-duck-dark/70">Plans</span>
          {plans.length > 0 && (
            <select
              value={selected ?? ''}
              onChange={(ev) => navigate(`/plans/${encodeURIComponent(ev.target.value)}`)}
              className="text-xs border border-duck-dark/20 rounded px-2 py-1 bg-background/80 text-duck-dark"
            >
              {/* Only while nothing is chosen: it disappears once you pick, so it can never be picked back. */}
              {!selected && <option value="">Select a plan…</option>}
              {plans.map((p) => (
                <option key={p} value={p}>
                  {p}
                </option>
              ))}
            </select>
          )}
        </div>

        <div className="overflow-y-auto h-full p-6">
          {selected ? (
            <div className="prose prose-sm dark:prose-invert max-w-none prose-headings:text-duck-dark prose-a:text-duck-teal prose-pre:bg-gray-900 prose-pre:text-green-400 prose-code:text-duck-teal prose-code:before:content-none prose-code:after:content-none prose-td:text-sm prose-th:text-sm">
              <ReactMarkdown remarkPlugins={[remarkGfm]} rehypePlugins={[rehypeRaw]}>
                {content}
              </ReactMarkdown>
            </div>
          ) : (
            <p className="text-sm text-duck-dark/50">
              {plans.length === 0 ? 'No plans yet.' : 'Pick a plan to read it.'}
            </p>
          )}
        </div>
      </Card>
    </div>
  );
};
