'use client';

import React, { useState, useEffect } from 'react';
import DashboardLayout from '@/app/dashboard/layout';
import dayjs from 'dayjs';
import {
  ChevronLeft,
  ChevronRight,
  Plus,
  Search,
  MessageSquare,
  Clock,
  CheckCircle,
  XCircle
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { useGlobalContext } from '@/context/Provider';
import apis from '@/utils/apis';
import RequestCategoryModal from '@/components/category/RequestCategoryModal';
import { cn } from '@/lib/utils';

export default function CategoryRequestsPage() {
  const { userInfo, Toast } = useGlobalContext();
  const rawType = userInfo?.restaurant_id?.type || 'grocery';
  const typeLabel = rawType === 'food' ? 'Grocery' : rawType.charAt(0).toUpperCase() + rawType.slice(1);

  const [requestList, setRequestList] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [showRequestModal, setShowRequestModal] = useState(false);

  const [pagination, setPagination] = useState({
    total: 0,
    page: 1,
    limit: 10,
    totalPages: 0
  });

  const fetchCategoryRequests = async (page: number) => {
    setLoading(true);
    try {
      let query = `page=${page}&limit=${pagination.limit}&type=${rawType}`;
      const res = await apis.category.getRequests(query);
      if (res) {
        const list = res.data || (Array.isArray(res) ? res : []);
        const total = res.data_count || res.count || res.total || list.length || 0;
        setRequestList(list);
        setPagination({
          total: total,
          page: page,
          limit: 10,
          totalPages: Math.ceil(total / 10) || 1
        });
      }
    } catch (error: any) {
      Toast.error(error || 'Error fetching category requests');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (userInfo?.restaurant_id?._id) {
      fetchCategoryRequests(1);
    }
  }, [userInfo?.restaurant_id?._id]);

  const handlePageChange = (newPage: number) => {
    if (newPage >= 1 && newPage <= pagination.totalPages) {
      setPagination(prev => ({ ...prev, page: newPage }));
      fetchCategoryRequests(newPage);
    }
  };

  const filteredList = requestList.filter((item) => {
    if (!searchQuery.trim()) return true;
    const catName = item.category_name || item.name || '';
    const note = item.note || item.description || '';
    const query = searchQuery.toLowerCase();
    return catName.toLowerCase().includes(query) || note.toLowerCase().includes(query);
  });

  return (
    <DashboardLayout>
      <main className="flex-1 bg-gray-50 p-6 overflow-hidden flex flex-col min-h-0">
        <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-6">
          <div>
            <h1 className="text-2xl font-bold text-[#1C1D22]">Category Requests</h1>
            <p className="text-xs text-gray-500 mt-0.5">
              View and track all category addition requests sent to admin
            </p>
          </div>
          <Button
            variant="theme"
            className="h-11 w-full sm:w-auto px-6 rounded-xl font-semibold shadow-md flex items-center gap-2 cursor-pointer"
            onClick={() => setShowRequestModal(true)}
          >
            <Plus className="w-4 h-4" />
            Request Category
          </Button>
        </div>

        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 flex flex-col flex-1 min-h-0 overflow-hidden">
          <div className="p-4 border-b border-gray-100 flex items-center justify-between gap-4">
            <div className="relative max-w-md w-full">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
              <Input
                placeholder="Search requested category"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-10 h-10 w-full border-gray-100 bg-[#F9FAFB] rounded-lg focus:ring-0"
              />
            </div>
            {pagination.total > 0 && (
              <span className="text-xs text-gray-500 font-medium whitespace-nowrap">
                Total Requests: <span className="font-bold text-gray-800">{pagination.total}</span>
              </span>
            )}
          </div>

          <div className="flex-1 overflow-auto">
            <Table>
              <TableHeader className="!bg-[#F9FAFB]">
                <TableRow className="border-none">
                  <TableHead className="font-semibold !text-gray-600">Sr. no.</TableHead>
                  <TableHead className="font-semibold !text-gray-600">Category Name</TableHead>
                  <TableHead className="font-semibold !text-gray-600">Note / Reason</TableHead>
                  <TableHead className="font-semibold !text-gray-600">Status</TableHead>
                  <TableHead className="font-semibold !text-gray-600">Requested Date</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {loading ? (
                  <TableRow>
                    <TableCell colSpan={5} className="h-40 text-center text-gray-400">
                      Loading category requests...
                    </TableCell>
                  </TableRow>
                ) : filteredList.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={5} className="h-40 text-center text-gray-400">
                      No category requests found
                    </TableCell>
                  </TableRow>
                ) : (
                  filteredList.map((req, index) => {
                    const catName = req.category_name || req.name || req.title || 'N/A';
                    const noteText = req.note || req.description || req.reason || '-';
                    const status = (req.status || 'pending').toLowerCase();
                    const dateStr = req.createdAt || req.created_at;

                    let badgeStyle = "bg-yellow-50 text-yellow-700 border-yellow-200";
                    let statusText = "Pending";
                    if (status === 'approved' || status === 'active' || status === 'completed') {
                      badgeStyle = "bg-green-50 text-green-700 border-green-200";
                      statusText = "Approved";
                    } else if (status === 'rejected' || status === 'declined' || status === 'inactive') {
                      badgeStyle = "bg-red-50 text-red-700 border-red-200";
                      statusText = "Rejected";
                    }

                    return (
                      <TableRow key={req._id || index} className="border-gray-50 hover:bg-gray-50/50">
                        <TableCell className="!text-gray-600">
                          {(pagination.page - 1) * pagination.limit + index + 1}
                        </TableCell>
                        <TableCell className="font-semibold text-[#1C1D22]">
                          {catName}
                        </TableCell>
                        <TableCell className="text-gray-600 max-w-md truncate">
                          {noteText}
                        </TableCell>
                        <TableCell>
                          <span className={cn("text-xs px-3 py-1 rounded-full font-semibold border inline-flex items-center gap-1 capitalize", badgeStyle)}>
                            {statusText}
                          </span>
                        </TableCell>
                        <TableCell className="text-xs text-gray-500">
                          {dateStr ? dayjs(dateStr).format('DD MMM YYYY, hh:mm A') : '-'}
                        </TableCell>
                      </TableRow>
                    );
                  })
                )}
              </TableBody>
            </Table>
          </div>

          <div className="p-4 border-t border-gray-100 flex items-center justify-center gap-2">
            <Button
              variant="ghost"
              size="icon"
              className="w-8 h-8 rounded-full"
              disabled={pagination.page <= 1}
              onClick={() => handlePageChange(pagination.page - 1)}
            >
              <ChevronLeft className="w-4 h-4" />
            </Button>
            <div className="flex gap-1">
              {(() => {
                const totalPages = pagination.totalPages;
                const currentPage = pagination.page;
                let pages: (number | string)[] = [];

                if (totalPages <= 7) {
                  pages = Array.from({ length: totalPages }, (_, i) => i + 1);
                } else {
                  if (currentPage <= 4) {
                    pages = [1, 2, 3, 4, 5, '...', totalPages];
                  } else if (currentPage >= totalPages - 3) {
                    pages = [1, '...', totalPages - 4, totalPages - 3, totalPages - 2, totalPages - 1, totalPages];
                  } else {
                    pages = [1, '...', currentPage - 1, currentPage, currentPage + 1, '...', totalPages];
                  }
                }

                return pages.map((page, index) => {
                  if (page === '...') {
                    return (
                      <span key={`dots-${index}`} className="flex items-center px-1 text-gray-400">
                        ...
                      </span>
                    );
                  }
                  return (
                    <button
                      key={page}
                      onClick={() => handlePageChange(page as number)}
                      className={cn(
                        "w-8 h-8 rounded-full text-sm font-medium transition-all",
                        currentPage === page ? "bg-[var(--primary-brand)] text-white" : "hover:bg-gray-100 text-gray-600"
                      )}
                    >
                      {page}
                    </button>
                  );
                });
              })()}
            </div>
            <Button
              variant="ghost"
              size="icon"
              className="w-8 h-8 rounded-full"
              disabled={pagination.page >= pagination.totalPages}
              onClick={() => handlePageChange(pagination.page + 1)}
            >
              <ChevronRight className="w-4 h-4" />
            </Button>
          </div>
        </div>

        {/* Request Category Modal */}
        <RequestCategoryModal
          isOpen={showRequestModal}
          onClose={() => setShowRequestModal(false)}
          onSuccess={() => fetchCategoryRequests(1)}
          rawType={rawType}
          storeId={userInfo?.restaurant_id?._id}
        />
      </main>
    </DashboardLayout>
  );
}
