"use client";

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

type Props = {
  ticketId: number;
  currentStatus: string;
  currentPriority: string;
  currentAssignedTo: number | null;
};

export default function AdminTicketActions({
  ticketId,
  currentStatus,
  currentPriority,
  currentAssignedTo,
}: Props) {
  const router = useRouter();
  const [status, setStatus] = useState(currentStatus);
  const [priority, setPriority] = useState(currentPriority);
  const [assignedTo, setAssignedTo] = useState(currentAssignedTo?.toString() || "");
  const [replyBody, setReplyBody] = useState("");
  const [saving, setSaving] = useState(false);
  const [replying, setReplying] = useState(false);
  const [summarizing, setSummarizing] = useState(false);
  const [error, setError] = useState("");

  async function handleUpdateTicket() {
    setSaving(true);
    setError("");
    try {
      const res = await fetch(`/api/tickets/${ticketId}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          status,
          priority,
          assigned_to: assignedTo || null,
        }),
      });
      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || "Failed to update");
      }
      router.refresh();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Something went wrong");
    } finally {
      setSaving(false);
    }
  }

  async function handleReply() {
    if (!replyBody.trim()) return;
    setReplying(true);
    setError("");
    try {
      const res = await fetch(`/api/tickets/${ticketId}/messages`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ body: replyBody.trim() }),
      });
      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || "Failed to reply");
      }
      setReplyBody("");
      router.refresh();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Something went wrong");
    } finally {
      setReplying(false);
    }
  }

  async function handleGenerateSummary() {
    setSummarizing(true);
    setError("");
    try {
      const ticketRes = await fetch(`/api/tickets/${ticketId}`);
      if (!ticketRes.ok) throw new Error("Failed to fetch ticket");
      const { ticket } = await ticketRes.json();

      const messagesText = ticket.messages
        .map((m: { is_admin: boolean; is_ai: boolean; body: string }) =>
          `[${m.is_admin ? "Admin" : m.is_ai ? "AI" : "User"}]: ${m.body}`
        )
        .join("\n\n");

      const res = await fetch("/api/ai/support-chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          messages: [
            {
              role: "user",
              content: `Summarize this support ticket thread in 2-3 bullet points:\n\nSubject: ${ticket.subject}\nCategory: ${ticket.category}\n\n${messagesText}`,
            },
          ],
          query: "summarize ticket",
        }),
      });

      if (!res.ok) throw new Error("Failed to generate summary");
      const data = await res.json();

      // Save summary to ticket
      await fetch(`/api/tickets/${ticketId}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ai_summary: data.reply }),
      });

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

  return (
    <div className="space-y-6">
      {/* Status / Priority / Assign */}
      <div className="bg-surface rounded-xl border border-surface-light p-5 space-y-4">
        <h3 className="font-semibold text-sm">Ticket Actions</h3>

        <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
          <div>
            <label className="block text-xs text-text-muted mb-1">Status</label>
            <select
              value={status}
              onChange={(e) => setStatus(e.target.value)}
              className="w-full bg-background border border-surface-light rounded-lg px-3 py-2 text-sm text-text focus:outline-none focus:ring-1 focus:ring-primary"
            >
              <option value="open">Open</option>
              <option value="in_progress">In Progress</option>
              <option value="resolved">Resolved</option>
              <option value="closed">Closed</option>
            </select>
          </div>
          <div>
            <label className="block text-xs text-text-muted mb-1">Priority</label>
            <select
              value={priority}
              onChange={(e) => setPriority(e.target.value)}
              className="w-full bg-background border border-surface-light rounded-lg px-3 py-2 text-sm text-text focus:outline-none focus:ring-1 focus:ring-primary"
            >
              <option value="normal">Normal</option>
              <option value="high">High</option>
            </select>
          </div>
          <div>
            <label className="block text-xs text-text-muted mb-1">Assign to (user ID)</label>
            <input
              type="number"
              value={assignedTo}
              onChange={(e) => setAssignedTo(e.target.value)}
              placeholder="Admin user ID"
              className="w-full bg-background border border-surface-light rounded-lg px-3 py-2 text-sm text-text placeholder:text-text-muted focus:outline-none focus:ring-1 focus:ring-primary"
            />
          </div>
        </div>

        <div className="flex gap-3">
          <button
            onClick={handleUpdateTicket}
            disabled={saving}
            className="bg-primary hover:bg-primary/90 disabled:opacity-50 text-white font-medium rounded-lg px-4 py-2 text-sm transition-colors"
          >
            {saving ? "Saving..." : "Update Ticket"}
          </button>
          <button
            onClick={handleGenerateSummary}
            disabled={summarizing}
            className="bg-purple-600 hover:bg-purple-700 disabled:opacity-50 text-white font-medium rounded-lg px-4 py-2 text-sm transition-colors"
          >
            {summarizing ? "Generating..." : "Generate AI Summary"}
          </button>
        </div>
      </div>

      {/* Admin Reply */}
      <div className="bg-surface rounded-xl border border-surface-light p-5 space-y-3">
        <h3 className="font-semibold text-sm">Reply as Admin</h3>
        <textarea
          value={replyBody}
          onChange={(e) => setReplyBody(e.target.value)}
          rows={4}
          className="w-full bg-background border border-surface-light rounded-lg px-3 py-2 text-sm text-text placeholder:text-text-muted focus:outline-none focus:ring-2 focus:ring-primary resize-y"
          placeholder="Type your reply..."
        />
        <button
          onClick={handleReply}
          disabled={replying || !replyBody.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"
        >
          {replying ? "Sending..." : "Send Reply"}
        </button>
      </div>

      {error && (
        <div className="bg-red-500/10 border border-red-500/20 rounded-lg p-3 text-red-400 text-sm">
          {error}
        </div>
      )}
    </div>
  );
}
