"use client";

import React, { useEffect, useState } from "react";
import DashboardLayout from "@/app/dashboard/layout";
import apis, { BUCKET_ROOT } from "@/utils/apis";
import dayjs from "dayjs";
import {
  Pagination,
  PaginationContent,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious,
  PaginationEllipsis,
} from "@/components/ui/pagination";
import { useGlobalContext } from "@/context/Provider";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent } from "@/components/ui/dialog";
import { 
  MessageCircle, 
  Clock, 
  CheckCircle, 
  Eye, 
  Calendar, 
  ImageIcon, 
  X, 
  Send, 
  User, 
  Phone, 
  Mail, 
  MessageSquare,
  ShoppingCart
} from "lucide-react";

interface QueryItem {
  _id: string;
  query_text: string;
  description?: string;
  image?: string;
  image_url?: string;
  reply?: string;
  reply_text?: string;
  status?: string;
  query_status?: string;
  createdAt: string;
  created_at?: string;
  customer_id?: {
    _id: string;
    name: string;
    email: string;
    country_code: string;
    phone: string;
    image: string | null;
  };
  customer?: {
    _id: string;
    name: string;
    email: string;
    country_code: string;
    phone: string;
    image: string | null;
  };
  user?: {
    _id: string;
    name: string;
    email: string;
    country_code: string;
    phone: string;
    image: string | null;
  };
}

const getPaginationRange = (
  currentPage: number,
  totalPages: number,
  siblingCount = 1
) => {
  const totalPageNumbers = siblingCount * 2 + 5;
  if (totalPages <= totalPageNumbers)
    return Array.from({ length: totalPages }, (_, i) => i + 1);

  const leftSiblingIndex = Math.max(currentPage - siblingCount, 2);
  const rightSiblingIndex = Math.min(currentPage + siblingCount, totalPages - 1);

  const shouldShowLeftEllipsis = leftSiblingIndex > 2;
  const shouldShowRightEllipsis = rightSiblingIndex < totalPages - 1;

  const range: (number | "...")[] = [1];

  if (shouldShowLeftEllipsis) range.push("...");

  for (let i = leftSiblingIndex; i <= rightSiblingIndex; i++) range.push(i);

  if (shouldShowRightEllipsis) range.push("...");

  range.push(totalPages);
  return range;
};

