"use client";

import { useState, useEffect, useRef, useCallback } from "react";
import type { Lang } from "@/lib/config";
import type { Session } from "next-auth";
import { fetchWithCSRF } from "@/lib/csrf-client";
import {
  MessageSquare,
  Plus,
  ChevronLeft,
  Clock,
  CheckCircle,
  AlertCircle,
  Send,
  RefreshCw,
  X,
  Inbox,
  HelpCircle,
  DollarSign,
  Wrench,
  Lightbulb,
  ArrowUpCircle,
} from "lucide-react";

// Category configuration
const CATEGORIES = [
  {
    value: "BILLING",
    label: "Billing",
    labelAr: "الفواتير",
    icon: DollarSign,
    color: "bg-blue-100 text-blue-700",
  },
  {
    value: "TECHNICAL",
    label: "Technical",
    labelAr: "تقني",
    icon: Wrench,
    color: "bg-purple-100 text-purple-700",
  },
  {
    value: "FEATURE_REQUEST",
    label: "Feature Request",
    labelAr: "طلب ميزة",
    icon: Lightbulb,
    color: "bg-amber-100 text-amber-700",
  },
  {
    value: "OTHER",
    label: "Other",
    labelAr: "أخرى",
    icon: HelpCircle,
    color: "bg-slate-100 text-slate-700",
  },
] as const;

const PRIORITY_CONFIG = {
  LOW: { label: "Low", labelAr: "منخفضة", color: "text-gray-600 bg-gray-100" },
  NORMAL: {
    label: "Normal",
    labelAr: "عادية",
    color: "text-blue-600 bg-blue-100",
  },
  URGENT: {
    label: "Urgent",
    labelAr: "عاجلة",
    color: "text-red-600 bg-red-100",
  },
} as const;

const STATUS_CONFIG = {
  OPEN: {
    label: "Open",
    labelAr: "مفتوحة",
    icon: Inbox,
    color: "text-blue-700 bg-blue-50 border-blue-200",
  },
  IN_PROGRESS: {
    label: "In Progress",
    labelAr: "قيد التنفيذ",
    icon: Clock,
    color: "text-yellow-700 bg-yellow-50 border-yellow-200",
  },
  RESOLVED: {
    label: "Resolved",
    labelAr: "تم الحل",
    icon: CheckCircle,
    color: "text-green-700 bg-green-50 border-green-200",
  },
  CLOSED: {
    label: "Closed",
    labelAr: "مغلقة",
    icon: X,
    color: "text-gray-700 bg-gray-100 border-gray-200",
  },
} as const;

interface Ticket {
  id: string;
  subject: string;
  category: string;
  priority: string;
  status: string;
  message: string;
  createdAt: string;
  updatedAt: string;
  unreadCount?: number;
}

interface TicketMessage {
  id: string;
  senderId: string;
  senderType: "USER" | "STAFF";
  message: string;
  createdAt: string;
  senderName?: string;
}

interface SupportPanelProps {
  lang: Lang;
  session: Session;
}

type ViewMode = "list" | "create" | "conversation";

