"use client";

import { useEffect, useState } from "react";
import { Button, Badge } from "@/components/ui";

interface Ticket {
  id: string;
  email: string;
  subject: string;
  description: string;
  status: string;
  priority: string;
  createdAt: string;
  familyName: string;
}

interface Response {
  id: string;
  message: string;
  createdAt: string;
}

export default function AdminSupport() {
  const [tickets, setTickets] = useState<Ticket[]>([]);
  const [loading, setLoading] = useState(true);
  const [statusFilter, setStatusFilter] = useState("all");
  const [selectedTicket, setSelectedTicket] = useState<Ticket | null>(null);
  const [responses, setResponses] = useState<Response[]>([]);
  const [replyText, setReplyText] = useState("");
  const [replying, setReplying] = useState(false);

  useEffect(() => {
    fetchTickets();
  }, [statusFilter]);

  useEffect(() => {
    if (selectedTicket) fetchResponses(selectedTicket.id);
  }, [selectedTicket]);

  const fetchTickets = async () => {
    try {
      const res = await fetch(`/api/admin/support?status=${statusFilter}`, { credentials: "include" });
      const data = await res.json();
      setTickets(data.tickets || []);
    } catch (err) {
      console.error("Failed to fetch tickets:", err);
    }
    setLoading(false);
  };

  const fetchResponses = async (ticketId: string) => {
    try {
      const res = await fetch(`/api/admin/support?ticketId=${ticketId}`, { credentials: "include" });
      const data = await res.json();
      setResponses(data.responses || []);
    } catch (err) {
      console.error("Failed to fetch responses:", err);
    }
  };

  const updateStatus = async (ticketId: string, status: string) => {
    try {
      await fetch("/api/admin/support", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({ ticketId, status }),
      });
      fetchTickets();
      if (selectedTicket?.id === ticketId) {
        setSelectedTicket(prev => prev ? { ...prev, status } : null);
      }
    } catch (err) {
      console.error("Failed to update ticket:", err);
    }
  };

  const handleReply = async () => {
    if (!replyText.trim() || !selectedTicket) return;
    setReplying(true);
    try {
      const res = await fetch("/api/admin/support", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({ ticketId: selectedTicket.id, message: replyText }),
      });
      if (res.ok) {
        setReplyText("");
        fetchResponses(selectedTicket.id);
        fetchTickets();
      }
    } catch (err) {
      console.error("Failed to send reply:", err);
    }
    setReplying(false);
  };

  const priorityVariant = (p: string): "rose" | "warning" | "default" =>
    p === "urgent" ? "rose" : p === "high" ? "warning" : "default";

  const statusVariant = (s: string): "rose" | "warning" | "default" =>
    s === "open" ? "rose" : s === "in_progress" ? "warning" : "default";

  const statusCounts = tickets.reduce((acc: Record<string, number>, t) => {
    acc[t.status] = (acc[t.status] || 0) + 1;
    return acc;
  }, {});

  function timeAgo(iso: string) {
    const diff = Date.now() - new Date(iso).getTime();
    const mins = Math.floor(diff / 60000);
    if (mins < 60) return `${mins}m ago`;
    const hrs = Math.floor(mins / 60);
    if (hrs < 24) return `${hrs}h ago`;
    return `${Math.floor(hrs / 24)}d ago`;
  }

  if (loading) return <div className="p-6 text-white">Loading...</div>;

  return (
    <div className="p-6 space-y-4">
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-2xl font-bold">Support</h1>
          <p className="text-gray-400">
            {tickets.length} tickets
            {statusCounts["open"] ? ` · ` : ""}
            {statusCounts["open"] ? <span className="text-rose-400">{statusCounts["open"]} open</span> : null}
          </p>
        </div>
      </div>

      {/* Status Filter */}
      <div className="flex gap-2 flex-wrap">
        {[
          { key: "all", label: "All" },
          { key: "open", label: `Open${statusCounts["open"] ? ` (${statusCounts["open"]})` : ""}` },
          { key: "in_progress", label: "In Progress" },
          { key: "resolved", label: "Resolved" },
          { key: "closed", label: "Closed" },
        ].map(({ key, label }) => (
          <Button
            key={key}
            size="sm"
            variant={statusFilter === key ? "primary" : "secondary"}
            onClick={() => setStatusFilter(key)}
          >
            {label}
          </Button>
        ))}
      </div>

      <div className="grid grid-cols-1 md:grid-cols-5 gap-4" style={{ height: "calc(100vh - 280px)", minHeight: "400px" }}>
        {/* Ticket List */}
        <div className="md:col-span-2 space-y-2 overflow-y-auto pr-1">
          {tickets.map((ticket) => (
            <div
              key={ticket.id}
              onClick={() => { setSelectedTicket(ticket); setResponses([]); }}
              className={`p-4 rounded-xl cursor-pointer transition-colors ${
                selectedTicket?.id === ticket.id
                  ? "bg-rose-500/20 border border-rose-500/50"
                  : "bg-gray-800 hover:bg-gray-750 border border-transparent"
              }`}
            >
              <div className="flex justify-between items-start mb-1.5">
                <Badge variant={priorityVariant(ticket.priority)}>{ticket.priority}</Badge>
                <Badge variant={statusVariant(ticket.status)}>{ticket.status.replace("_", " ")}</Badge>
              </div>
              <div className="font-medium text-sm">{ticket.subject}</div>
              <div className="text-xs text-gray-400 mt-0.5">{ticket.email}</div>
              {ticket.familyName && (
                <div className="text-xs text-gray-600 mt-0.5">Family: {ticket.familyName}</div>
              )}
              <div className="text-xs text-gray-600 mt-1.5">{timeAgo(ticket.createdAt)}</div>
            </div>
          ))}
          {tickets.length === 0 && (
            <div className="p-8 text-center text-gray-500">No tickets</div>
          )}
        </div>

        {/* Ticket Detail + Reply */}
        <div className="md:col-span-3 bg-gray-800 rounded-xl flex flex-col overflow-hidden">
          {selectedTicket ? (
            <>
              {/* Ticket header */}
              <div className="p-4 border-b border-gray-700">
                <div className="flex justify-between items-start">
                  <div>
                    <div className="font-semibold">{selectedTicket.subject}</div>
                    <div className="text-sm text-gray-400">{selectedTicket.email}</div>
                    {selectedTicket.familyName && (
                      <div className="text-xs text-gray-500 mt-0.5">Family: {selectedTicket.familyName}</div>
                    )}
                  </div>
                  <div className="flex gap-2 flex-shrink-0">
                    {selectedTicket.status === "open" && (
                      <Button size="sm" variant="secondary" onClick={() => updateStatus(selectedTicket.id, "in_progress")}>
                        Start
                      </Button>
                    )}
                    {selectedTicket.status === "in_progress" && (
                      <Button size="sm" onClick={() => updateStatus(selectedTicket.id, "resolved")}>
                        Resolve
                      </Button>
                    )}
                    {selectedTicket.status === "resolved" && (
                      <Button size="sm" variant="secondary" onClick={() => updateStatus(selectedTicket.id, "closed")}>
                        Close
                      </Button>
                    )}
                    {selectedTicket.status === "closed" && (
                      <Button size="sm" variant="secondary" onClick={() => updateStatus(selectedTicket.id, "open")}>
                        Reopen
                      </Button>
                    )}
                  </div>
                </div>
              </div>

              {/* Conversation thread */}
              <div className="flex-1 overflow-y-auto p-4 space-y-3">
                {/* Original message */}
                <div className="bg-gray-700 rounded-xl p-3">
                  <div className="text-xs text-gray-500 mb-1.5 flex justify-between">
                    <span>{selectedTicket.email}</span>
                    <span>{timeAgo(selectedTicket.createdAt)}</span>
                  </div>
                  <div className="text-sm whitespace-pre-wrap">{selectedTicket.description}</div>
                </div>

                {/* Admin responses */}
                {responses.map((r) => (
                  <div key={r.id} className="bg-rose-500/15 border border-rose-500/20 rounded-xl p-3 ml-6">
                    <div className="text-xs text-gray-500 mb-1.5 flex justify-between">
                      <span className="text-rose-400">Admin</span>
                      <span>{timeAgo(r.createdAt)}</span>
                    </div>
                    <div className="text-sm whitespace-pre-wrap">{r.message}</div>
                  </div>
                ))}
              </div>

              {/* Reply box */}
              {selectedTicket.status !== "closed" && (
                <div className="p-3 border-t border-gray-700">
                  <textarea
                    value={replyText}
                    onChange={(e) => setReplyText(e.target.value)}
                    placeholder="Type your reply…"
                    rows={3}
                    className="w-full bg-gray-700 text-white text-sm rounded-lg px-3 py-2 resize-none outline-none focus:ring-1 focus:ring-rose-500 placeholder-gray-500"
                    onKeyDown={(e) => {
                      if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) handleReply();
                    }}
                  />
                  <div className="flex justify-between items-center mt-2">
                    <span className="text-xs text-gray-600">Cmd+Enter to send</span>
                    <Button size="sm" onClick={handleReply} disabled={!replyText.trim() || replying}>
                      {replying ? "Sending…" : "Send Reply"}
                    </Button>
                  </div>
                </div>
              )}
            </>
          ) : (
            <div className="flex-1 flex items-center justify-center text-gray-600">
              Select a ticket to view the conversation
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
