'use client';

import { useState } from 'react';
import { api } from '@/lib/api';
import type { Service } from '@/lib/types';
import { X } from 'lucide-react';

interface ServiceFormProps {
  service?: Service;
  onClose: () => void;
  onSuccess: () => void;
}

export function ServiceForm({ service, onClose, onSuccess }: ServiceFormProps) {
  const [formData, setFormData] = useState({
    id: service?.id || '',
    name: service?.name || '',
    scriptPath: service?.scriptPath || '',
    healthUrl: service?.healthUrl || '',
    repoPath: service?.repoPath || '',
  });

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

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

    try {
      if (service) {
        await api.updateService(service.id, formData);
      } else {
        await api.createService(formData);
      }
      onSuccess();
      onClose();
    } catch (err: any) {
      setError(err.error || 'Failed to save service');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50" role="dialog" aria-modal="true" aria-labelledby="service-form-title">
      <div className="bg-white rounded-lg shadow-xl max-w-md w-full mx-4">
        <div className="flex items-center justify-between p-6 border-b border-gray-200">
          <h2 id="service-form-title" className="text-xl font-semibold text-gray-900">
            {service ? 'Edit Service' : 'Create Service'}
          </h2>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500 rounded p-1"
            aria-label="Close form"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        <form onSubmit={handleSubmit} className="p-6 space-y-4">
          {error && (
            <div className="p-3 bg-red-50 border border-red-200 rounded-md text-sm text-red-600">
              {error}
            </div>
          )}

          <div>
            <label htmlFor="id" className="block text-sm font-medium text-gray-700 mb-1">
              Service ID
            </label>
            <input
              type="text"
              id="id"
              value={formData.id}
              onChange={(e) => setFormData({ ...formData, id: e.target.value })}
              disabled={!!service}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 disabled:cursor-not-allowed"
              placeholder="e.g., trading"
              required={!service}
            />
          </div>

          <div>
            <label htmlFor="name" className="block text-sm font-medium text-gray-700 mb-1">
              Service Name
            </label>
            <input
              type="text"
              id="name"
              value={formData.name}
              onChange={(e) => setFormData({ ...formData, name: e.target.value })}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="e.g., Investment Trading"
              required
            />
          </div>

          <div>
            <label htmlFor="scriptPath" className="block text-sm font-medium text-gray-700 mb-1">
              Script Path
            </label>
            <input
              type="text"
              id="scriptPath"
              value={formData.scriptPath}
              onChange={(e) => setFormData({ ...formData, scriptPath: e.target.value })}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="e.g., ../deploy-invttrdg.sh"
              required
            />
          </div>

          <div>
            <label htmlFor="healthUrl" className="block text-sm font-medium text-gray-700 mb-1">
              Health URL
            </label>
            <input
              type="url"
              id="healthUrl"
              value={formData.healthUrl}
              onChange={(e) => setFormData({ ...formData, healthUrl: e.target.value })}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="https://api.bytelyst.com/invttrdg/health"
              required
            />
          </div>

          <div>
            <label htmlFor="repoPath" className="block text-sm font-medium text-gray-700 mb-1">
              Repository Path
            </label>
            <input
              type="text"
              id="repoPath"
              value={formData.repoPath}
              onChange={(e) => setFormData({ ...formData, repoPath: e.target.value })}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="../learning_ai_invt_trdg"
              required
            />
          </div>

          <div className="flex justify-end gap-3 pt-4">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={loading}
              className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-md hover:bg-blue-700 disabled:bg-gray-300 disabled:cursor-not-allowed focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
            >
              {loading ? 'Saving...' : service ? 'Update' : 'Create'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
