"use client";

import { useState, useEffect } from "react";
import {
  Search,
  Filter,
  RefreshCw,
  ChevronLeft,
  ChevronRight,
  AlertTriangle,
  Clock,
  CheckCircle,
  XCircle,
  Inbox,
  MessageSquare,
  DollarSign,
  Wrench,
  Lightbulb,
  HelpCircle,
  X,
  Send,
  User,
  Headphones,
} from "lucide-react";

interface Ticket {
  id: string;
  userId: string;
  subject: string;
  category: "BILLING" | "TECHNICAL" | "FEATURE_REQUEST" | "OTHER";
  priority: "LOW" | "NORMAL" | "URGENT";
  message: string;
  status: "OPEN" | "IN_PROGRESS" | "RESOLVED" | "CLOSED";
  attachments: string[] | null;
  resolvedAt: string | null;
  resolvedBy: string | null;
  resolution: string | null;
  createdAt: string;
  updatedAt: string;
  user: {
    id: string;
    email: string;
    name: string | null;
    companyName: string | null;
  };
}

interface Metrics {
  totalOpen: number;
  totalInProgress: number;
  totalResolved: number;
  totalClosed: number;
  avgResolutionTimeHours: number;
  ticketsByCategory: Record<string, number>;
  ticketsByPriority: Record<string, number>;
  urgentTickets: number;
}

interface Filters {
  status: string;
  priority: string;
  category: string;
  search: string;
}

interface User {
  id: string;
  role: string;
}

interface TicketMessage {
  id: string;
  ticketId: string;
  senderId: string;
  senderType: "USER" | "STAFF";
  message: string;
  attachments: string[] | null;
  isRead: boolean;
  readAt: string | null;
  createdAt: string;
  senderName?: string;
  senderEmail?: string;
}

const CATEGORY_CONFIG = {
  BILLING: {
    icon: DollarSign,
    label: "Billing",
    color: "text-blue-600 bg-blue-50",
  },
  TECHNICAL: {
    icon: Wrench,
    label: "Technical",
    color: "text-purple-600 bg-purple-50",
  },
  FEATURE_REQUEST: {
    icon: Lightbulb,
    label: "Feature Request",
    color: "text-yellow-600 bg-yellow-50",
  },
  OTHER: {
    icon: HelpCircle,
    label: "Other",
    color: "text-gray-600 bg-gray-100",
  },
};

const STATUS_CONFIG = {
  OPEN: {
    icon: Inbox,
    label: "Open",
    color: "text-blue-700 bg-blue-50 border-blue-200",
  },
  IN_PROGRESS: {
    icon: Clock,
    label: "In Progress",
    color: "text-yellow-700 bg-yellow-50 border-yellow-200",
  },
  RESOLVED: {
    icon: CheckCircle,
    label: "Resolved",
    color: "text-green-700 bg-green-50 border-green-200",
  },
  CLOSED: {
    icon: XCircle,
    label: "Closed",
    color: "text-gray-700 bg-gray-100 border-gray-200",
  },
};

const PRIORITY_CONFIG = {
  LOW: { label: "Low", color: "text-gray-600 bg-gray-100" },
  NORMAL: { label: "Normal", color: "text-blue-600 bg-blue-50" },
  URGENT: { label: "Urgent", color: "text-red-600 bg-red-50" },
};

