import { defineStory, useSelect, useBoolean } from '@djangocfg/playground';
import { Editor, DiffEditor } from './components';

export default defineStory({
  title: 'Tools/Code Editor',
  component: Editor,
  description: 'Monaco-based code editor with syntax highlighting, diff view, and full IDE features.',
});

const SAMPLE_CODE = {
  typescript: `import { useState, useCallback, useMemo } from 'react';

interface User {
  id: string;
  name: string;
  email: string;
  role: 'admin' | 'user' | 'viewer';
}

export function useUsers() {
  const [users, setUsers] = useState<User[]>([]);

  const addUser = useCallback((user: Omit<User, 'id'>) => {
    setUsers(prev => [...prev, { ...user, id: crypto.randomUUID() }]);
  }, []);

  const admins = useMemo(
    () => users.filter(u => u.role === 'admin'),
    [users],
  );

  return { users, admins, addUser };
}`,

  python: `from __future__ import annotations

from dataclasses import dataclass
from datetime import datetime
from typing import AsyncIterator

import httpx
from pydantic import BaseModel, Field


class User(BaseModel):
    id: str
    name: str
    email: str
    role: str = "user"
    created_at: datetime = Field(default_factory=datetime.utcnow)


@dataclass
class UserService:
    base_url: str
    client: httpx.AsyncClient | None = None

    async def list_users(self, page: int = 1) -> list[User]:
        async with httpx.AsyncClient(base_url=self.base_url) as client:
            response = await client.get("/users", params={"page": page})
            response.raise_for_status()
            return [User(**u) for u in response.json()["data"]]`,

  json: `{
  "name": "@djangocfg/ui-tools",
  "version": "2.1.0",
  "description": "Heavy React tools with lazy loading",
  "dependencies": {
    "monaco-editor": "^0.55.1",
    "react": "^19.1.0"
  },
  "exports": {
    ".": "./src/index.ts",
    "./code-editor": "./src/tools/CodeEditor/index.ts"
  }
}`,

  css: `/* Design tokens */
:root {
  --radius: 0.5rem;
  --shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1);
}

.editor-container {
  position: relative;
  border-radius: var(--radius);
  border: 1px solid hsl(var(--border));
  overflow: hidden;

  &:focus-within {
    outline: 2px solid hsl(var(--ring));
    outline-offset: 2px;
  }
}`,
};

const DIFF_ORIGINAL = `function greet(name: string) {
  console.log("Hello, " + name);
}

greet("World");`;

const DIFF_MODIFIED = `function greet(name: string, greeting = "Hello") {
  console.log(\`\${greeting}, \${name}!\`);
}

function farewell(name: string) {
  console.log(\`Goodbye, \${name}!\`);
}

greet("World");
farewell("World");`;

export const Interactive = () => {
  const [language] = useSelect('language', {
    options: ['typescript', 'python', 'json', 'css'] as const,
    defaultValue: 'typescript',
    label: 'Language',
  });

  const [readOnly] = useBoolean('readOnly', {
    defaultValue: false,
    label: 'Read Only',
  });

  const [minimap] = useBoolean('minimap', {
    defaultValue: false,
    label: 'Minimap',
  });

  const [autoHeight] = useBoolean('autoHeight', {
    defaultValue: false,
    label: 'Auto Height',
    description: 'Resize editor to fit content',
  });

  return autoHeight ? (
    <Editor
      value={SAMPLE_CODE[language]}
      language={language}
      autoHeight
      minHeight={100}
      maxHeight={500}
      options={{ readOnly, minimap, fontSize: 14 }}
    />
  ) : (
    <div style={{ height: 400 }}>
      <Editor
        value={SAMPLE_CODE[language]}
        language={language}
        options={{ readOnly, minimap, fontSize: 14 }}
      />
    </div>
  );
};

export const TypeScript = () => (
  <div style={{ height: 350 }}>
    <Editor value={SAMPLE_CODE.typescript} language="typescript" />
  </div>
);

export const Python = () => (
  <div style={{ height: 350 }}>
    <Editor value={SAMPLE_CODE.python} language="python" />
  </div>
);

export const ReadOnly = () => (
  <div style={{ height: 300 }}>
    <Editor
      value={SAMPLE_CODE.json}
      language="json"
      options={{ readOnly: true, lineNumbers: 'on' }}
    />
  </div>
);

export const AutoHeight = () => (
  <div className="flex flex-col gap-4 max-w-3xl">
    <p className="text-sm text-muted-foreground">
      Editor grows with content (min 100px, max 400px). Try typing new lines.
    </p>
    <Editor
      value={`const x = 1;\nconst y = 2;\nconst z = x + y;`}
      language="typescript"
      autoHeight
      minHeight={100}
      maxHeight={400}
    />
  </div>
);

export const DiffView = () => (
  <div style={{ height: 400 }}>
    <DiffEditor
      original={DIFF_ORIGINAL}
      modified={DIFF_MODIFIED}
      language="typescript"
    />
  </div>
);
