'use client';

import * as React from 'react';
import { useFormStatus } from 'react-dom';
import AdminModal from '@/app/components/admin/admin-modal.jsx';
import { createProjectAction } from './actions.js';
import FolderPicker from './folder-picker.jsx';

function slugifyPreview(input) {
  return String(input || '')
    .toLowerCase()
    .trim()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-+|-+$/g, '')
    .slice(0, 64) || 'project';
}

function shortenPath(p, max = 48) {
  if (!p || p.length <= max) return p;
  const head = p.slice(0, Math.floor(max / 2) - 1);
  const tail = p.slice(p.length - Math.floor(max / 2) + 2);
  return `${head}…${tail}`;
}

const COLOR_OPTIONS = [
  { value: '#c2452a', name: 'Mars Red' },
  { value: '#a83a22', name: 'Deep Red' },
  { value: '#7c2b19', name: 'Dark Red' },
  { value: '#111318', name: 'Charcoal' },
  { value: '#3f3a30', name: 'Warm Black' },
  { value: '#68707b', name: 'Slate' },
  { value: '#cdb78a', name: 'Warm Sand' },
  { value: '#1f6c9f', name: 'Skill Blue' },
];

const DEFAULT_COLOR = '#c2452a';

function SubmitButton() {
  const { pending } = useFormStatus();
  return (
    <button
      type="submit"
      className="admin-button"
      disabled={pending}
      aria-busy={pending ? 'true' : undefined}
    >
      {pending ? 'Creating…' : 'Create project'}
    </button>
  );
}

export default function NewProjectModal({ workspaceRoot = '~/workspace/projects' }) {
  const [open, setOpen] = React.useState(false);
  const [name, setName] = React.useState('');
  const [folderMode, setFolderMode] = React.useState('workspace');
  const [customPath, setCustomPath] = React.useState('');
  const customPathRef = React.useRef(null);

  const workspacePreview = React.useMemo(
    () => `${workspaceRoot.replace(/\/$/, '')}/${slugifyPreview(name)}`,
    [workspaceRoot, name],
  );

  React.useEffect(() => {
    if (folderMode === 'custom') customPathRef.current?.focus();
  }, [folderMode]);

  return (
    <>
      <button type="button" className="admin-button agents-new-cta" onClick={() => setOpen(true)}>
        <span aria-hidden className="agents-new-cta-glyph">+</span>
        New project
      </button>

      <AdminModal
        open={open}
        onClose={() => setOpen(false)}
        eyebrow="New project"
        title="Create a project"
      >
        <form className="agents-modal-form" action={createProjectAction}>
          <p className="agents-modal-help">
            Scope agents, documents, memory, and integrations together.
          </p>

          <section className="agents-modal-section">
            <label className="agents-modal-field wide">
              <span>Name</span>
              <input
                name="name"
                type="text"
                required
                placeholder="Acme Co."
                autoComplete="off"
                value={name}
                onChange={(e) => setName(e.target.value)}
                autoFocus
              />
            </label>
          </section>

          <section className="agents-modal-section">
            <div className="agents-modal-section-head">
              <span>Folder location</span>
              <small>Where this project lives on disk.</small>
            </div>
            <div className="agents-modal-radio-group">
              <label
                className={`agents-modal-radio ${folderMode === 'workspace' ? 'on' : ''}`}
              >
                <input
                  type="radio"
                  name="folder_mode"
                  value="workspace"
                  checked={folderMode === 'workspace'}
                  onChange={() => setFolderMode('workspace')}
                />
                <span className="agents-modal-radio-body">
                  <b>madarX workspace</b>
                  <code title={workspacePreview}>{shortenPath(workspacePreview)}</code>
                </span>
              </label>
              <label
                className={`agents-modal-radio ${folderMode === 'custom' ? 'on' : ''}`}
              >
                <input
                  type="radio"
                  name="folder_mode"
                  value="custom"
                  checked={folderMode === 'custom'}
                  onChange={() => setFolderMode('custom')}
                />
                <span className="agents-modal-radio-body">
                  <b>Custom path</b>
                  <small>Any absolute folder. Created if missing.</small>
                </span>
              </label>
            </div>
            {folderMode === 'custom' ? (
              <FolderPicker
                inputRef={customPathRef}
                value={customPath}
                onChange={setCustomPath}
              />
            ) : (
              <input type="hidden" name="folder_path" value="" />
            )}
          </section>

          <section className="agents-modal-section">
            <div className="agents-modal-section-head">
              <span>Color</span>
              <small>Used for the project tile across the app.</small>
            </div>
            <fieldset className="agents-modal-swatches">
              <legend className="visually-hidden">Project color</legend>
              {COLOR_OPTIONS.map((c) => (
                <label
                  key={c.value}
                  className="agents-modal-swatch"
                  style={{ '--swatch': c.value }}
                >
                  <input
                    type="radio"
                    name="color"
                    value={c.value}
                    defaultChecked={c.value === DEFAULT_COLOR}
                  />
                  <span className="agents-modal-swatch-ring" aria-hidden="true" />
                  <span className="visually-hidden">{c.name}</span>
                </label>
              ))}
            </fieldset>
          </section>

          <section className="agents-modal-section">
            <div className="agents-modal-section-head">
              <span>Description</span>
              <small>Used as context for agents working in this project.</small>
            </div>
            <label className="agents-modal-field wide">
              <textarea
                name="description"
                rows={3}
                placeholder="What is this project for? Goals, audience, voice, constraints."
              />
            </label>
          </section>

          <footer className="agents-modal-foot">
            <button
              type="button"
              className="admin-button secondary"
              onClick={() => setOpen(false)}
            >
              Cancel
            </button>
            <SubmitButton />
          </footer>
        </form>
      </AdminModal>
    </>
  );
}