const CustomerQueriesList = () => {
  const { userInfo, Toast } = useGlobalContext();
  const restaurant_id = userInfo?.restaurant_id?._id;

  const [queries, setQueries] = useState<QueryItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [pageNumber, setPageNumber] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [totalCount, setTotalCount] = useState(0);
  const [replyTexts, setReplyTexts] = useState<Record<string, string>>({});
  const [submittingReply, setSubmittingReply] = useState<Record<string, boolean>>({});
  const [previewImage, setPreviewImage] = useState<string | null>(null);
  
  const limit = 6;

  const fetchQueries = async (page: number) => {
    if (!restaurant_id) return;
    setLoading(true);

    try {
      const queryStr = `restaurant_id=${restaurant_id}&page=${page}&limit=${limit}`;
      const res = await apis.Customer.queriesList(queryStr);
      
      const rawData = res?.data || (Array.isArray(res) ? res : res?.list || []);
      const total = res?.total || res?.count || rawData.length || 0;

      setQueries(rawData);
      setTotalCount(total);
      setTotalPages(Math.ceil(total / limit) || 1);
    } catch (error: any) {
      console.error("Error fetching customer queries:", error);
      Toast.error(error?.message || "Failed to load customer queries");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (restaurant_id) {
      fetchQueries(pageNumber);
    }
  }, [restaurant_id, pageNumber]);

  const handleReplySubmit = async (queryId: string) => {
    const text = replyTexts[queryId]?.trim();
    if (!text) {
      Toast.error("Please enter a reply message.");
      return;
    }

    setSubmittingReply(prev => ({ ...prev, [queryId]: true }));
    try {
      await apis.Customer.replyQuery({
        query_id: queryId,
        reply: text
      });
      Toast.success("Reply submitted successfully!");
      // Clear reply field for this query
      setReplyTexts(prev => ({ ...prev, [queryId]: "" }));
      // Refresh queries list
      fetchQueries(pageNumber);
    } catch (error: any) {
      console.error("Error submitting reply:", error);
      Toast.error(error?.message || "Failed to submit reply");
    } finally {
      setSubmittingReply(prev => ({ ...prev, [queryId]: false }));
    }
  };

  const handleResolveSubmit = async (queryId: string) => {
    setSubmittingReply(prev => ({ ...prev, [queryId]: true }));
    try {
      await apis.Customer.replyQuery({
        query_id: queryId,
        reply: "Resolved"
      });
      Toast.success("Query resolved successfully!");
      // Refresh queries list
      fetchQueries(pageNumber);
    } catch (error: any) {
      console.error("Error resolving query:", error);
      Toast.error(error?.message || "Failed to resolve query");
    } finally {
      setSubmittingReply(prev => ({ ...prev, [queryId]: false }));
    }
  };

  const handleCreatePOSOrder = (query: QueryItem) => {
    const custId = query.customer_id?._id || query.customer?._id || query.user?._id || "";
    const custName = query.customer_id?.name || query.customer?.name || query.user?.name || "";
    const custPhone = query.customer_id?.phone || query.customer?.phone || query.user?.phone || "";
    const custEmail = query.customer_id?.email || query.customer?.email || query.user?.email || "";
    const custPhoneCode = query.customer_id?.country_code || query.customer?.country_code || query.user?.country_code || "";
    const rawType = userInfo?.restaurant_id?.type || 'grocery';
    const posUrl = rawType === 'grocery' ? '/grocery-pos' : '/point-of-sale';

    const params = new URLSearchParams({
      customer_id: custId,
      name: custName,
      phone: custPhone,
      email: custEmail,
      country_code: custPhoneCode
    });

    window.location.href = `${posUrl}?${params.toString()}`;
  };

  return (
    <div className="overflow-y-auto h-screen w-full flex flex-col bg-gray-50 p-6 pb-24">
      {/* Header Section */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 tracking-tight">Snap and Order</h1>
          <p className="text-sm text-gray-500 mt-1">Review and resolve customer snap and order requests.</p>
        </div>
      </div>

      {/* Main Grid View */}
      {loading ? (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6 flex-1">
          {[...Array(4)].map((_, i) => (
            <div key={i} className="bg-white rounded-2xl p-6 border border-gray-100 shadow-sm flex flex-col h-80 animate-pulse">
              <div className="flex items-center gap-3 pb-4 border-b border-gray-100">
                <div className="w-10 h-10 bg-gray-200 rounded-full" />
                <div className="space-y-2 flex-1">
                  <div className="h-4 bg-gray-200 rounded w-1/3" />
                  <div className="h-3 bg-gray-200 rounded w-1/4" />
                </div>
                <div className="w-16 h-6 bg-gray-200 rounded-full" />
              </div>
              <div className="flex-1 py-4 space-y-2">
                <div className="h-3 bg-gray-200 rounded w-full" />
                <div className="h-3 bg-gray-200 rounded w-5/6" />
                <div className="h-3 bg-gray-200 rounded w-4/6" />
              </div>
              <div className="h-10 bg-gray-200 rounded-lg w-full mt-auto" />
            </div>
          ))}
        </div>
      ) : queries.length > 0 ? (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 pb-6">
          {queries.map((query) => {
            const custName = query.customer_id?.name || query.customer?.name || query.user?.name || "Customer";
            const custEmail = query.customer_id?.email || query.customer?.email || query.user?.email;
            const custPhone = query.customer_id?.phone || query.customer?.phone || query.user?.phone;
            const custPhoneCode = query.customer_id?.country_code || query.customer?.country_code || query.user?.country_code || "";
            const custImage = query.customer_id?.image || query.customer?.image || query.user?.image;
            
            const hasReply = !!(query.reply || query.reply_text);
            const normalizedStatus = (query.status || query.query_status || "pending").toLowerCase();
            const isResolved = hasReply || normalizedStatus === "resolved" || normalizedStatus === "completed" || normalizedStatus === "closed";
            
            const imageKey = query.image || query.image_url;

            return (
              <div
                key={query._id}
                className="bg-white border border-gray-200 rounded-2xl shadow-sm p-6 flex flex-col justify-between hover:shadow-md transition-shadow"
              >
                <div>
                  {/* Customer Info Header */}
                  <div className="flex items-center justify-between pb-4 border-b border-gray-100 mb-4 gap-3">
                    <div className="flex items-center gap-3">
                      {custImage ? (
                        <img
                          src={custImage.startsWith("http") ? custImage : BUCKET_ROOT + custImage}
                          alt={custName}
                          className="w-11 h-11 rounded-full object-cover border border-gray-200"
                        />
                      ) : (
                        <div className="w-11 h-11 rounded-full bg-brand/10 text-brand flex items-center justify-center font-bold">
                          {custName.charAt(0).toUpperCase()}
                        </div>
                      )}
                      <div>
                        <h3 className="font-bold text-gray-900 text-sm leading-tight capitalize">{custName}</h3>
                        <p className="text-xs text-gray-400 mt-0.5">
                          Sent {dayjs(query.createdAt || query.created_at).format("DD MMM YYYY, hh:mm A")}
                        </p>
                      </div>
                    </div>

                    <span
                      className={`text-xs px-3 py-1 rounded-full font-semibold border ${
                        isResolved
                          ? "bg-green-50 text-green-700 border-green-200"
                          : "bg-yellow-50 text-yellow-700 border-yellow-200"
                      }`}
                    >
                      {isResolved ? "Resolved" : "Pending"}
                    </span>
                  </div>

                  {/* Customer details info */}
                  <div className="flex flex-wrap gap-x-4 gap-y-2 mb-4 text-xs text-gray-500 bg-gray-50 p-3 rounded-lg border border-gray-100/50">
                    {custEmail && (
                      <div className="flex items-center gap-1.5 min-w-0">
                        <Mail className="w-3.5 h-3.5 text-gray-400 flex-shrink-0" />
                        <span className="truncate">{custEmail}</span>
                      </div>
                    )}
                    {custPhone && (
                      <div className="flex items-center gap-1.5">
                        <Phone className="w-3.5 h-3.5 text-gray-400 flex-shrink-0" />
                        <span>{custPhoneCode.startsWith("+") ? "" : "+"}{custPhoneCode} {custPhone}</span>
                      </div>
                    )}
                  </div>

                  {/* Query text details */}
                  <div className="mb-4">
                    <p className="text-gray-700 text-sm leading-relaxed whitespace-pre-line bg-gray-50/20 border border-gray-100 p-3.5 rounded-xl">
                      {query.query_text || query.description || "No query description provided"}
                    </p>
                  </div>

                  {/* Attachment if present */}
                  {imageKey && (
                    <div className="mb-4 p-3 border border-gray-100 bg-white rounded-xl flex items-center justify-between shadow-xs">
                      <div className="flex items-center gap-2 text-xs font-semibold text-gray-600">
                        <ImageIcon className="w-4 h-4 text-brand" />
                        <span>1 Attachment</span>
                      </div>
                      <button
                        onClick={() => {
                          const fullUrl = imageKey.startsWith("http") ? imageKey : BUCKET_ROOT + imageKey;
                          setPreviewImage(fullUrl);
                        }}
                        className="text-xs font-bold text-brand hover:text-brand-dark flex items-center gap-1 transition-colors"
                      >
                        <Eye className="w-4 h-4" /> View Image
                      </button>
                    </div>
                  )}
                </div>

                {/* Reply section */}
                {!isResolved && (
                  <div className="mt-4 pt-4 border-t border-gray-100">
                    {/* {hasReply ? (
                      <div className="bg-green-50/50 border border-green-100 rounded-xl p-4">
                        <div className="flex items-center gap-1.5 text-xs font-bold text-green-700 mb-1.5">
                          <CheckCircle className="w-4 h-4" />
                          <span>Your Reply</span>
                        </div>
                        <p className="text-sm text-gray-700 leading-relaxed whitespace-pre-line">
                          {query.reply || query.reply_text}
                        </p>
                      </div>
                    ) : ( */}
                      <div className="space-y-3">
                        {/*
                        <label className="block text-xs font-semibold text-gray-600">Reply to Customer</label>
                        <div className="flex flex-col gap-3">
                          <textarea
                            placeholder="Type your response to the customer here..."
                            value={replyTexts[query._id] || ""}
                            onChange={(e) => setReplyTexts(prev => ({ ...prev, [query._id]: e.target.value }))}
                            className="w-full min-h-[80px] max-h-[160px] p-3 text-sm border border-gray-200 rounded-xl focus:outline-none focus:ring-1 focus:ring-brand/50 focus:border-brand bg-white resize-y"
                          />
                          <div className="flex justify-end">
                            <Button
                              disabled={submittingReply[query._id] || !replyTexts[query._id]?.trim()}
                              onClick={() => handleReplySubmit(query._id)}
                              variant="theme"
                              className="h-10 px-5 rounded-xl flex items-center gap-2 font-semibold"
                            >
                              {submittingReply[query._id] ? (
                                <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin" />
                              ) : (
                                <>
                                  <span>Send Reply</span>
                                  <Send className="w-4 h-4" />
                                </>
                              )}
                            </Button>
                          </div>
                        </div>
                        */}
                        <div className="flex justify-end">
                          <Button
                            disabled={submittingReply[query._id]}
                            onClick={() => handleResolveSubmit(query._id)}
                            variant="theme"
                            className="h-10 px-5 rounded-xl flex items-center gap-2 font-semibold bg-green-600 hover:bg-green-700 text-white"
                          >
                            {submittingReply[query._id] ? (
                              <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin" />
                            ) : (
                              <>
                                <span>Resolve</span>
                                <CheckCircle className="w-4 h-4" />
                              </>
                            )}
                          </Button>
                        </div>
                      </div>
                    {/* )} */}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      ) : (
        <div className="flex flex-col justify-center items-center text-gray-500 py-20 bg-white rounded-2xl border border-dashed border-gray-200 shadow-sm flex-1">
          <div className="w-16 h-16 bg-gray-50 rounded-full flex items-center justify-center mb-4">
            <MessageSquare className="w-8 h-8 text-gray-300" />
          </div>
          <p className="text-lg font-medium text-gray-900">No snap and order requests found</p>
          <p className="text-sm text-gray-400 mt-1">Requests submitted by customers will show up here for you to answer.</p>
        </div>
      )}

      {/* Pagination */}
      {!loading && totalPages > 1 && (
        <div className="mt-6 flex justify-center bg-white py-3 border border-gray-100 rounded-xl shadow-sm">
          <Pagination>
            <PaginationPrevious
              onClick={() => setPageNumber((prev) => Math.max(prev - 1, 1))}
              className="cursor-pointer"
            >
              Previous
            </PaginationPrevious>
            <PaginationContent>
              {getPaginationRange(pageNumber, totalPages).map((p, i) => (
                <PaginationItem key={i}>
                  {p === "..." ? (
                    <PaginationEllipsis />
                  ) : (
                    <PaginationLink
                      isActive={pageNumber === p}
                      onClick={() => setPageNumber(Number(p))}
                      className="cursor-pointer"
                    >
                      {p}
                    </PaginationLink>
                  )}
                </PaginationItem>
              ))}
            </PaginationContent>
            <PaginationNext
              onClick={() => setPageNumber((prev) => Math.min(prev + 1, totalPages))}
              className="cursor-pointer"
            >
              Next
            </PaginationNext>
          </Pagination>
        </div>
      )}

      {/* Image Lightbox Dialog */}
      <Dialog open={!!previewImage} onOpenChange={() => setPreviewImage(null)}>
        <DialogContent className="max-w-3xl bg-transparent border-none shadow-none flex justify-center items-center p-0">
          <div className="relative max-h-[85vh] max-w-full overflow-hidden rounded-xl bg-black/80 flex items-center justify-center p-4">
            <button
              onClick={() => setPreviewImage(null)}
              className="absolute top-4 right-4 z-50 bg-black/60 hover:bg-black/80 text-white rounded-full p-2 transition-all"
            >
              <X className="w-5 h-5" />
            </button>
            {previewImage && (
              <img
                src={previewImage}
                alt="Attachment Preview"
                className="max-h-[80vh] max-w-full object-contain rounded-lg"
              />
            )}
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
};

export default function CustomerQueriesPage() {
  return (
    <DashboardLayout>
      <CustomerQueriesList />
    </DashboardLayout>
  );
}