export default function SupportTicketsDashboard({ user }: { user: User }) {
  const [tickets, setTickets] = useState<Ticket[]>([]);
  const [metrics, setMetrics] = useState<Metrics | null>(null);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [total, setTotal] = useState(0);
  const [selectedTicket, setSelectedTicket] = useState<Ticket | null>(null);
  const [showFilters, setShowFilters] = useState(false);
  const [filters, setFilters] = useState<Filters>({
    status: "",
    priority: "",
    category: "",
    search: "",
  });
  const [updating, setUpdating] = useState(false);
  const [resolution, setResolution] = useState("");

  // Message thread state
  const [messages, setMessages] = useState<TicketMessage[]>([]);
  const [loadingMessages, setLoadingMessages] = useState(false);
  const [replyText, setReplyText] = useState("");
  const [sendingReply, setSendingReply] = useState(false);

  const canManage = user.role === "ADMIN" || user.role === "SUPER_ADMIN";

  useEffect(() => {
    fetchMetrics();
  }, []);

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

  const fetchMetrics = async () => {
    try {
      const response = await fetch(
        "/api/staff/dashboard/support?action=metrics",
      );
      if (response.ok) {
        const data = await response.json();
        setMetrics(data);
      }
    } catch (error) {
      console.error("Failed to fetch metrics:", error);
    }
  };

  const fetchTickets = async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams({
        page: page.toString(),
        limit: "20",
      });

      if (filters.status) params.append("status", filters.status);
      if (filters.priority) params.append("priority", filters.priority);
      if (filters.category) params.append("category", filters.category);
      if (filters.search) params.append("search", filters.search);

      const response = await fetch(`/api/staff/dashboard/support?${params}`);
      if (response.ok) {
        const data = await response.json();
        setTickets(data.tickets);
        setTotalPages(data.totalPages);
        setTotal(data.total);
      }
    } catch (error) {
      console.error("Failed to fetch tickets:", error);
    } finally {
      setLoading(false);
    }
  };

  const updateTicketStatus = async (
    ticketId: string,
    status: string,
    resolutionText?: string,
  ) => {
    if (!canManage) return;

    setUpdating(true);
    try {
      const body: Record<string, string> = { status };
      if (resolutionText) body.resolution = resolutionText;

      const response = await fetch(`/api/staff/dashboard/support/${ticketId}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });

      if (response.ok) {
        const data = await response.json();
        setTickets((prev) =>
          prev.map((t) => (t.id === ticketId ? data.ticket : t)),
        );
        if (selectedTicket?.id === ticketId) {
          setSelectedTicket(data.ticket);
        }
        fetchMetrics();
        setResolution("");
      }
    } catch (error) {
      console.error("Failed to update ticket:", error);
    } finally {
      setUpdating(false);
    }
  };

  const updateTicketPriority = async (ticketId: string, priority: string) => {
    if (!canManage) return;

    try {
      const response = await fetch(`/api/staff/dashboard/support/${ticketId}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ priority }),
      });

      if (response.ok) {
        const data = await response.json();
        setTickets((prev) =>
          prev.map((t) => (t.id === ticketId ? data.ticket : t)),
        );
        if (selectedTicket?.id === ticketId) {
          setSelectedTicket(data.ticket);
        }
      }
    } catch (error) {
      console.error("Failed to update priority:", error);
    }
  };

  const clearFilters = () => {
    setFilters({ status: "", priority: "", category: "", search: "" });
    setPage(1);
  };

  const hasActiveFilters = Object.values(filters).some((v) => v !== "");

  // Fetch messages for a ticket
  const fetchMessages = async (ticketId: string) => {
    setLoadingMessages(true);
    try {
      const response = await fetch(
        `/api/staff/dashboard/support/${ticketId}/messages`,
      );
      if (response.ok) {
        const data = await response.json();
        setMessages(data.messages || []);
      }
    } catch (error) {
      console.error("Failed to fetch messages:", error);
    } finally {
      setLoadingMessages(false);
    }
  };

  // Send staff reply
  const sendStaffReply = async () => {
    if (!selectedTicket || !replyText.trim() || !canManage) return;

    setSendingReply(true);
    try {
      const response = await fetch(
        `/api/staff/dashboard/support/${selectedTicket.id}/messages`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ message: replyText }),
        },
      );

      if (response.ok) {
        const data = await response.json();
        setMessages((prev) => [...prev, data.message]);
        setReplyText("");
        // Auto-update ticket to IN_PROGRESS if it's OPEN
        if (selectedTicket.status === "OPEN") {
          updateTicketStatus(selectedTicket.id, "IN_PROGRESS");
        }
      }
    } catch (error) {
      console.error("Failed to send reply:", error);
    } finally {
      setSendingReply(false);
    }
  };

  // Open ticket and fetch messages
  const openTicketDetails = (ticket: Ticket) => {
    setSelectedTicket(ticket);
    setMessages([]);
    setReplyText("");
    fetchMessages(ticket.id);
  };

  // Close modal and reset state
  const closeTicketModal = () => {
    setSelectedTicket(null);
    setMessages([]);
    setReplyText("");
  };

  return (
    <div className="space-y-6">
      {/* Metrics Overview */}
      {metrics && (
        <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4">
          <MetricCard
            label="Open"
            value={metrics.totalOpen}
            icon={Inbox}
            color="blue"
            highlight={metrics.totalOpen > 0}
          />
          <MetricCard
            label="In Progress"
            value={metrics.totalInProgress}
            icon={Clock}
            color="yellow"
          />
          <MetricCard
            label="Resolved"
            value={metrics.totalResolved}
            icon={CheckCircle}
            color="green"
          />
          <MetricCard
            label="Urgent"
            value={metrics.urgentTickets}
            icon={AlertTriangle}
            color="red"
            highlight={metrics.urgentTickets > 0}
          />
          <MetricCard
            label="Avg Resolution"
            value={`${metrics.avgResolutionTimeHours}h`}
            icon={Clock}
            color="purple"
          />
          <MetricCard
            label="Total Closed"
            value={metrics.totalClosed}
            icon={XCircle}
            color="gray"
          />
        </div>
      )}

      {/* Toolbar */}
      <div className="flex flex-wrap items-center gap-3">
        {/* Search */}
        <div className="relative flex-1 min-w-[200px]">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
          <input
            type="text"
            placeholder="Search tickets..."
            value={filters.search}
            onChange={(e) => {
              setFilters({ ...filters, search: e.target.value });
              setPage(1);
            }}
            className="w-full pl-9 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green text-sm"
          />
        </div>

        {/* Quick Filters */}
        <div className="flex gap-2">
          <button
            onClick={() => {
              setFilters({
                ...filters,
                status: filters.status === "OPEN" ? "" : "OPEN",
              });
              setPage(1);
            }}
            className={`px-3 py-2 rounded-lg text-sm font-medium transition ${
              filters.status === "OPEN"
                ? "bg-blue-100 text-blue-700"
                : "bg-gray-100 text-gray-700 hover:bg-gray-200"
            }`}
          >
            Open
          </button>
          <button
            onClick={() => {
              setFilters({
                ...filters,
                priority: filters.priority === "URGENT" ? "" : "URGENT",
              });
              setPage(1);
            }}
            className={`px-3 py-2 rounded-lg text-sm font-medium transition ${
              filters.priority === "URGENT"
                ? "bg-red-100 text-red-700"
                : "bg-gray-100 text-gray-700 hover:bg-gray-200"
            }`}
          >
            Urgent
          </button>
        </div>

        {/* Filter toggle */}
        <button
          onClick={() => setShowFilters(!showFilters)}
          className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition ${
            showFilters || hasActiveFilters
              ? "bg-brand-green text-white"
              : "bg-gray-100 text-gray-700 hover:bg-gray-200"
          }`}
        >
          <Filter className="w-4 h-4" />
          More Filters
        </button>

        {/* Refresh */}
        <button
          onClick={() => {
            fetchTickets();
            fetchMetrics();
          }}
          disabled={loading}
          className="p-2 text-gray-600 hover:bg-gray-100 rounded-lg transition"
          title="Refresh"
        >
          <RefreshCw className={`w-4 h-4 ${loading ? "animate-spin" : ""}`} />
        </button>
      </div>

      {/* Filters Panel */}
      {showFilters && (
        <div className="bg-gray-50 rounded-lg p-4 border border-gray-200">
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
            <div>
              <label className="block text-xs font-medium text-gray-700 mb-1">
                Status
              </label>
              <select
                value={filters.status}
                onChange={(e) => {
                  setFilters({ ...filters, status: e.target.value });
                  setPage(1);
                }}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm"
              >
                <option value="">All Status</option>
                <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 font-medium text-gray-700 mb-1">
                Priority
              </label>
              <select
                value={filters.priority}
                onChange={(e) => {
                  setFilters({ ...filters, priority: e.target.value });
                  setPage(1);
                }}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm"
              >
                <option value="">All Priority</option>
                <option value="URGENT">Urgent</option>
                <option value="NORMAL">Normal</option>
                <option value="LOW">Low</option>
              </select>
            </div>

            <div>
              <label className="block text-xs font-medium text-gray-700 mb-1">
                Category
              </label>
              <select
                value={filters.category}
                onChange={(e) => {
                  setFilters({ ...filters, category: e.target.value });
                  setPage(1);
                }}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm"
              >
                <option value="">All Categories</option>
                <option value="BILLING">Billing</option>
                <option value="TECHNICAL">Technical</option>
                <option value="FEATURE_REQUEST">Feature Request</option>
                <option value="OTHER">Other</option>
              </select>
            </div>

            <div className="flex items-end">
              <button
                onClick={clearFilters}
                className="w-full px-3 py-2 text-sm text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-100 transition"
              >
                Clear All
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Results count */}
      <div className="text-sm text-gray-500">{total} tickets</div>

      {/* Tickets List */}
      <div className="bg-white border border-gray-200 rounded-xl overflow-hidden">
        <div className="divide-y divide-gray-100">
          {loading ? (
            <div className="p-12 text-center text-gray-500">
              <RefreshCw className="w-6 h-6 animate-spin mx-auto mb-2" />
              Loading tickets...
            </div>
          ) : tickets.length === 0 ? (
            <div className="p-12 text-center text-gray-500">
              <MessageSquare className="w-12 h-12 mx-auto mb-4 text-gray-300" />
              <p>No tickets found</p>
            </div>
          ) : (
            tickets.map((ticket) => {
              const categoryConfig = CATEGORY_CONFIG[ticket.category];
              const statusConfig = STATUS_CONFIG[ticket.status];
              const priorityConfig = PRIORITY_CONFIG[ticket.priority];
              const CategoryIcon = categoryConfig.icon;
              const StatusIcon = statusConfig.icon;

              return (
                <div
                  key={ticket.id}
                  onClick={() => openTicketDetails(ticket)}
                  className={`p-4 hover:bg-gray-50 cursor-pointer transition ${
                    ticket.priority === "URGENT"
                      ? "border-l-4 border-l-red-500"
                      : ""
                  }`}
                >
                  <div className="flex items-start gap-4">
                    <div
                      className={`p-2 rounded-lg shrink-0 ${categoryConfig.color}`}
                    >
                      <CategoryIcon className="w-5 h-5" />
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-start justify-between gap-2">
                        <div>
                          <h4 className="font-semibold text-brand-ink truncate">
                            {ticket.subject}
                          </h4>
                          <p className="text-sm text-gray-500">
                            {ticket.user.name || ticket.user.email}
                            {ticket.user.companyName &&
                              ` • ${ticket.user.companyName}`}
                          </p>
                        </div>
                        <div className="flex items-center gap-2 shrink-0">
                          <span
                            className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${priorityConfig.color}`}
                          >
                            {priorityConfig.label}
                          </span>
                          <span
                            className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium border ${statusConfig.color}`}
                          >
                            <StatusIcon className="w-3 h-3" />
                            {statusConfig.label}
                          </span>
                        </div>
                      </div>
                      <p className="text-sm text-gray-600 mt-1 line-clamp-2">
                        {ticket.message}
                      </p>
                      <p className="text-xs text-gray-400 mt-2">
                        #{ticket.id.slice(0, 8)} •{" "}
                        {new Date(ticket.createdAt).toLocaleString()}
                      </p>
                    </div>
                  </div>
                </div>
              );
            })
          )}
        </div>

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="flex items-center justify-between px-4 py-3 border-t border-gray-200">
            <p className="text-sm text-gray-500">
              Page {page} of {totalPages}
            </p>
            <div className="flex gap-2">
              <button
                onClick={() => setPage(page - 1)}
                disabled={page === 1}
                className="flex items-center gap-1 px-3 py-1.5 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <ChevronLeft className="w-4 h-4" />
                Previous
              </button>
              <button
                onClick={() => setPage(page + 1)}
                disabled={page === totalPages}
                className="flex items-center gap-1 px-3 py-1.5 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                Next
                <ChevronRight className="w-4 h-4" />
              </button>
            </div>
          </div>
        )}
      </div>

      {/* Ticket Detail Modal */}
      {selectedTicket && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl max-w-2xl w-full max-h-[90vh] overflow-hidden flex flex-col">
            {/* Header */}
            <div className="flex items-center justify-between px-6 py-4 border-b border-gray-200">
              <div>
                <h3 className="text-lg font-semibold text-brand-ink">
                  {selectedTicket.subject}
                </h3>
                <p className="text-sm text-gray-500">
                  #{selectedTicket.id.slice(0, 8)}
                </p>
              </div>
              <button
                onClick={closeTicketModal}
                className="p-1 text-gray-400 hover:text-gray-600 rounded"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            {/* Content */}
            <div className="flex-1 overflow-y-auto p-6 space-y-6">
              {/* Status & Meta */}
              <div className="flex flex-wrap gap-3">
                <span
                  className={`inline-flex items-center gap-1 px-3 py-1 rounded-full text-sm font-medium border ${
                    STATUS_CONFIG[selectedTicket.status].color
                  }`}
                >
                  {STATUS_CONFIG[selectedTicket.status].label}
                </span>
                <span
                  className={`inline-flex items-center gap-1 px-3 py-1 rounded-full text-sm font-medium ${
                    PRIORITY_CONFIG[selectedTicket.priority].color
                  }`}
                >
                  {PRIORITY_CONFIG[selectedTicket.priority].label} Priority
                </span>
                <span
                  className={`inline-flex items-center gap-1 px-3 py-1 rounded-full text-sm font-medium ${
                    CATEGORY_CONFIG[selectedTicket.category].color
                  }`}
                >
                  {CATEGORY_CONFIG[selectedTicket.category].label}
                </span>
              </div>

              {/* User Info */}
              <div className="bg-gray-50 rounded-lg p-4">
                <h4 className="text-sm font-medium text-gray-700 mb-2">
                  Customer
                </h4>
                <p className="font-medium text-brand-ink">
                  {selectedTicket.user.name || "Unknown"}
                </p>
                <p className="text-sm text-gray-500">
                  {selectedTicket.user.email}
                </p>
                {selectedTicket.user.companyName && (
                  <p className="text-sm text-gray-500">
                    {selectedTicket.user.companyName}
                  </p>
                )}
              </div>

              {/* Message Thread */}
              <div>
                <h4 className="text-sm font-medium text-gray-700 mb-2 flex items-center gap-2">
                  <MessageSquare className="w-4 h-4" />
                  Conversation ({messages.length} messages)
                </h4>
                <div className="bg-gray-50 rounded-lg p-4 max-h-72 overflow-y-auto space-y-3">
                  {loadingMessages ? (
                    <div className="text-center py-4">
                      <RefreshCw className="w-5 h-5 animate-spin mx-auto text-gray-400" />
                      <p className="text-sm text-gray-500 mt-2">
                        Loading messages...
                      </p>
                    </div>
                  ) : messages.length === 0 ? (
                    <p className="text-center text-gray-500 py-4">
                      No messages yet
                    </p>
                  ) : (
                    messages.map((msg) => (
                      <div
                        key={msg.id}
                        className={`p-3 rounded-lg ${
                          msg.senderType === "STAFF"
                            ? "bg-brand-green/10 border border-brand-green/20 ml-6"
                            : "bg-white border border-gray-200 mr-6"
                        }`}
                      >
                        <div className="flex items-center gap-2 mb-1.5">
                          <span
                            className={`p-1 rounded ${msg.senderType === "STAFF" ? "bg-brand-green/20" : "bg-gray-200"}`}
                          >
                            {msg.senderType === "STAFF" ? (
                              <Headphones className="w-3 h-3 text-brand-green" />
                            ) : (
                              <User className="w-3 h-3 text-gray-600" />
                            )}
                          </span>
                          <span className="text-xs font-semibold text-gray-700">
                            {msg.senderType === "STAFF"
                              ? msg.senderName || "Staff"
                              : msg.senderName || "Customer"}
                          </span>
                          <span className="text-xs text-gray-400">
                            {new Date(msg.createdAt).toLocaleString()}
                          </span>
                        </div>
                        <p className="text-sm text-gray-700 whitespace-pre-wrap">
                          {msg.message}
                        </p>
                      </div>
                    ))
                  )}
                </div>
              </div>

              {/* Staff Reply Input */}
              {canManage && selectedTicket.status !== "CLOSED" && (
                <div>
                  <h4 className="text-sm font-medium text-gray-700 mb-2">
                    Reply to Customer
                  </h4>
                  <div className="flex gap-2">
                    <textarea
                      value={replyText}
                      onChange={(e) => setReplyText(e.target.value)}
                      placeholder="Type your reply..."
                      className="flex-1 px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green resize-none"
                      rows={3}
                      onKeyDown={(e) => {
                        if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
                          e.preventDefault();
                          sendStaffReply();
                        }
                      }}
                    />
                  </div>
                  <div className="flex justify-between items-center mt-2">
                    <p className="text-xs text-gray-400">
                      Press Cmd/Ctrl + Enter to send
                    </p>
                    <button
                      onClick={sendStaffReply}
                      disabled={!replyText.trim() || sendingReply}
                      className="flex items-center gap-2 px-4 py-2 bg-brand-green text-white font-medium rounded-lg hover:bg-brand-greenHover transition disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      {sendingReply ? (
                        <RefreshCw className="w-4 h-4 animate-spin" />
                      ) : (
                        <Send className="w-4 h-4" />
                      )}
                      Send Reply
                    </button>
                  </div>
                </div>
              )}

              {/* Resolution */}
              {selectedTicket.resolution && (
                <div>
                  <h4 className="text-sm font-medium text-gray-700 mb-2">
                    Resolution
                  </h4>
                  <div className="bg-green-50 rounded-lg p-4">
                    <p className="text-green-700 whitespace-pre-wrap">
                      {selectedTicket.resolution}
                    </p>
                    {selectedTicket.resolvedAt && (
                      <p className="text-xs text-green-600 mt-2">
                        Resolved on{" "}
                        {new Date(selectedTicket.resolvedAt).toLocaleString()}
                      </p>
                    )}
                  </div>
                </div>
              )}

              {/* Timestamps */}
              <div className="text-sm text-gray-500 space-y-1">
                <p>
                  Created: {new Date(selectedTicket.createdAt).toLocaleString()}
                </p>
                <p>
                  Updated: {new Date(selectedTicket.updatedAt).toLocaleString()}
                </p>
              </div>
            </div>

            {/* Actions */}
            {canManage && selectedTicket.status !== "CLOSED" && (
              <div className="px-6 py-4 border-t border-gray-200 space-y-4">
                {/* Priority Update */}
                <div className="flex items-center gap-3">
                  <span className="text-sm text-gray-600">Priority:</span>
                  <div className="flex gap-2">
                    {(["LOW", "NORMAL", "URGENT"] as const).map((p) => (
                      <button
                        key={p}
                        onClick={() =>
                          updateTicketPriority(selectedTicket.id, p)
                        }
                        className={`px-3 py-1 text-sm rounded-lg transition ${
                          selectedTicket.priority === p
                            ? PRIORITY_CONFIG[p].color + " ring-2 ring-offset-1"
                            : "bg-gray-100 text-gray-600 hover:bg-gray-200"
                        }`}
                      >
                        {PRIORITY_CONFIG[p].label}
                      </button>
                    ))}
                  </div>
                </div>

                {/* Resolution Input */}
                {selectedTicket.status !== "RESOLVED" && (
                  <div>
                    <textarea
                      value={resolution}
                      onChange={(e) => setResolution(e.target.value)}
                      placeholder="Enter resolution notes..."
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green resize-none"
                      rows={3}
                    />
                  </div>
                )}

                {/* Status Buttons */}
                <div className="flex gap-3">
                  {selectedTicket.status === "OPEN" && (
                    <button
                      onClick={() =>
                        updateTicketStatus(selectedTicket.id, "IN_PROGRESS")
                      }
                      disabled={updating}
                      className="flex-1 px-4 py-2 bg-yellow-100 text-yellow-700 font-medium rounded-lg hover:bg-yellow-200 transition disabled:opacity-50"
                    >
                      Start Working
                    </button>
                  )}
                  {selectedTicket.status !== "RESOLVED" && (
                    <button
                      onClick={() =>
                        updateTicketStatus(
                          selectedTicket.id,
                          "RESOLVED",
                          resolution,
                        )
                      }
                      disabled={updating}
                      className="flex-1 px-4 py-2 bg-green-600 text-white font-medium rounded-lg hover:bg-green-700 transition disabled:opacity-50"
                    >
                      Resolve Ticket
                    </button>
                  )}
                  <button
                    onClick={() =>
                      updateTicketStatus(selectedTicket.id, "CLOSED")
                    }
                    disabled={updating}
                    className="px-4 py-2 bg-gray-100 text-gray-700 font-medium rounded-lg hover:bg-gray-200 transition disabled:opacity-50"
                  >
                    Close
                  </button>
                </div>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

function MetricCard({
  label,
  value,
  icon: Icon,
  color,
  highlight,
}: {
  label: string;
  value: number | string;
  icon: React.ComponentType<{ className?: string }>;
  color: "blue" | "yellow" | "green" | "red" | "purple" | "gray";
  highlight?: boolean;
}) {
  const colors = {
    blue: "bg-blue-50 text-blue-600",
    yellow: "bg-yellow-50 text-yellow-600",
    green: "bg-green-50 text-green-600",
    red: "bg-red-50 text-red-600",
    purple: "bg-purple-50 text-purple-600",
    gray: "bg-gray-50 text-gray-600",
  };

  return (
    <div
      className={`bg-white rounded-xl border p-4 ${
        highlight ? "border-red-300 ring-2 ring-red-100" : "border-gray-200"
      }`}
    >
      <div className="flex items-center gap-3">
        <div className={`p-2 rounded-lg ${colors[color]}`}>
          <Icon className="w-5 h-5" />
        </div>
        <div>
          <p className="text-xl font-bold text-brand-ink">{value}</p>
          <p className="text-xs text-gray-500">{label}</p>
        </div>
      </div>
    </div>
  );
}
