import React, { useState } from "react";
import TicketFieldRow from "./TicketRow";
import TicketTextarea from "./TicketText";
import type { CreateTicketFormData } from "../../types/ticket";

interface TicketFormProps {
  onError: (msg: string | null) => void;
}

const TicketForm: React.FC<TicketFormProps> = ({ onError }) => {
  const [form, setForm] = useState<CreateTicketFormData>({
    title: "",
    status: "Open",
    priority: "4",
    category: "General",
    type: "Issue",
    description: "",
  });

  function updateField(field: keyof CreateTicketFormData, value: string) {
    setForm(prev => ({ ...prev, [field]: value }));
  }

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();

    if (!form.title.trim() || !form.description.trim()) {
      onError("Title and description are required.");
      return;
    }

    console.log("Submitting:", form);
    // Later: POST to Express/PHP
  }

  return (
    <form className="ticket-form" onSubmit={handleSubmit}>
      <div className="ticket-details">
        <div className="detail-group">
          <label>Title</label>
          <input
            type="text"
            value={form.title}
            onChange={e => updateField("title", e.target.value)}
            required
          />
        </div>

        <TicketFieldRow form={form} updateField={updateField} />

        <TicketTextarea
          label="Description"
          value={form.description}
          onChange={value => updateField("description", value)}
          required
        />
      </div>

      <div className="ticket-footer">
        <button type="submit" className="btn primary">Create Ticket</button>
        <button
          type="button"
          className="btn back-btn"
          onClick={() => (window.location.href = "/")}
        >
          Cancel
        </button>
      </div>
    </form>
  );
};

export default TicketForm;
