'use client';

import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import DashboardLayout from '@/app/dashboard/layout';
import dayjs from 'dayjs';
import {
  Pencil,
  Search,
  Trash2,
  ChevronLeft,
  ChevronRight,
  Plus,
  Upload,
  Clock,
  CheckCircle,
  XCircle,
  MessageSquare,
  GripVertical
} 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 DeleteDialog from '@/components/ui/deleteModal';
import RequestCategoryModal from '@/components/category/RequestCategoryModal';
import { cn } from '@/lib/utils';
import {
  DndContext,
  closestCenter,
  KeyboardSensor,
  PointerSensor,
  useSensor,
  useSensors,
  DragEndEvent,
} from '@dnd-kit/core';
import {
  arrayMove,
  SortableContext,
  sortableKeyboardCoordinates,
  verticalListSortingStrategy,
  useSortable,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';

interface SortableCategoryRowProps {
  cat: any;
  index: number;
  pagination: any;
  handleEdit: (cat: any) => void;
  setDeletingCategory: (cat: any) => void;
  setShowDeleteModal: (show: boolean) => void;
}

const SortableCategoryRow = ({
  cat,
  index,
  pagination,
  handleEdit,
  setDeletingCategory,
  setShowDeleteModal,
}: SortableCategoryRowProps) => {
  const id = cat._id || cat.id;
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({ id });

  const style: React.CSSProperties = {
    transform: CSS.Transform.toString(transform),
    transition,
    opacity: isDragging ? 0.6 : 1,
    zIndex: isDragging ? 20 : 1,
    position: isDragging ? 'relative' : undefined,
  };

  return (
    <TableRow
      ref={setNodeRef}
      style={style}
      className={cn(
        "border-gray-50 hover:bg-gray-50/50 transition-colors",
        isDragging && "bg-orange-50/60 shadow-md"
      )}
    >
      <TableCell className="w-10">
        <div
          {...attributes}
          {...listeners}
          className="cursor-grab active:cursor-grabbing text-gray-400 hover:text-gray-600 p-1 rounded inline-flex items-center justify-center"
          title="Drag to reorder category"
        >
          <GripVertical className="w-4 h-4" />
        </div>
      </TableCell>
      <TableCell className="!text-gray-600 font-medium">
        {(pagination.page - 1) * pagination.limit + index + 1}
      </TableCell>
      <TableCell>
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-lg bg-gray-100 flex items-center justify-center border border-gray-200 overflow-hidden shrink-0">
            {cat.category_image ? (
              <img
                src={`${apis.BUCKET_ROOT}${cat.category_image}`}
                alt={cat.category_name}
                className="w-full h-full object-cover"
              />
            ) : (
              <div className="w-full h-full flex items-center justify-center bg-[#F1F3F5] text-[#A0AEC0]">
                <Upload className="w-5 h-5" />
              </div>
            )}
          </div>
          <span className="font-medium text-[#1C1D22]">{cat.category_name}</span>
        </div>
      </TableCell>
      <TableCell>
        <div className="flex justify-center gap-2">
          <Button
            variant="ghost"
            size="icon"
            className="h-8 w-8 rounded-lg border border-gray-200 hover:bg-gray-100 cursor-pointer"
            onClick={() => handleEdit(cat)}
          >
            <Pencil className="w-4 h-4 text-gray-500" />
          </Button>
          <Button
            variant="ghost"
            size="icon"
            className="h-8 w-8 rounded-lg border border-gray-200 hover:bg-red-50 hover:border-red-200 cursor-pointer"
            onClick={() => {
              setDeletingCategory(cat);
              setShowDeleteModal(true);
            }}
          >
            <Trash2 className="w-4 h-4 text-red-500" />
          </Button>
        </div>
      </TableCell>
    </TableRow>
  );
};

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

  const [categoryList, setCategoryList] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [pagination, setPagination] = useState({
    total: 0,
    page: 1,
    limit: 10,
    totalPages: 0
  });

  const [searchQuery, setSearchQuery] = useState('');
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [showEditModal, setShowEditModal] = useState(false);
  const [showRequestModal, setShowRequestModal] = useState(false);

  const [deletingCategory, setDeletingCategory] = useState<any>(null);
  const [editingCategory, setEditingCategory] = useState<any>(null);
  const [editName, setEditName] = useState('');
  const [editImage, setEditImage] = useState<any>(null);
  const [editImageUrl, setEditImageUrl] = useState('');
  const [isUpdating, setIsUpdating] = useState(false);
  const [isDragging, setIsDragging] = useState(false);
  const editFileInputRef = React.useRef<HTMLInputElement>(null);

  const sensors = useSensors(
    useSensor(PointerSensor, {
      activationConstraint: {
        distance: 5,
      },
    }),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates,
    })
  );

  const handleDragEnd = async (event: DragEndEvent) => {
    const { active, over } = event;
    if (!over || active.id === over.id) return;

    const oldIndex = categoryList.findIndex((cat: any) => (cat._id || cat.id) === active.id);
    const newIndex = categoryList.findIndex((cat: any) => (cat._id || cat.id) === over.id);

    if (oldIndex !== -1 && newIndex !== -1) {
      const updatedList = arrayMove(categoryList, oldIndex, newIndex);
      setCategoryList(updatedList);

      try {
        const payload = {
          categories: updatedList.map((cat: any, index: number) => ({
            id: cat._id || cat.id,
            sort_order: index,
          })),
        };
        const apiRes = await apis.category.reorder(payload);
        if (apiRes?.success || apiRes?.message) {
          Toast.success(apiRes?.message || 'Category order updated');
        }
      } catch (error: any) {
        Toast.error(error?.message || error || 'Failed to reorder categories');
        fetchCategories(pagination.page, searchQuery);
      }
    }
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(true);
  };

  const handleDragLeave = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(false);
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(false);

    const file = e.dataTransfer.files?.[0];
    if (file) {
      if (!file.type.startsWith('image/')) {
        Toast.error('Please upload an image file');
        return;
      }
      setEditImage(file);
      setEditImageUrl(URL.createObjectURL(file));
    }
  };

  const fetchCategories = async (page: number, search: string) => {
    setLoading(true);
    try {
      const storeId = userInfo?.restaurant_id?._id;
      let query = `page=${page}&limit=${pagination.limit}&type=${rawType}`;
      if (storeId) query += `&store_id=${storeId}`;
      if (search) query += `&search=${search}`;

      const res = await apis.category.list(query);
      if (res) {
        setCategoryList(res.data || []);
        const total = res.data_count || 0;
        setPagination({
          total: total,
          page: page,
          limit: 10,
          totalPages: Math.ceil(total / 10)
        });
      }
    } catch (error: any) {
      Toast.error(error || 'Error fetching categories');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (!userInfo?.restaurant_id?._id) return;
    const timer = setTimeout(() => {
      fetchCategories(1, searchQuery);
      if (pagination.page !== 1) {
        setPagination(prev => ({ ...prev, page: 1 }));
      }
    }, 500);
    return () => clearTimeout(timer);
  }, [searchQuery, userInfo?.restaurant_id?._id]);

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

  const handleEdit = async (cat: any) => {
    setLoading(true);
    try {
      const res = await apis.category.getById(cat._id);
      if (res?.success || res?.data) {
        const data = res.data || res;
        setEditingCategory(data);
        setEditName(data.category_name || '');
        setEditImageUrl(data.category_image || '');
        setEditImage(null);
        setShowEditModal(true);
      }
    } catch (error: any) {
      Toast.error(error || 'Error fetching category details');
    } finally {
      setLoading(false);
    }
  };

  const handleUpdateCategory = async () => {
    if (!editName.trim()) {
      Toast.error('Category name is required');
      return;
    }

    setIsUpdating(true);
    try {
      let finalImageUrl = editImageUrl;

      if (editImage) {
        const uploadRes = await apis.Common.uploadFile('file', editImage);
        if (uploadRes && uploadRes.key) {
          finalImageUrl = uploadRes.key;
        } else {
          throw new Error(uploadRes?.message || 'Image upload failed');
        }
      }

      const payload = {
        category_name: editName,
        category_image: finalImageUrl
      };

      const res = await apis.category.update(editingCategory._id, payload);
      if (res) {
        Toast.success('Category updated successfully');
        setShowEditModal(false);
        fetchCategories(pagination.page, searchQuery);
      }
    } catch (error: any) {
      Toast.error(error || 'Error updating category');
    } finally {
      setIsUpdating(false);
    }
  };

  const handleEditImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      setEditImage(file);
      setEditImageUrl(URL.createObjectURL(file));
    }
  };

  const confirmDeleteCategory = async () => {
    if (!deletingCategory) return;
    try {
      await apis.category.delete(deletingCategory._id);
      Toast.success('Category deleted successfully');
      fetchCategories(pagination.page, searchQuery);
    } catch (error: any) {
      Toast.error(error || 'Error deleting category');
    } finally {
      setShowDeleteModal(false);
      setDeletingCategory(null);
    }
  };

  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]">{typeLabel} Category</h1>
            <p className="text-xs text-gray-500 mt-0.5">Manage existing categories or request a new category from 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">
          <div className="p-4 border-b border-gray-100">
            <div className="relative max-w-md">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
              <Input
                placeholder="Search 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>
          </div>

          <div className="flex-1 overflow-auto">
            <Table>
              <TableHeader className="!bg-[#F9FAFB]">
                <TableRow className="border-none">
                  <TableHead className="w-10"></TableHead>
                  <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 text-center">Action</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {loading ? (
                  <TableRow>
                    <TableCell colSpan={4} className="h-40 text-center text-gray-400">
                      Loading categories...
                    </TableCell>
                  </TableRow>
                ) : categoryList.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={4} className="h-40 text-center text-gray-400">
                      No categories found
                    </TableCell>
                  </TableRow>
                ) : (
                  <DndContext
                    id="grocery-category-dnd-context"
                    sensors={sensors}
                    collisionDetection={closestCenter}
                    onDragEnd={handleDragEnd}
                  >
                    <SortableContext
                      items={categoryList.map((c: any) => c._id || c.id)}
                      strategy={verticalListSortingStrategy}
                    >
                      {categoryList.map((cat, index) => (
                        <SortableCategoryRow
                          key={cat._id || cat.id || index}
                          cat={cat}
                          index={index}
                          pagination={pagination}
                          handleEdit={handleEdit}
                          setDeletingCategory={setDeletingCategory}
                          setShowDeleteModal={setShowDeleteModal}
                        />
                      ))}
                    </SortableContext>
                  </DndContext>
                )}
              </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>

        <DeleteDialog
          isOpen={showDeleteModal}
          onClose={() => setShowDeleteModal(false)}
          handleDelete={confirmDeleteCategory}
          title={`Delete ${typeLabel} Category`}
          description={`Are you sure you want to delete "${deletingCategory?.category_name}"? This action cannot be undone.`}
        />

        {/* Edit Category Modal */}
        {showEditModal && (
          <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
            <div className="bg-white rounded-2xl shadow-xl w-full max-w-md overflow-hidden flex flex-col">
              <div className="p-6 border-b border-gray-100 flex justify-between items-center bg-[#F9FAFB]">
                <h2 className="text-xl font-bold text-[#1C1D22]">Edit Category</h2>
                <button
                  onClick={() => setShowEditModal(false)}
                  className="p-2 hover:bg-gray-200 rounded-full transition-colors"
                >
                  <Plus className="w-5 h-5 rotate-45 text-gray-500" />
                </button>
              </div>

              <div className="p-6 space-y-6">
                <div className="space-y-2">
                  <label className="text-sm font-semibold text-gray-700">Category Name</label>
                  <Input
                    placeholder="Enter category name"
                    value={editName}
                    onChange={(e) => setEditName(e.target.value)}
                    className="h-12 border-gray-200 bg-gray-50 focus:bg-white transition-all rounded-xl"
                  />
                </div>

                <div className="space-y-2">
                  <label className="text-sm font-semibold text-gray-700">Category Image</label>
                  <div
                    onClick={() => editFileInputRef.current?.click()}
                    onDragOver={handleDragOver}
                    onDragLeave={handleDragLeave}
                    onDrop={handleDrop}
                    className={cn(
                      "group relative h-40 w-full rounded-2xl border-2 border-dashed flex flex-col items-center justify-center cursor-pointer transition-all overflow-hidden",
                      isDragging
                        ? "border-[var(--primary-brand)] bg-[var(--primary-brand)]/15 scale-[1.01]"
                        : "border-gray-200 bg-gray-50 hover:border-[var(--primary-brand)] hover:bg-[var(--primary-brand)]/5"
                    )}
                  >
                    {editImageUrl ? (
                      <>
                        <img
                          src={editImageUrl.startsWith('blob:') ? editImageUrl : `${apis.BUCKET_ROOT}${editImageUrl}`}
                          alt="Category"
                          className="w-full h-full object-cover"
                        />
                        <div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 flex items-center justify-center transition-opacity">
                          <p className="text-xs text-white font-medium bg-black/60 px-3 py-1.5 rounded-lg flex items-center gap-1.5">
                            <Upload className="w-4 h-4" /> Change Image
                          </p>
                        </div>
                      </>
                    ) : (
                      <>
                        <div className="p-3 bg-white rounded-xl shadow-sm mb-2 group-hover:scale-110 transition-transform">
                          <Upload className="w-6 h-6 text-[var(--primary-brand)]" />
                        </div>
                        <p className="text-sm font-medium text-gray-500">
                          {isDragging ? 'Drop image here' : 'Drag & drop image here, or click to upload'}
                        </p>
                      </>
                    )}
                  </div>
                  <input
                    type="file"
                    ref={editFileInputRef}
                    onChange={handleEditImageChange}
                    accept="image/*"
                    className="hidden"
                  />
                </div>
              </div>

              <div className="p-6 border-t border-gray-100 bg-[#F9FAFB] flex gap-3">
                <Button
                  variant="outline"
                  className="flex-1 h-12 rounded-xl border-gray-200 font-semibold"
                  onClick={() => setShowEditModal(false)}
                  disabled={isUpdating}
                >
                  Cancel
                </Button>
                <Button
                  variant="theme"
                  className="flex-1 h-12 rounded-xl font-semibold shadow-lg shadow-[var(--primary-brand)]/20"
                  onClick={handleUpdateCategory}
                  disabled={isUpdating}
                >
                  {isUpdating ? 'Updating...' : 'Save Changes'}
                </Button>
              </div>
            </div>
          </div>
        )}

        {/* Request Category Modal */}
        <RequestCategoryModal
          isOpen={showRequestModal}
          onClose={() => setShowRequestModal(false)}
          onSuccess={() => {
            fetchCategories(1, searchQuery);
            router.push('/category-requests');
          }}
          rawType={rawType}
          storeId={userInfo?.restaurant_id?._id}
        />
      </main>
    </DashboardLayout>
  );
}
