"use client";

import { useState, useEffect } from "react";
import dynamic from "next/dynamic";
import { useTranslations } from "next-intl";
import { customInstance } from "@/config/axios";
import deleteAnimation from "@/public/animations/delete.json";

const Lottie = dynamic(() => import("lottie-react"), { ssr: false });

// API base URL for constructing image URLs
const API_BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL || '';

// Helper function to get full image URL
const getImageUrl = (avatar: string | null | undefined): string | null => {
  if (!avatar || typeof avatar !== 'string') return null;
  // If already a full URL, return as-is
  if (avatar.startsWith('http://') || avatar.startsWith('https://')) {
    return avatar;
  }
  // Construct full URL using API base URL
  return `${API_BASE_URL}/uploads/${avatar}`;
};

// Avatar component with error handling
const UserAvatar = ({
  avatar,
  name,
  size = 40
}: {
  avatar: string | null | undefined;
  name: string;
  size?: number;
}) => {
  const [imageError, setImageError] = useState(false);
  const [imageSrc, setImageSrc] = useState<string | null>(null);

  useEffect(() => {
    // Reset error state when avatar changes
    setImageError(false);
    setImageSrc(getImageUrl(avatar));
  }, [avatar]);

  const initial = name?.charAt(0)?.toUpperCase() || 'U';

  if (!imageSrc || imageError) {
    return (
      <div
        className="rounded-full bg-gray-200 flex items-center justify-center flex-shrink-0"
        style={{ width: size, height: size }}
      >
        <span className="text-gray-500 font-medium" style={{ fontSize: size * 0.35 }}>
          {initial}
        </span>
      </div>
    );
  }

  return (
    <img
      src={imageSrc}
      alt={name}
      width={size}
      height={size}
      className="rounded-full object-cover flex-shrink-0"
      style={{ width: size, height: size }}
      onError={() => setImageError(true)}
    />
  );
};

interface SupportTicket {
  uuid: string;
  ticket_number: string;
  user: {
    uuid: string;
    username: string;
    email: string;
    avatar: string | null;
  } | null;
  email: string;
  subject: string;
  message: string;
  status: "open" | "in_progress" | "resolved" | "closed";
  priority: string;
  created_at: string;
  resolved_at: string | null;
}

