"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";

export default function TicketReplyForm({ ticketId }: { ticketId: number }) {
  const router = useRouter();
  const [body, setBody] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!body.trim()) return;

    setSubmitting(true);
    setError("");

    try {
      const res = await fetch(`/api/tickets/${ticketId}/messages`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ body: body.trim() }),
      });

      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || "Failed to send reply");
      }

      setBody("");
      router.refresh();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Something went wrong");
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-3">
      <label htmlFor="reply" className="block text-sm font-medium">
        Reply
      </label>
      <textarea
        id="reply"
        value={body}
        onChange={(e) => setBody(e.target.value)}
        rows={4}
        className="w-full bg-background border border-surface-light rounded-lg px-3 py-2 text-text placeholder:text-text-muted focus:outline-none focus:ring-2 focus:ring-primary resize-y"
        placeholder="Type your reply..."
        required
      />
      {error && (
        <div className="bg-red-500/10 border border-red-500/20 rounded-lg p-3 text-red-400 text-sm">
          {error}
        </div>
      )}
      <button
        type="submit"
        disabled={submitting || !body.trim()}
        className="bg-primary hover:bg-primary/90 disabled:opacity-50 text-white font-medium rounded-lg px-4 py-2 text-sm transition-colors"
      >
        {submitting ? "Sending..." : "Send Reply"}
      </button>
    </form>
  );
}
