import { Component, createSignal } from 'solid-js';
import { useNavigate } from '@solidjs/router';
import { useAuth } from '../../lib/auth';
import { createProjectService } from '../../lib/projects/service';

export const ProjectForm: Component<any> = () => {
  const auth = useAuth();
  const navigate = useNavigate();
  const projectService = createProjectService();

  const [name, setName] = createSignal('');
  const [description, setDescription] = createSignal('');
  const [error, setError] = createSignal('');

  const handleSubmit = async (e: Event) => {
    e.preventDefault();
    if (!name().trim()) {
      setError('Project name is required');
      return;
    }

    const user = auth().user;
    if (!user) {
      setError('User not authenticated');
      return;
    }

    try {
      const project = await projectService.createProject(
        name().trim(),
        description().trim(),
        user.id
      );
      navigate(`/projects/${project.id}`);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to create project');
    }
  };

  return (
    <div class="freno-project-form">
      <div class="freno-page-header">
        <h1>New Project</h1>
        <button class="freno-btn freno-btn-secondary" onClick={() => navigate('/projects')}>
          Cancel
        </button>
      </div>

      {error() && (
        <div class="freno-alert freno-alert-error">{error()}</div>
      )}

      <form class="freno-form" onSubmit={handleSubmit}>
        <div class="freno-form-group">
          <label class="freno-label" for="project-name">Project Name</label>
          <input
            class="freno-input"
            id="project-name"
            type="text"
            placeholder="My Screenplay"
            value={name()}
            onInput={(e) => setName(e.target.value)}
            autofocus
          />
        </div>

        <div class="freno-form-group">
          <label class="freno-label" for="project-desc">Description</label>
          <textarea
            class="freno-textarea"
            id="project-desc"
            placeholder="A brief description of your project..."
            value={description()}
            onInput={(e) => setDescription(e.target.value)}
            rows={4}
          />
        </div>

        <div class="freno-form-actions">
          <button type="submit" class="freno-btn freno-btn-primary">
            Create Project
          </button>
        </div>
      </form>
    </div>
  );
};
