'use client';

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

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' },
];

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

export default function EditProjectButton({ projectId, projectName, projectColor, projectDescription, projectFolderPath }) {
  const [open, setOpen] = React.useState(false);
  const [folderMode, setFolderMode] = React.useState('keep');
  const [customPath, setCustomPath] = React.useState(projectFolderPath || '');
  const customPathRef = React.useRef(null);

  React.useEffect(() => {
    if (open) {
      setFolderMode('keep');
      setCustomPath(projectFolderPath || '');
    }
  }, [open, projectFolderPath]);

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

  return (
    <>
      <button type="button" className="admin-button secondary project-edit" onClick={() => setOpen(true)} aria-label={`Edit ${projectName}`}>
        Edit
      </button>

      <AdminModal open={open} onClose={() => setOpen(false)} eyebrow="Edit project" title={`Edit ${projectName}`}>
        <form className="agents-modal-form" action={updateProjectAction}>
          <input type="hidden" name="project_id" value={projectId} />

          <section className="agents-modal-section">
            <label className="agents-modal-field wide">
              <span>Name</span>
              <input name="name" type="text" defaultValue={projectName} autoComplete="off" required />
            </label>
          </section>

          <section className="agents-modal-section">
            <div className="agents-modal-section-head">
              <span>Folder location</span>
              <small>Where project files live on disk. Move only if you've already moved the folder yourself.</small>
            </div>
            <div className="agents-modal-radio-group">
              <label className={`agents-modal-radio ${folderMode === 'keep' ? 'on' : ''}`}>
                <input type="radio" name="folder_mode" value="keep" checked={folderMode === 'keep'} onChange={() => setFolderMode('keep')} />
                <span className="agents-modal-radio-body">
                  <b>Keep current</b>
                  <code title={projectFolderPath || ''}>{shortenPath(projectFolderPath) || '(not set)'}</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>Change to…</b>
                  <small>Absolute path. Must already exist or be writable.</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>Tile color 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 === (projectColor || '#c2452a')} />
                  <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}
                defaultValue={projectDescription || ''}
                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>
    </>
  );
}
