import { useState } from 'react';
import { X } from 'lucide-react';
import type { WatchedItem } from '../types';
import { updateItem } from '../api/client';

interface Props {
  item: WatchedItem;
  onClose: () => void;
  onSaved: () => void;
}

function displayName(item: WatchedItem): string {
  if (item.name) return item.name;
  try { return new URL(item.url).pathname.split('/').filter(Boolean).pop() ?? item.url; }
  catch { return item.url; }
}

export default function EditItemModal({ item, onClose, onSaved }: Props) {
  const [interval, setInterval] = useState(String(item.check_interval));
  const [loading, setLoading]   = useState(false);
  const [error, setError]       = useState('');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');

    const secs = Math.max(30, parseInt(interval, 10) || item.check_interval);
    setLoading(true);
    try {
      await updateItem(item.id, { check_interval: secs });
      onSaved();
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : 'Failed to save changes');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="modal-backdrop" onClick={e => e.target === e.currentTarget && onClose()}>
      <div className="modal" role="dialog" aria-modal="true" aria-labelledby="edit-title">
        <div className="modal-header">
          <div>
            <div className="modal-title" id="edit-title">Edit Item</div>
            <div className="modal-subtitle" style={{ maxWidth: 360, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {displayName(item)}
            </div>
          </div>
          <button className="modal-close" onClick={onClose} aria-label="Close">
            <X size={18} />
          </button>
        </div>

        {error && <div className="form-error">{error}</div>}

        <form onSubmit={handleSubmit}>
          <div className="form-group">
            <label className="form-label">Product URL</label>
            <input
              className="form-input"
              type="text"
              value={item.url}
              disabled
              style={{ opacity: 0.5, cursor: 'not-allowed' }}
            />
          </div>

          <div className="form-group">
            <label className="form-label" htmlFor="edit-interval">Check Every (seconds)</label>
            <input
              id="edit-interval"
              className="form-input"
              type="number"
              min="30"
              step="1"
              value={interval}
              onChange={e => setInterval(e.target.value)}
              autoFocus
              required
            />
            <div className="form-hint">Minimum 30 seconds. The scheduler will restart with the new interval immediately.</div>
          </div>

          <div className="form-actions">
            <button type="button" className="btn-secondary" onClick={onClose} disabled={loading}>
              Cancel
            </button>
            <button type="submit" className="btn-primary" disabled={loading}>
              {loading ? <><div className="spinner" style={{ width: 14, height: 14 }} /> Saving…</> : 'Save Changes'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
