import * as React from 'react';
import { useState } from 'react';
import { useParams, Link } from 'react-router-dom';
import { api, type Prompt } from '../api';
import { useFetch } from '../hooks/useFetch';
import { PromptEditor, type PromptDraft } from '../components/PromptEditor';

/**
 * Project prompts editor:
 *   - GET /api/v1/prompts?project=<name> to list (project-scoped + globals)
 *   - filter to project-only for this view
 *   - inline create / edit / delete; Monaco for content
 */
export function ProjectPromptsPage(): React.JSX.Element {
  const { name } = useParams<{ name: string }>();
  const projectName = name ?? '';
  const { data, error, loading, refetch } = useFetch(
    () => api.get<Prompt[]>(`/api/v1/prompts?project=${encodeURIComponent(projectName)}`),
    [projectName],
  );

  const [editingId, setEditingId] = useState<string | null>(null);
  const [creating, setCreating] = useState(false);
  const [busy, setBusy] = useState(false);

  if (loading) return <div>Loading prompts…</div>;
  if (error !== null) return <div style={{ color: '#ff7b72' }}>Error: {error.message}</div>;
  const all = data ?? [];
  // Filter to project-scoped only — the API includes globals as well.
  const prompts = all.filter((p) => p.projectId !== null);

  async function handleCreate(draft: PromptDraft): Promise<void> {
    setBusy(true);
    try {
      await api.post('/api/v1/prompts', {
        name: draft.name,
        content: draft.content,
        priority: draft.priority,
        project: projectName,
      });
      setCreating(false);
      refetch();
    } finally {
      setBusy(false);
    }
  }

  async function handleUpdate(id: string, draft: PromptDraft): Promise<void> {
    setBusy(true);
    try {
      await api.put(`/api/v1/prompts/${id}`, {
        content: draft.content,
        priority: draft.priority,
      });
      setEditingId(null);
      refetch();
    } finally {
      setBusy(false);
    }
  }

  async function handleDelete(id: string, name: string): Promise<void> {
    if (!confirm(`Delete prompt '${name}'?`)) return;
    await api.delete(`/api/v1/prompts/${id}`);
    refetch();
  }

  return (
    <section>
      <p style={{ marginTop: 0 }}>
        <Link to="/projects" style={{ color: '#58a6ff' }}>← Projects</Link>
      </p>
      <h2 style={{ marginTop: 0 }}>{projectName}<span style={{ color: '#7d8590' }}> · prompts</span></h2>
      {!creating && (
        <button onClick={() => setCreating(true)} style={primaryBtn}>+ New prompt</button>
      )}
      {creating && (
        <div style={card}>
          <h3>New prompt</h3>
          <PromptEditor
            submitLabel="Create"
            onSubmit={handleCreate}
            onCancel={() => setCreating(false)}
            busy={busy}
          />
        </div>
      )}
      {prompts.length === 0 && !creating && (
        <p style={{ color: '#7d8590' }}>No prompts in this project yet.</p>
      )}
      <ul style={{ listStyle: 'none', padding: 0, margin: '16px 0 0 0' }}>
        {prompts.sort((a, b) => b.priority - a.priority).map((p) => (
          <li key={p.id} style={card}>
            {editingId === p.id ? (
              <>
                <h3>Edit prompt: {p.name}</h3>
                <PromptEditor
                  initial={{ name: p.name, priority: p.priority, content: p.content }}
                  nameLocked
                  submitLabel="Save"
                  onSubmit={(d) => handleUpdate(p.id, d)}
                  onCancel={() => setEditingId(null)}
                  busy={busy}
                />
              </>
            ) : (
              <>
                <div style={cardHeader}>
                  <div>
                    <strong style={{ fontFamily: 'ui-monospace, monospace' }}>{p.name}</strong>
                    <span style={{ color: '#7d8590', marginLeft: 8, fontSize: 12 }}>
                      priority {p.priority}
                    </span>
                  </div>
                  <div style={{ display: 'flex', gap: 8 }}>
                    <button onClick={() => setEditingId(p.id)} style={secondaryBtn}>Edit</button>
                    <button onClick={() => handleDelete(p.id, p.name)} style={dangerBtn}>Delete</button>
                  </div>
                </div>
                <pre style={contentPre}>{p.content}</pre>
              </>
            )}
          </li>
        ))}
      </ul>
    </section>
  );
}

const card: React.CSSProperties = {
  background: '#161b22',
  border: '1px solid #30363d',
  borderRadius: 6,
  padding: 16,
  margin: '12px 0',
};
const cardHeader: React.CSSProperties = {
  display: 'flex',
  justifyContent: 'space-between',
  alignItems: 'center',
  marginBottom: 8,
};
const contentPre: React.CSSProperties = {
  background: '#0d1117',
  color: '#c9d1d9',
  padding: 12,
  borderRadius: 4,
  margin: 0,
  whiteSpace: 'pre-wrap',
  fontFamily: 'ui-monospace, "SF Mono", Menlo, monospace',
  fontSize: 12,
};
const primaryBtn: React.CSSProperties = {
  background: '#238636',
  color: '#fff',
  border: 'none',
  borderRadius: 4,
  padding: '8px 16px',
  cursor: 'pointer',
  fontWeight: 600,
};
const secondaryBtn: React.CSSProperties = {
  background: 'transparent',
  color: '#c9d1d9',
  border: '1px solid #30363d',
  borderRadius: 4,
  padding: '4px 12px',
  cursor: 'pointer',
};
const dangerBtn: React.CSSProperties = {
  background: 'transparent',
  color: '#ff7b72',
  border: '1px solid #f85149',
  borderRadius: 4,
  padding: '4px 12px',
  cursor: 'pointer',
};