export default function SupportPanel({ lang, session }: SupportPanelProps) {
  const isAr = lang === "ar";
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // View state
  const [viewMode, setViewMode] = useState<ViewMode>("list");
  const [selectedTicket, setSelectedTicket] = useState<Ticket | null>(null);

  // Data state
  const [tickets, setTickets] = useState<Ticket[]>([]);
  const [messages, setMessages] = useState<TicketMessage[]>([]);

  // Loading states
  const [loading, setLoading] = useState(true);
  const [loadingMessages, setLoadingMessages] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [sending, setSending] = useState(false);

  // Form states
  const [newTicketForm, setNewTicketForm] = useState({
    subject: "",
    category: "TECHNICAL",
    priority: "NORMAL",
    message: "",
  });
  const [replyMessage, setReplyMessage] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  // Translations
  const t = {
    title: isAr ? "الدعم الفني" : "Support",
    subtitle: isAr ? "احصل على مساعدة من فريقنا" : "Get help from our team",
    newTicket: isAr ? "تذكرة جديدة" : "New Ticket",
    backToList: isAr ? "العودة للقائمة" : "Back to List",
    noTickets: isAr ? "لا توجد تذاكر بعد" : "No tickets yet",
    noTicketsDesc: isAr
      ? "أنشئ تذكرة للحصول على مساعدة من فريق الدعم"
      : "Create a ticket to get help from our support team",
    subject: isAr ? "الموضوع" : "Subject",
    subjectPlaceholder: isAr
      ? "اكتب موضوع التذكرة..."
      : "Enter ticket subject...",
    category: isAr ? "الفئة" : "Category",
    priority: isAr ? "الأولوية" : "Priority",
    message: isAr ? "الرسالة" : "Message",
    messagePlaceholder: isAr
      ? "اشرح مشكلتك بالتفصيل..."
      : "Describe your issue in detail...",
    submit: isAr ? "إرسال التذكرة" : "Submit Ticket",
    sendReply: isAr ? "إرسال" : "Send",
    replyPlaceholder: isAr ? "اكتب ردك هنا..." : "Type your reply here...",
    you: isAr ? "أنت" : "You",
    supportTeam: isAr ? "فريق الدعم" : "Support Team",
    created: isAr ? "تم الإنشاء" : "Created",
    lastUpdate: isAr ? "آخر تحديث" : "Last update",
    successCreated: isAr
      ? "تم إنشاء التذكرة بنجاح!"
      : "Ticket created successfully!",
    successSent: isAr ? "تم إرسال الرد!" : "Reply sent!",
    errorGeneric: isAr
      ? "حدث خطأ. حاول مرة أخرى."
      : "Something went wrong. Please try again.",
    ticketClosed: isAr ? "هذه التذكرة مغلقة" : "This ticket is closed",
    refresh: isAr ? "تحديث" : "Refresh",
  };

  // Fetch tickets
  const fetchTickets = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/support/tickets");
      if (res.ok) {
        const data = await res.json();
        setTickets(data.tickets || []);
      }
    } catch (err) {
      console.error("Failed to fetch tickets:", err);
    } finally {
      setLoading(false);
    }
  }, []);

  // Fetch ticket messages
  const fetchMessages = useCallback(async (ticketId: string) => {
    setLoadingMessages(true);
    try {
      const res = await fetch(`/api/support/tickets/${ticketId}`);
      if (res.ok) {
        const data = await res.json();
        setMessages(data.messages || []);
        // Update the selected ticket with fresh data
        if (data.ticket) {
          setSelectedTicket((prev) =>
            prev ? { ...prev, ...data.ticket } : null,
          );
        }
      }
    } catch (err) {
      console.error("Failed to fetch messages:", err);
    } finally {
      setLoadingMessages(false);
    }
  }, []);

  // Create new ticket
  const handleCreateTicket = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    setError(null);

    try {
      const res = await fetchWithCSRF("/api/support/tickets", {
        method: "POST",
        body: JSON.stringify(newTicketForm),
      });

      if (res.ok) {
        const data = await res.json();
        setTickets((prev) => [data.ticket, ...prev]);
        setNewTicketForm({
          subject: "",
          category: "TECHNICAL",
          priority: "NORMAL",
          message: "",
        });
        setSuccess(t.successCreated);
        setViewMode("list");
        setTimeout(() => setSuccess(null), 3000);
      } else {
        const err = await res.json();
        setError(err.error || t.errorGeneric);
      }
    } catch {
      setError(t.errorGeneric);
    } finally {
      setSubmitting(false);
    }
  };

  // Send reply
  const handleSendReply = async () => {
    if (!selectedTicket || !replyMessage.trim()) return;

    setSending(true);
    try {
      const res = await fetch(
        `/api/support/tickets/${selectedTicket.id}/messages`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ message: replyMessage }),
        },
      );

      if (res.ok) {
        const data = await res.json();
        setMessages((prev) => [...prev, data.message]);
        setReplyMessage("");
        // Scroll to bottom
        setTimeout(
          () => messagesEndRef.current?.scrollIntoView({ behavior: "smooth" }),
          100,
        );
      }
    } catch (err) {
      console.error("Failed to send reply:", err);
    } finally {
      setSending(false);
    }
  };

  // Open ticket conversation
  const openTicket = (ticket: Ticket) => {
    setSelectedTicket(ticket);
    setViewMode("conversation");
    fetchMessages(ticket.id);
  };

  // Go back to list
  const goBackToList = () => {
    setViewMode("list");
    setSelectedTicket(null);
    setMessages([]);
    fetchTickets(); // Refresh list
  };

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

  // Auto-refresh messages when viewing conversation
  useEffect(() => {
    if (viewMode === "conversation" && selectedTicket) {
      const interval = setInterval(
        () => fetchMessages(selectedTicket.id),
        30000,
      );
      return () => clearInterval(interval);
    }
  }, [viewMode, selectedTicket, fetchMessages]);

  // Format date
  const formatDate = (dateStr: string) => {
    const date = new Date(dateStr);
    return date.toLocaleDateString(isAr ? "ar-SA" : "en-US", {
      year: "numeric",
      month: "short",
      day: "numeric",
    });
  };

  const formatDateTime = (dateStr: string) => {
    const date = new Date(dateStr);
    return date.toLocaleString(isAr ? "ar-SA" : "en-US", {
      month: "short",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  return (
    <div className="space-y-6" dir={isAr ? "rtl" : "ltr"}>
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold text-slate-900">{t.title}</h2>
          <p className="text-slate-500 mt-1">{t.subtitle}</p>
        </div>
        {viewMode === "list" && (
          <div className="flex items-center gap-2">
            <button
              onClick={fetchTickets}
              disabled={loading}
              className="p-2.5 text-slate-500 hover:text-slate-700 hover:bg-slate-100 rounded-xl transition-colors"
              title={t.refresh}
            >
              <RefreshCw
                className={`w-5 h-5 ${loading ? "animate-spin" : ""}`}
              />
            </button>
            <button
              onClick={() => setViewMode("create")}
              className="flex items-center gap-2 px-4 py-2.5 bg-brand-green text-white rounded-xl font-semibold hover:bg-brand-greenHover transition-colors shadow-lg shadow-brand-green/25"
            >
              <Plus className="w-5 h-5" />
              {t.newTicket}
            </button>
          </div>
        )}
        {viewMode !== "list" && (
          <button
            onClick={goBackToList}
            className="flex items-center gap-2 px-4 py-2.5 bg-slate-100 text-slate-700 rounded-xl font-semibold hover:bg-slate-200 transition-colors"
          >
            <ChevronLeft className={`w-5 h-5 ${isAr ? "rotate-180" : ""}`} />
            {t.backToList}
          </button>
        )}
      </div>

      {/* Success/Error Messages */}
      {success && (
        <div className="p-4 bg-green-50 border border-green-200 rounded-xl text-green-700 flex items-center gap-3">
          <CheckCircle className="w-5 h-5 flex-shrink-0" />
          {success}
        </div>
      )}
      {error && (
        <div className="p-4 bg-red-50 border border-red-200 rounded-xl text-red-700 flex items-center gap-3">
          <AlertCircle className="w-5 h-5 flex-shrink-0" />
          {error}
        </div>
      )}

      {/* LIST VIEW */}
      {viewMode === "list" && (
        <div className="bg-white rounded-2xl border border-slate-200 overflow-hidden shadow-sm">
          {loading ? (
            <div className="p-12 text-center">
              <RefreshCw className="w-8 h-8 animate-spin mx-auto text-slate-400" />
              <p className="text-slate-500 mt-3">Loading tickets...</p>
            </div>
          ) : tickets.length === 0 ? (
            <div className="p-12 text-center">
              <div className="w-16 h-16 mx-auto bg-slate-100 rounded-2xl flex items-center justify-center mb-4">
                <MessageSquare className="w-8 h-8 text-slate-400" />
              </div>
              <p className="font-semibold text-slate-700 text-lg">
                {t.noTickets}
              </p>
              <p className="text-slate-500 text-sm mt-1 max-w-sm mx-auto">
                {t.noTicketsDesc}
              </p>
              <button
                onClick={() => setViewMode("create")}
                className="mt-6 px-6 py-2.5 bg-brand-green text-white rounded-xl font-semibold hover:bg-brand-greenHover transition-colors"
              >
                {t.newTicket}
              </button>
            </div>
          ) : (
            <div className="divide-y divide-slate-100">
              {tickets.map((ticket) => {
                const cat = CATEGORIES.find((c) => c.value === ticket.category);
                const status =
                  STATUS_CONFIG[ticket.status as keyof typeof STATUS_CONFIG];
                const StatusIcon = status?.icon || Inbox;
                const CatIcon = cat?.icon || HelpCircle;

                return (
                  <button
                    key={ticket.id}
                    onClick={() => openTicket(ticket)}
                    className="w-full p-4 sm:p-5 flex items-start gap-4 hover:bg-slate-50 transition-colors text-start"
                  >
                    <div
                      className={`p-2.5 rounded-xl flex-shrink-0 ${cat?.color || "bg-slate-100 text-slate-700"}`}
                    >
                      <CatIcon className="w-5 h-5" />
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 flex-wrap">
                        <h4 className="font-semibold text-slate-900 truncate">
                          {ticket.subject}
                        </h4>
                        {(ticket.unreadCount ?? 0) > 0 && (
                          <span className="px-2 py-0.5 bg-brand-green text-white text-xs font-bold rounded-full flex-shrink-0">
                            {ticket.unreadCount} {isAr ? "جديد" : "new"}
                          </span>
                        )}
                      </div>
                      <p className="text-sm text-slate-500 truncate mt-1">
                        {ticket.message}
                      </p>
                      <div className="flex items-center gap-3 mt-2 text-xs text-slate-400">
                        <span>
                          {t.created}: {formatDate(ticket.createdAt)}
                        </span>
                        <span className="hidden sm:inline">•</span>
                        <span className="hidden sm:inline">
                          #{ticket.id.slice(0, 8)}
                        </span>
                      </div>
                    </div>
                    <span
                      className={`px-3 py-1.5 rounded-lg text-xs font-medium border flex items-center gap-1.5 flex-shrink-0 ${status?.color}`}
                    >
                      <StatusIcon className="w-3.5 h-3.5" />
                      <span className="hidden sm:inline">
                        {isAr ? status?.labelAr : status?.label}
                      </span>
                    </span>
                  </button>
                );
              })}
            </div>
          )}
        </div>
      )}

      {/* CREATE TICKET VIEW */}
      {viewMode === "create" && (
        <form
          onSubmit={handleCreateTicket}
          className="bg-white rounded-2xl border border-slate-200 p-6 space-y-6 shadow-sm"
        >
          {/* Subject */}
          <div>
            <label className="block text-sm font-semibold text-slate-700 mb-2">
              {t.subject}
            </label>
            <input
              type="text"
              value={newTicketForm.subject}
              onChange={(e) =>
                setNewTicketForm((f) => ({ ...f, subject: e.target.value }))
              }
              placeholder={t.subjectPlaceholder}
              className="w-full px-4 py-3 border border-slate-200 rounded-xl focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green transition-colors"
              required
              minLength={3}
            />
          </div>

          {/* Category & Priority */}
          <div className="grid sm:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-semibold text-slate-700 mb-2">
                {t.category}
              </label>
              <select
                value={newTicketForm.category}
                onChange={(e) =>
                  setNewTicketForm((f) => ({ ...f, category: e.target.value }))
                }
                className="w-full px-4 py-3 border border-slate-200 rounded-xl focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green bg-white transition-colors"
              >
                {CATEGORIES.map((cat) => (
                  <option key={cat.value} value={cat.value}>
                    {isAr ? cat.labelAr : cat.label}
                  </option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-sm font-semibold text-slate-700 mb-2">
                {t.priority}
              </label>
              <select
                value={newTicketForm.priority}
                onChange={(e) =>
                  setNewTicketForm((f) => ({ ...f, priority: e.target.value }))
                }
                className="w-full px-4 py-3 border border-slate-200 rounded-xl focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green bg-white transition-colors"
              >
                {Object.entries(PRIORITY_CONFIG).map(([key, val]) => (
                  <option key={key} value={key}>
                    {isAr ? val.labelAr : val.label}
                  </option>
                ))}
              </select>
            </div>
          </div>

          {/* Message */}
          <div>
            <label className="block text-sm font-semibold text-slate-700 mb-2">
              {t.message}
            </label>
            <textarea
              value={newTicketForm.message}
              onChange={(e) =>
                setNewTicketForm((f) => ({ ...f, message: e.target.value }))
              }
              placeholder={t.messagePlaceholder}
              rows={6}
              className="w-full px-4 py-3 border border-slate-200 rounded-xl focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green resize-none transition-colors"
              required
              minLength={10}
            />
          </div>

          {/* Submit */}
          <button
            type="submit"
            disabled={submitting}
            className="w-full py-3.5 bg-brand-green text-white font-semibold rounded-xl hover:bg-brand-greenHover transition-colors disabled:opacity-50 disabled:cursor-not-allowed shadow-lg shadow-brand-green/25"
          >
            {submitting ? (
              <span className="flex items-center justify-center gap-2">
                <RefreshCw className="w-5 h-5 animate-spin" />
                {isAr ? "جاري الإرسال..." : "Submitting..."}
              </span>
            ) : (
              t.submit
            )}
          </button>
        </form>
      )}

      {/* CONVERSATION VIEW */}
      {viewMode === "conversation" && selectedTicket && (
        <div
          className="bg-white rounded-2xl border border-slate-200 overflow-hidden shadow-sm flex flex-col"
          style={{ height: "calc(100vh - 280px)", minHeight: "500px" }}
        >
          {/* Ticket Header */}
          <div className="p-4 sm:p-5 border-b border-slate-200 bg-gradient-to-r from-slate-50 to-white">
            <div className="flex items-start justify-between gap-4">
              <div className="min-w-0">
                <h3 className="font-bold text-slate-900 text-lg truncate">
                  {selectedTicket.subject}
                </h3>
                <p className="text-sm text-slate-500 mt-1">
                  #{selectedTicket.id.slice(0, 8)} • {t.lastUpdate}:{" "}
                  {formatDateTime(selectedTicket.updatedAt)}
                </p>
              </div>
              <div className="flex items-center gap-2 flex-shrink-0">
                {(() => {
                  const status =
                    STATUS_CONFIG[
                      selectedTicket.status as keyof typeof STATUS_CONFIG
                    ];
                  const StatusIcon = status?.icon || Inbox;
                  return (
                    <span
                      className={`px-3 py-1.5 rounded-lg text-xs font-medium border flex items-center gap-1.5 ${status?.color}`}
                    >
                      <StatusIcon className="w-3.5 h-3.5" />
                      {isAr ? status?.labelAr : status?.label}
                    </span>
                  );
                })()}
              </div>
            </div>
          </div>

          {/* Messages */}
          <div className="flex-1 overflow-y-auto p-4 sm:p-5 space-y-4 bg-slate-50/50">
            {loadingMessages ? (
              <div className="text-center py-12">
                <RefreshCw className="w-6 h-6 animate-spin mx-auto text-slate-400" />
                <p className="text-slate-500 mt-2 text-sm">
                  Loading messages...
                </p>
              </div>
            ) : messages.length === 0 ? (
              <div className="text-center py-12">
                <MessageSquare className="w-10 h-10 mx-auto text-slate-300" />
                <p className="text-slate-500 mt-2">No messages yet</p>
              </div>
            ) : (
              messages.map((msg) => (
                <div
                  key={msg.id}
                  className={`flex ${msg.senderType === "USER" ? (isAr ? "justify-start" : "justify-end") : isAr ? "justify-end" : "justify-start"}`}
                >
                  <div
                    className={`max-w-[85%] sm:max-w-[75%] p-4 rounded-2xl shadow-sm ${
                      msg.senderType === "USER"
                        ? "bg-brand-green text-white rounded-br-md"
                        : "bg-white text-slate-800 border border-slate-200 rounded-bl-md"
                    }`}
                  >
                    <p
                      className={`text-xs font-semibold mb-1.5 ${msg.senderType === "USER" ? "text-green-100" : "text-slate-500"}`}
                    >
                      {msg.senderType === "USER"
                        ? t.you
                        : msg.senderName || t.supportTeam}
                    </p>
                    <p className="whitespace-pre-wrap text-sm leading-relaxed">
                      {msg.message}
                    </p>
                    <p
                      className={`text-xs mt-2 ${msg.senderType === "USER" ? "text-green-100" : "text-slate-400"}`}
                    >
                      {formatDateTime(msg.createdAt)}
                    </p>
                  </div>
                </div>
              ))
            )}
            <div ref={messagesEndRef} />
          </div>

          {/* Reply Input */}
          {selectedTicket.status !== "CLOSED" ? (
            <div className="p-4 border-t border-slate-200 bg-white">
              <div className="flex gap-3">
                <input
                  type="text"
                  value={replyMessage}
                  onChange={(e) => setReplyMessage(e.target.value)}
                  placeholder={t.replyPlaceholder}
                  className="flex-1 px-4 py-3 border border-slate-200 rounded-xl focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green transition-colors"
                  onKeyDown={(e) => {
                    if (e.key === "Enter" && !e.shiftKey) {
                      e.preventDefault();
                      handleSendReply();
                    }
                  }}
                  disabled={sending}
                />
                <button
                  onClick={handleSendReply}
                  disabled={!replyMessage.trim() || sending}
                  className="px-5 py-3 bg-brand-green text-white rounded-xl font-semibold hover:bg-brand-greenHover transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2 shadow-lg shadow-brand-green/25"
                >
                  {sending ? (
                    <RefreshCw className="w-5 h-5 animate-spin" />
                  ) : (
                    <>
                      <Send className="w-5 h-5" />
                      <span className="hidden sm:inline">{t.sendReply}</span>
                    </>
                  )}
                </button>
              </div>
            </div>
          ) : (
            <div className="p-4 border-t border-slate-200 bg-slate-50 text-center">
              <p className="text-slate-500 text-sm flex items-center justify-center gap-2">
                <X className="w-4 h-4" />
                {t.ticketClosed}
              </p>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