export default function AdminSupport() {
  const t = useTranslations();
  const [searchQuery, setSearchQuery] = useState("");
  const [sortBy, setSortBy] = useState("");
  const [statusFilter, setStatusFilter] = useState("");
  const [tickets, setTickets] = useState<SupportTicket[]>([]);
  const [loading, setLoading] = useState(true);
  const [deleteModalOpen, setDeleteModalOpen] = useState(false);
  const [ticketToDelete, setTicketToDelete] = useState<SupportTicket | null>(null);
  const [resolvingTicket, setResolvingTicket] = useState<string | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [totalCount, setTotalCount] = useState(0);
  const [viewModalOpen, setViewModalOpen] = useState(false);
  const [selectedTicket, setSelectedTicket] = useState<SupportTicket | null>(null);

  const handleViewClick = (ticket: SupportTicket) => {
    setSelectedTicket(ticket);
    setViewModalOpen(true);
  };

  const truncateText = (text: string, maxLength: number = 50) => {
    if (!text) return '-';
    if (text.length <= maxLength) return text;
    return text.substring(0, maxLength) + '...';
  };

  const fetchTickets = async () => {
    try {
      setLoading(true);
      const response = await customInstance<{
        data: {
          tickets: SupportTicket[];
          total_count: number;
          page: number;
          limit: number;
          total_pages: number;
        };
      }>({
        url: '/v1/support-tickets',
        method: 'GET',
        params: {
          page: currentPage,
          limit: 50,
          search: searchQuery || undefined,
          sort_field: sortBy || 'created_at',
          sort_direction: 'DESC',
          ...(statusFilter && { status: statusFilter }),
        },
      });
      setTickets(response.data.tickets || []);
      setTotalCount(response.data.total_count || 0);
      setTotalPages(response.data.total_pages || 1);
    } catch (error) {
      console.error('Error fetching support tickets:', error);
      setTickets([]);
    } finally {
      setLoading(false);
    }
  };

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

  useEffect(() => {
    const delayDebounceFn = setTimeout(() => {
      if (currentPage === 1) {
        fetchTickets();
      } else {
        setCurrentPage(1);
      }
    }, 500);

    return () => clearTimeout(delayDebounceFn);
  }, [searchQuery]);

  const formatDate = (dateString: string) => {
    if (!dateString) return '-';
    return new Date(dateString).toLocaleString('en-US', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    }).replace(',', '');
  };

  const getStatusDisplay = (status: string) => {
    switch (status) {
      case 'resolved':
        return t("admin.support.resolved");
      case 'in_progress':
        return t("admin.support.inProgress");
      case 'open':
        return t("admin.support.open");
      case 'closed':
        return t("admin.support.closed");
      default:
        return status;
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'resolved':
      case 'closed':
        return {
          bg: 'bg-green-50',
          text: 'text-green-600',
          dot: 'bg-green-500'
        };
      case 'in_progress':
        return {
          bg: 'bg-orange-50',
          text: 'text-orange-500',
          dot: 'bg-orange-500'
        };
      case 'open':
      default:
        return {
          bg: 'bg-blue-50',
          text: 'text-blue-500',
          dot: 'bg-blue-500'
        };
    }
  };

  const handleDeleteClick = (ticket: SupportTicket) => {
    setTicketToDelete(ticket);
    setDeleteModalOpen(true);
  };

  const handleConfirmDelete = async () => {
    if (!ticketToDelete) return;

    try {
      await customInstance({
        url: `/v1/support-tickets/${ticketToDelete.uuid}`,
        method: 'DELETE',
      });
      setDeleteModalOpen(false);
      setTicketToDelete(null);
      fetchTickets();
    } catch (error) {
      console.error('Error deleting ticket:', error);
    }
  };

  const handleCancelDelete = () => {
    setDeleteModalOpen(false);
    setTicketToDelete(null);
  };

  const handleMarkAsResolved = async (ticket: SupportTicket) => {
    try {
      setResolvingTicket(ticket.uuid);
      await customInstance({
        url: `/v1/support-tickets/${ticket.uuid}/status`,
        method: 'PATCH',
        data: {
          status: 'resolved',
        },
      });
      fetchTickets();
    } catch (error) {
      console.error('Error resolving ticket:', error);
    } finally {
      setResolvingTicket(null);
    }
  };

  const renderPagination = () => {
    const pages: (number | string)[] = [];

    if (totalPages <= 7) {
      for (let i = 1; i <= totalPages; i++) {
        pages.push(i);
      }
    } else {
      if (currentPage <= 3) {
        pages.push(1, 2, 3, '...', totalPages - 1, totalPages);
      } else if (currentPage >= totalPages - 2) {
        pages.push(1, 2, '...', totalPages - 2, totalPages - 1, totalPages);
      } else {
        pages.push(1, '...', currentPage - 1, currentPage, currentPage + 1, '...', totalPages);
      }
    }

    return pages.map((page, index) => (
      typeof page === 'number' ? (
        <button
          key={index}
          onClick={() => setCurrentPage(page)}
          className={`w-8 h-8 rounded-lg text-sm font-medium cursor-pointer ${
            currentPage === page
              ? 'bg-gray-100 text-gray-900'
              : 'text-gray-600 hover:bg-gray-50'
          }`}
        >
          {page}
        </button>
      ) : (
        <span key={index} className="px-2 text-gray-400">{page}</span>
      )
    ));
  };

  if (loading && tickets.length === 0) {
    return (
      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="flex items-center justify-center h-64">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-[#3B9EC9]"></div>
        </div>
      </main>
    );
  }

  return (
    <>
      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Support Table Card */}
        <div className="bg-white rounded-xl border border-gray-200 shadow-sm">
          {/* Table Header */}
          <div className="p-5 border-b border-gray-200">
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
              <h3 className="text-lg font-semibold text-gray-900">
                {t("admin.support.title")}
                {totalCount > 0 && (
                  <span className="ml-2 text-sm font-normal text-gray-500">
                    ({totalCount} {totalCount === 1 ? 'ticket' : 'tickets'})
                  </span>
                )}
              </h3>
              <div className="flex flex-wrap items-center gap-2">
                {/* Search */}
                <div className="relative flex-1 sm:flex-none">
                  <svg className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                  </svg>
                  <input
                    type="text"
                    placeholder={t("admin.common.search")}
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    className="pl-9 pr-4 py-2 w-full sm:w-48 border border-gray-200 rounded-full text-sm focus:outline-none focus:ring-2 focus:ring-[#3B9EC9]"
                  />
                </div>

                {/* Sort By */}
                <select
                  value={sortBy}
                  onChange={(e) => setSortBy(e.target.value)}
                  className="px-4 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] min-w-[120px] cursor-pointer"
                >
                  <option value="">{t("admin.common.sortBy")}</option>
                  <option value="created_at">{t("admin.support.created")}</option>
                  <option value="status">{t("admin.support.status")}</option>
                </select>

                {/* Status Filter */}
                <select
                  value={statusFilter}
                  onChange={(e) => setStatusFilter(e.target.value)}
                  className="px-4 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] min-w-[140px] cursor-pointer"
                >
                  <option value="">{t("admin.support.allStatuses")}</option>
                  <option value="open">{t("admin.support.open")}</option>
                  <option value="resolved">{t("admin.support.resolved")}</option>
                </select>
              </div>
            </div>
          </div>

          {/* Table */}
          <div className="mx-5 mb-5 mt-5 border border-gray-300 rounded-lg overflow-hidden">
            <div className="overflow-x-auto">
            <table className="w-full border-collapse min-w-[700px]">
              <thead>
                <tr className="bg-gray-50">
                  <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-b border-r border-gray-300">{t("admin.support.user")}</th>
                  <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-b border-r border-gray-300">{t("admin.support.ticket")}</th>
                  <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-b border-r border-gray-300">{t("admin.support.description")}</th>
                  <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-b border-r border-gray-300">{t("admin.support.created")}</th>
                  <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-b border-r border-gray-300">{t("admin.support.status")}</th>
                  <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-b border-gray-300">{t("admin.support.action")}</th>
                </tr>
              </thead>
              <tbody>
                {tickets.length === 0 ? (
                  <tr>
                    <td colSpan={6} className="px-5 py-8 text-center text-gray-500">
                      {t("admin.common.noTicketsFound")}
                    </td>
                  </tr>
                ) : (
                  tickets.map((ticket, index) => {
                    const statusColor = getStatusColor(ticket.status);
                    return (
                      <tr key={ticket.uuid} className="hover:bg-gray-50/50 transition">
                        <td className={`px-5 py-4 border-r border-gray-300 ${index !== tickets.length - 1 ? 'border-b border-gray-300' : ''}`}>
                          <div className="flex items-center gap-3">
                            <UserAvatar
                              avatar={ticket.user?.avatar}
                              name={ticket.user?.username || ticket.email}
                              size={40}
                            />
                            <div>
                              <p className="text-sm font-medium text-gray-900">{ticket.ticket_number}</p>
                              <p className="text-xs text-gray-500">{ticket.user?.email || ticket.email}</p>
                            </div>
                          </div>
                        </td>
                        <td className={`px-5 py-4 text-sm text-gray-600 border-r border-gray-300 ${index !== tickets.length - 1 ? 'border-b border-gray-300' : ''}`}>
                          {ticket.subject || '-'}
                        </td>
                        <td className={`px-5 py-4 text-sm text-gray-600 border-r border-gray-300 max-w-xs ${index !== tickets.length - 1 ? 'border-b border-gray-300' : ''}`}>
                          <span title={ticket.message}>{truncateText(ticket.message, 40)}</span>
                        </td>
                        <td className={`px-5 py-4 text-sm text-gray-600 border-r border-gray-300 ${index !== tickets.length - 1 ? 'border-b border-gray-300' : ''}`}>
                          {formatDate(ticket.created_at)}
                        </td>
                        <td className={`px-5 py-4 border-r border-gray-300 ${index !== tickets.length - 1 ? 'border-b border-gray-300' : ''}`}>
                          <span className={`inline-flex items-center gap-1.5 px-3 py-1 text-xs font-medium rounded-full ${statusColor.bg} ${statusColor.text}`}>
                            <span className={`w-1.5 h-1.5 rounded-full ${statusColor.dot}`}></span>
                            {getStatusDisplay(ticket.status)}
                          </span>
                        </td>
                        <td className={`px-5 py-4 ${index !== tickets.length - 1 ? 'border-b border-gray-300' : ''}`}>
                          <div className="flex items-center gap-2">
                            {/* View Button */}
                            <button
                              onClick={() => handleViewClick(ticket)}
                              className="w-9 h-9 rounded-lg bg-blue-50 flex items-center justify-center text-blue-400 hover:bg-blue-100 hover:text-blue-600 transition cursor-pointer"
                              title={t("admin.common.view")}
                            >
                              <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                                <path strokeLinecap="round" strokeLinejoin="round" d="M2.036 12.322a1.012 1.012 0 010-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178z" />
                                <path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                              </svg>
                            </button>
                            {/* Resolve Button */}
                            {(ticket.status === "in_progress" || ticket.status === "open") && (
                              <button
                                onClick={() => handleMarkAsResolved(ticket)}
                                disabled={resolvingTicket === ticket.uuid}
                                className="w-9 h-9 rounded-lg bg-green-50 flex items-center justify-center text-green-400 hover:bg-green-100 hover:text-green-600 transition disabled:opacity-50 cursor-pointer"
                                title={t("admin.support.markResolved")}
                              >
                                {resolvingTicket === ticket.uuid ? (
                                  <div className="w-4 h-4 border-2 border-green-400 border-t-transparent rounded-full animate-spin"></div>
                                ) : (
                                  <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                                    <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
                                  </svg>
                                )}
                              </button>
                            )}
                            {/* Delete Button */}
                            <button
                              onClick={() => handleDeleteClick(ticket)}
                              className="w-9 h-9 rounded-lg bg-red-50 flex items-center justify-center text-red-400 hover:bg-red-100 hover:text-red-600 transition cursor-pointer"
                              title={t("admin.common.delete")}
                            >
                              <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                                <path strokeLinecap="round" strokeLinejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                              </svg>
                            </button>
                          </div>
                        </td>
                      </tr>
                    );
                  })
                )}
              </tbody>
            </table>
            </div>
          </div>

          {/* Pagination */}


          {totalPages > 1 && (


          <div className="px-5 py-4 border-t border-gray-200 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
            <button
              onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
              disabled={currentPage === 1}
              className="flex items-center gap-2 px-4 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 hover:bg-gray-50 transition disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
            >
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
              </svg>
              {t("admin.common.previous")}
            </button>

            <div className="flex items-center gap-1">
              {renderPagination()}
            </div>

            <button
              onClick={() => setCurrentPage(prev => Math.min(totalPages, prev + 1))}
              disabled={currentPage === totalPages}
              className="flex items-center gap-2 px-4 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 hover:bg-gray-50 transition disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
            >
              {t("admin.common.next")}
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
              </svg>
            </button>
          </div>
          )}
        </div>
      </main>

      {/* Delete Confirmation Modal */}
      {deleteModalOpen && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center"
          style={{ animation: 'fadeIn 0.2s ease-out' }}
        >
          <style dangerouslySetInnerHTML={{ __html: `
            @keyframes fadeIn {
              from { opacity: 0; }
              to { opacity: 1; }
            }
            @keyframes scaleIn {
              from { opacity: 0; transform: scale(0.9) translateY(10px); }
              to { opacity: 1; transform: scale(1) translateY(0); }
            }
          `}} />

          {/* Backdrop */}
          <div
            className="absolute inset-0 bg-black/30"
            style={{ animation: 'fadeIn 0.2s ease-out' }}
            onClick={handleCancelDelete}
          ></div>

          {/* Modal */}
          <div
            className="relative bg-white rounded-2xl shadow-xl w-full max-w-md mx-4 p-8 pt-12"
            style={{ animation: 'scaleIn 0.3s ease-out' }}
          >
            {/* Close button */}
            <button
              onClick={handleCancelDelete}
              className="absolute top-4 right-4 text-gray-400 hover:text-gray-600 transition cursor-pointer"
            >
              <svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>

            {/* Icon - Lottie Animation */}
            <div className="flex justify-center mb-6">
              <div className="w-36 h-36">
                <Lottie
                  animationData={deleteAnimation}
                  loop={false}
                  autoplay={true}
                />
              </div>
            </div>

            {/* Content */}
            <div className="text-center mb-8">
              <h3 className="text-2xl font-semibold text-[#E05A5A] mb-3">{t("admin.modals.removeTicket")}</h3>
              <p className="text-gray-500 text-lg">
                {t("admin.modals.removeTicketConfirm")}
              </p>
            </div>

            {/* Actions */}
            <div className="flex gap-4 justify-center">
              <button
                onClick={handleCancelDelete}
                className="px-10 py-3 border border-gray-300 rounded-full text-gray-600 font-medium hover:bg-gray-50 transition cursor-pointer"
              >
                {t("admin.modals.close")}
              </button>
              <button
                onClick={handleConfirmDelete}
                className="px-10 py-3 bg-[#E05A5A] rounded-full text-white font-medium hover:bg-[#D04A4A] transition cursor-pointer"
              >
                {t("admin.modals.remove")}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* View Ticket Modal */}
      {viewModalOpen && selectedTicket && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center"
          style={{ animation: 'fadeIn 0.2s ease-out' }}
        >
          {/* Backdrop */}
          <div
            className="absolute inset-0 bg-black/30"
            onClick={() => setViewModalOpen(false)}
          ></div>

          {/* Modal */}
          <div
            className="relative bg-white rounded-2xl shadow-xl w-full max-w-2xl mx-4 flex flex-col max-h-[90vh]"
            style={{ animation: 'scaleIn 0.3s ease-out' }}
          >
            {/* Header */}
            <div className="flex items-start justify-between px-8 pt-8 pb-4 flex-shrink-0">
              <div>
                <h3 className="text-xl font-semibold text-gray-900 mb-1">{t("admin.support.ticketDetails")}</h3>
                <p className="text-sm text-gray-500">{selectedTicket.ticket_number}</p>
              </div>
              {/* Close button */}
              <button
                onClick={() => setViewModalOpen(false)}
                className="text-gray-400 hover:text-gray-600 transition cursor-pointer flex-shrink-0 ml-4"
              >
                <svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>

            {/* Scrollable Content */}
            <div className="overflow-y-auto flex-1 px-8 pb-4">
            <div className="space-y-4">
              {/* User Info */}
              <div className="flex items-center gap-3 p-4 bg-gray-50 rounded-lg">
                <UserAvatar
                  avatar={selectedTicket.user?.avatar}
                  name={selectedTicket.user?.username || selectedTicket.email}
                  size={48}
                />
                <div>
                  <p className="text-sm font-medium text-gray-900">{selectedTicket.user?.username || t("admin.common.guestUser")}</p>
                  <p className="text-sm text-gray-500">{selectedTicket.user?.email || selectedTicket.email}</p>
                </div>
                <div className="ml-auto">
                  {(() => {
                    const statusColor = getStatusColor(selectedTicket.status);
                    return (
                      <span className={`inline-flex items-center gap-1.5 px-3 py-1 text-xs font-medium rounded-full ${statusColor.bg} ${statusColor.text}`}>
                        <span className={`w-1.5 h-1.5 rounded-full ${statusColor.dot}`}></span>
                        {getStatusDisplay(selectedTicket.status)}
                      </span>
                    );
                  })()}
                </div>
              </div>

              {/* Subject */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">{t("admin.support.subject")}</label>
                <p className="text-sm text-gray-900 p-3 bg-gray-50 rounded-lg">{selectedTicket.subject}</p>
              </div>

              {/* Message */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">{t("admin.support.message")}</label>
                <p className="text-sm text-gray-900 p-3 bg-gray-50 rounded-lg whitespace-pre-wrap min-h-[100px]">{selectedTicket.message}</p>
              </div>

              {/* Dates */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">{t("admin.support.created")}</label>
                  <p className="text-sm text-gray-600">{formatDate(selectedTicket.created_at)}</p>
                </div>
                {selectedTicket.resolved_at && (
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">{t("admin.support.resolvedAt")}</label>
                    <p className="text-sm text-gray-600">{formatDate(selectedTicket.resolved_at)}</p>
                  </div>
                )}
              </div>
            </div>
            </div>

            {/* Actions */}
            <div className="flex gap-3 justify-end px-8 pb-8 pt-4 border-t border-gray-200 flex-shrink-0">
              {(selectedTicket.status === "in_progress" || selectedTicket.status === "open") && (
                <button
                  onClick={() => {
                    handleMarkAsResolved(selectedTicket);
                    setViewModalOpen(false);
                  }}
                  className="px-6 py-2.5 bg-green-500 rounded-full text-white font-medium hover:bg-green-600 transition cursor-pointer"
                >
                  {t("admin.support.markResolved")}
                </button>
              )}
              <button
                onClick={() => setViewModalOpen(false)}
                className="px-6 py-2.5 border border-gray-300 rounded-full text-gray-600 font-medium hover:bg-gray-50 transition cursor-pointer"
              >
                {t("admin.modals.close")}
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
