"use client";

import { useState } from "react";

interface Props {
  lang: "ar" | "en";
}

export default function TwoWayChatInbox({ lang }: Props) {
  const isAr = lang === "ar";
  const [selectedChat, setSelectedChat] = useState("1");
  const [aiAssist, setAiAssist] = useState(false);

  const content = {
    ar: {
      title: "صندوق الوارد الموحد للمحادثات",
      subtitle: "كل المحادثات من WhatsApp وSMS والبريد في مكان واحد",
      inbox: {
        title: "الرسائل الواردة",
        empty: "كل شيء مُنجز. الرسائل الجديدة ستظهر هنا.",
        channels: {
          whatsapp: "WhatsApp",
          sms: "SMS",
          email: "Email",
        },
        chats: [
          {
            id: "1",
            patient: "سارة أحمد",
            channel: "whatsapp",
            lastMessage: "هل يمكن تغيير موعدي إلى الأسبوع القادم؟",
            time: "منذ دقيقتين",
            unread: 2,
            assignee: "نورا",
            sla: "عاجل",
            tags: ["تغيير موعد", "VIP"],
          },
          {
            id: "2",
            patient: "محمد العلي",
            channel: "sms",
            lastMessage: "متى نتائج الفحص؟",
            time: "منذ 10 دقائق",
            unread: 1,
            assignee: "أحمد",
            sla: "عادي",
            tags: ["استفسار"],
          },
          {
            id: "3",
            patient: "فاطمة خالد",
            channel: "email",
            lastMessage: "شكراً على الخدمة الممتازة",
            time: "منذ ساعة",
            unread: 0,
            assignee: null,
            sla: null,
            tags: ["تقييم إيجابي"],
          },
        ],
      },
      quickReplies: {
        title: "ردود سريعة",
        templates: [
          "شكراً لتواصلك. كيف يمكنني مساعدتك؟",
          "موعدك مؤكد في {{date}} الساعة {{time}}",
          "سنتواصل معك خلال 30 دقيقة",
          "يمكنك الحجز من خلال الرابط: {{booking_link}}",
        ],
      },
      customerProfile: {
        title: "ملف المريض",
        lastVisit: "آخر زيارة",
        nextBooking: "الموعد القادم",
        totalVisits: "إجمالي الزيارات",
        tags: "التصنيفات",
      },
      actions: {
        aiDraft: "مسودة بالذكاء الاصطناعي",
        summarize: "تلخيص المحادثة",
        escalate: "تصعيد للهاتف",
        assign: "تعيين لـ",
        internalNote: "ملاحظة داخلية",
      },
    },
    en: {
      title: "Two-Way Chat Unified Inbox",
      subtitle: "All chats from WhatsApp, SMS, and Email in one place",
      inbox: {
        title: "Inbox Messages",
        empty: "All caught up. New messages will land here.",
        channels: {
          whatsapp: "WhatsApp",
          sms: "SMS",
          email: "Email",
        },
        chats: [
          {
            id: "1",
            patient: "Sarah Ahmed",
            channel: "whatsapp",
            lastMessage: "Can I change my appointment to next week?",
            time: "2 min ago",
            unread: 2,
            assignee: "Nora",
            sla: "Urgent",
            tags: ["Reschedule", "VIP"],
          },
          {
            id: "2",
            patient: "Mohammed Ali",
            channel: "sms",
            lastMessage: "When are test results ready?",
            time: "10 min ago",
            unread: 1,
            assignee: "Ahmed",
            sla: "Normal",
            tags: ["Inquiry"],
          },
          {
            id: "3",
            patient: "Fatima Khaled",
            channel: "email",
            lastMessage: "Thank you for the excellent service",
            time: "1 hour ago",
            unread: 0,
            assignee: null,
            sla: null,
            tags: ["Positive Review"],
          },
        ],
      },
      quickReplies: {
        title: "Quick Replies",
        templates: [
          "Thank you for contacting us. How can I help you?",
          "Your appointment is confirmed on {{date}} at {{time}}",
          "We'll contact you within 30 minutes",
          "You can book through this link: {{booking_link}}",
        ],
      },
      customerProfile: {
        title: "Customer Profile",
        lastVisit: "Last Visit",
        nextBooking: "Next Booking",
        totalVisits: "Total Visits",
        tags: "Tags",
      },
      actions: {
        aiDraft: "AI Draft Reply",
        summarize: "Summarize Thread",
        escalate: "Escalate to Phone",
        assign: "Assign to",
        internalNote: "Internal Note",
      },
    },
  };

  const t = content[lang];

  const getChannelColor = (channel: string) => {
    switch (channel) {
      case "whatsapp":
        return "bg-green-500";
      case "sms":
        return "bg-blue-500";
      case "email":
        return "bg-purple-500";
      default:
        return "bg-gray-500";
    }
  };

  const getSLAColor = (sla: string | null) => {
    switch (sla) {
      case "Urgent":
      case "عاجل":
        return "text-red-600 bg-red-100";
      case "Normal":
      case "عادي":
        return "text-yellow-600 bg-yellow-100";
      default:
        return "";
    }
  };

  return (
    <div className="space-y-6">
      <div className="text-center space-y-2">
        <h2 className="text-3xl font-bold text-brand-ink dark:text-white">
          {t.title}
        </h2>
        <p className="text-gray-600 dark:text-gray-300">{t.subtitle}</p>
      </div>

      {/* Inbox Interface */}
      <div className="bg-white dark:bg-slate-900 rounded-3xl shadow-2xl overflow-hidden">
        <div className="grid lg:grid-cols-3 h-[600px]">
          {/* Chat List */}
          <div className="border-r dark:border-gray-700 overflow-y-auto">
            <div className="p-4 border-b dark:border-gray-700">
              <h3 className="font-bold text-brand-ink dark:text-white">
                {t.inbox.title}
              </h3>
            </div>
            <div className="divide-y dark:divide-gray-700">
              {t.inbox.chats.map((chat) => (
                <button
                  key={chat.id}
                  onClick={() => setSelectedChat(chat.id)}
                  className={`w-full p-4 hover:bg-gray-50 dark:hover:bg-slate-800 transition-colors text-left ${
                    selectedChat === chat.id ? "bg-brand-green/10" : ""
                  }`}
                >
                  <div className="flex items-start gap-3">
                    {/* Channel Badge */}
                    <div
                      className={`w-2 h-2 rounded-full mt-2 ${getChannelColor(chat.channel)}`}
                    />

                    <div className="flex-1 min-w-0">
                      <div className="flex items-center justify-between gap-2">
                        <span className="font-semibold text-brand-ink dark:text-white truncate">
                          {chat.patient}
                        </span>
                        <span className="text-xs text-gray-500 whitespace-nowrap">
                          {chat.time}
                        </span>
                      </div>

                      <p className="text-sm text-gray-600 dark:text-gray-400 truncate">
                        {chat.lastMessage}
                      </p>

                      <div className="flex items-center gap-2 mt-2">
                        {chat.unread > 0 && (
                          <span className="inline-flex items-center justify-center w-5 h-5 text-xs font-bold text-white bg-red-500 rounded-full">
                            {chat.unread}
                          </span>
                        )}
                        {chat.assignee && (
                          <span className="text-xs text-gray-500">
                            @{chat.assignee}
                          </span>
                        )}
                        {chat.sla && (
                          <span
                            className={`text-xs px-2 py-0.5 rounded-full font-medium ${getSLAColor(chat.sla)}`}
                          >
                            {chat.sla}
                          </span>
                        )}
                      </div>

                      <div className="flex gap-1 mt-2">
                        {chat.tags.map((tag, i) => (
                          <span
                            key={i}
                            className="text-xs px-2 py-0.5 bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400 rounded-full"
                          >
                            {tag}
                          </span>
                        ))}
                      </div>
                    </div>
                  </div>
                </button>
              ))}
            </div>
          </div>

          {/* Chat Content */}
          <div className="lg:col-span-2 flex flex-col">
            {/* Chat Header */}
            <div className="p-4 border-b dark:border-gray-700 flex items-center justify-between">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-brand-green text-white rounded-full flex items-center justify-center font-bold">
                  {isAr ? "س" : "S"}
                </div>
                <div>
                  <p className="font-semibold text-brand-ink dark:text-white">
                    {isAr ? "سارة أحمد" : "Sarah Ahmed"}
                  </p>
                  <p className="text-xs text-gray-500">
                    {isAr ? "آخر ظهور منذ دقيقتين" : "Last seen 2 min ago"}
                  </p>
                </div>
              </div>

              {/* Actions */}
              <div className="flex gap-2">
                <button
                  onClick={() => setAiAssist(!aiAssist)}
                  className={`px-3 py-1 rounded-lg text-sm font-medium transition-colors ${
                    aiAssist
                      ? "bg-purple-600 text-white"
                      : "bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300"
                  }`}
                >
                  {t.actions.aiDraft}
                </button>
                <button className="px-3 py-1 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg text-sm font-medium hover:bg-gray-200 dark:hover:bg-gray-600">
                  {t.actions.summarize}
                </button>
              </div>
            </div>

            {/* Messages Area */}
            <div className="flex-1 p-4 overflow-y-auto bg-gray-50 dark:bg-slate-800">
              <div className="space-y-4">
                {/* Patient Message */}
                <div className="flex justify-start">
                  <div className="max-w-xs bg-white dark:bg-slate-700 rounded-2xl rounded-bl-none p-3 shadow">
                    <p className="text-sm text-gray-800 dark:text-gray-200">
                      {isAr
                        ? "هل يمكن تغيير موعدي إلى الأسبوع القادم؟"
                        : "Can I change my appointment to next week?"}
                    </p>
                    <p className="text-xs text-gray-500 mt-1">10:30 AM</p>
                  </div>
                </div>

                {/* Agent Message */}
                <div className="flex justify-end">
                  <div className="max-w-xs bg-brand-green text-white rounded-2xl rounded-br-none p-3">
                    <p className="text-sm">
                      {isAr
                        ? "بالطبع! دعني أتحقق من المواعيد المتاحة الأسبوع القادم."
                        : "Of course! Let me check available slots for next week."}
                    </p>
                    <p className="text-xs text-green-100 mt-1">10:32 AM</p>
                  </div>
                </div>

                {/* AI Assistant Suggestion */}
                {aiAssist && (
                  <div className="bg-purple-50 dark:bg-purple-900/20 border-2 border-purple-200 dark:border-purple-700 rounded-xl p-4">
                    <div className="flex items-center gap-2 mb-2">
                      <span className="text-purple-600 dark:text-purple-400">
                        🤖
                      </span>
                      <span className="text-sm font-semibold text-purple-600 dark:text-purple-400">
                        {isAr ? "اقتراح الذكاء الاصطناعي" : "AI Suggestion"}
                      </span>
                    </div>
                    <p className="text-sm text-gray-700 dark:text-gray-300">
                      {isAr
                        ? "لدينا مواعيد متاحة يوم الثلاثاء في 10:00 ص و 2:00 م، أو الخميس في 3:00 م. أي وقت يناسبك؟"
                        : "We have available slots on Tuesday at 10:00 AM and 2:00 PM, or Thursday at 3:00 PM. Which time works best for you?"}
                    </p>
                    <div className="flex gap-2 mt-3">
                      <button className="px-3 py-1 bg-purple-600 text-white rounded-lg text-sm hover:bg-purple-700">
                        {isAr ? "استخدم" : "Use"}
                      </button>
                      <button className="px-3 py-1 bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg text-sm hover:bg-gray-300 dark:hover:bg-gray-600">
                        {isAr ? "تعديل" : "Edit"}
                      </button>
                    </div>
                  </div>
                )}
              </div>
            </div>

            {/* Quick Replies */}
            <div className="p-4 border-t dark:border-gray-700">
              <p className="text-xs text-gray-500 mb-2">
                {t.quickReplies.title}:
              </p>
              <div className="flex gap-2 flex-wrap">
                {t.quickReplies.templates.slice(0, 3).map((template, i) => (
                  <button
                    key={i}
                    className="px-3 py-1 bg-gray-100 dark:bg-gray-700 text-xs text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600"
                  >
                    {template.substring(0, 30)}...
                  </button>
                ))}
              </div>
            </div>

            {/* Message Input */}
            <div className="p-4 border-t dark:border-gray-700">
              <div className="flex gap-2">
                <button type="button" aria-label="Attach file" className="p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300">
                  📎
                </button>
                <input
                  type="text"
                  placeholder={isAr ? "اكتب رسالتك..." : "Type your message..."}
                  className="flex-1 px-4 py-2 bg-gray-100 dark:bg-gray-800 rounded-xl focus:outline-none focus:ring-2 focus:ring-brand-green"
                  dir={isAr ? "rtl" : "ltr"}
                />
                <button className="px-4 py-2 bg-brand-green text-white rounded-xl hover:bg-brand-greenHover">
                  {isAr ? "إرسال" : "Send"}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Customer Profile Sidebar */}
      <div className="bg-gray-50 dark:bg-slate-800 rounded-2xl p-6 space-y-4">
        <h3 className="text-lg font-bold text-brand-ink dark:text-white">
          {t.customerProfile.title}
        </h3>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <div>
            <p className="text-xs text-gray-500 mb-1">
              {t.customerProfile.lastVisit}
            </p>
            <p className="font-semibold text-brand-ink dark:text-white">
              {isAr ? "15 نوفمبر 2024" : "Nov 15, 2024"}
            </p>
          </div>
          <div>
            <p className="text-xs text-gray-500 mb-1">
              {t.customerProfile.nextBooking}
            </p>
            <p className="font-semibold text-brand-green">
              {isAr ? "28 نوفمبر 2:00م" : "Nov 28, 2:00 PM"}
            </p>
          </div>
          <div>
            <p className="text-xs text-gray-500 mb-1">
              {t.customerProfile.totalVisits}
            </p>
            <p className="font-semibold text-brand-ink dark:text-white">12</p>
          </div>
          <div>
            <p className="text-xs text-gray-500 mb-1">
              {t.customerProfile.tags}
            </p>
            <div className="flex gap-1">
              <span className="px-2 py-0.5 bg-yellow-100 text-yellow-700 text-xs rounded-full">
                VIP
              </span>
              <span className="px-2 py-0.5 bg-blue-100 text-blue-700 text-xs rounded-full">
                {isAr ? "منتظم" : "Regular"}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
