'use client';

import { useState } from 'react';

const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000';

interface CreateIssueFormProps {
  taskId: string;
  projectId: string;
  workspaceId: string;
  onSuccess: () => void;
  onCancel: () => void;
}

export default function CreateIssueForm({ taskId, projectId, workspaceId, onSuccess, onCancel }: CreateIssueFormProps) {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [formData, setFormData] = useState({
    title: '',
    description: '',
  });

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

    try {
      const res = await fetch(`${API_BASE}/api/v1/project-management/issues`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          task_id: taskId,
          project_id: projectId,
          workspace_id: workspaceId,
          ...formData,
        }),
      });

      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.detail || '创建失败');
      }

      onSuccess();
    } catch (err: any) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} style={{
      background: 'var(--bg-white)',
      padding: '20px',
      borderRadius: '8px',
      border: '1px solid var(--border)',
    }}>
      {error && (
        <div style={{
          padding: '12px',
          background: '#FFECE8',
          border: '1px solid var(--error)',
          borderRadius: '4px',
          color: 'var(--error)',
          marginBottom: '16px',
        }}>
          {error}
        </div>
      )}

      <div style={{ marginBottom: '12px' }}>
        <label style={{ display: 'block', marginBottom: '6px', fontWeight: '500' }}>
          问题标题 <span style={{ color: 'var(--error)' }}>*</span>
        </label>
        <input
          type="text"
          required
          value={formData.title}
          onChange={(e) => setFormData({ ...formData, title: e.target.value })}
          style={{
            width: '100%',
            padding: '8px 12px',
            border: '1px solid var(--border)',
            borderRadius: '4px',
            fontSize: '14px',
          }}
          placeholder="简要描述问题"
        />
      </div>

      <div style={{ marginBottom: '16px' }}>
        <label style={{ display: 'block', marginBottom: '6px', fontWeight: '500' }}>
          详细描述
        </label>
        <textarea
          value={formData.description}
          onChange={(e) => setFormData({ ...formData, description: e.target.value })}
          rows={3}
          style={{
            width: '100%',
            padding: '8px 12px',
            border: '1px solid var(--border)',
            borderRadius: '4px',
            fontSize: '14px',
            resize: 'vertical',
          }}
          placeholder="详细说明问题情况"
        />
      </div>

      <div style={{ display: 'flex', gap: '10px' }}>
        <button
          type="submit"
          disabled={loading}
          style={{
            flex: 1,
            padding: '8px',
            borderRadius: '4px',
            border: 'none',
            background: loading ? '#ccc' : 'var(--primary)',
            color: 'white',
            fontWeight: 'bold',
            cursor: loading ? 'not-allowed' : 'pointer',
          }}
        >
          {loading ? '创建中...' : '创建问题'}
        </button>
        <button
          type="button"
          onClick={onCancel}
          style={{
            flex: 1,
            padding: '8px',
            borderRadius: '4px',
            border: '1px solid var(--border)',
            background: 'white',
            cursor: 'pointer',
          }}
        >
          取消
        </button>
      </div>
    </form>
  );
}
