'use client';

import React from 'react';
import { useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Plus, Pencil, Trash2, CircleX, Search } from 'lucide-react';
import apis, { BUCKET_ROOT } from '@/utils/apis';
import { useGlobalContext } from '@/context/Provider';
import Loader from '@/components/common/loader';
import DashboardLayout from '@/app/dashboard/layout';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Dialog, DialogContent } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import AddCategory from '../auth/menu/add/addCategory';

interface Category {
  _id: string;
  category_name: string;
  category_image: string;
  total_food_add?: number;
  total_item_add?: number;
  catering_services: boolean;
  vendor_id: string | null;
  is_default: boolean;
}

const CateringCategoriesList: React.FC = () => {
  const [categories, setCategories] = React.useState<Category[]>([]);
  const [loading, setLoading] = React.useState(false);
  const [selectedCategory, setSelectedCategory] = React.useState<Category | null>(null);
  const [openConfirm, setOpenConfirm] = React.useState(false);
  const [isOpen, setIsOpen] = React.useState(false);
  const [searchQuery, setSearchQuery] = React.useState('');
  const [image, setImage] = React.useState('');
  const [name, setName] = React.useState('');
  const [catId, setCatId] = React.useState('');

  const { Toast } = useGlobalContext();
  const router = useRouter();

  const fetchCategories = async () => {
    try {
      setLoading(true);
      const response = await apis.category.get('catering_services=true');

      if (response?.data) {
        setCategories(response.data);
      }
    } catch (error) {
      Toast.error(error);
    } finally {
      setLoading(false);
    }
  };

  React.useEffect(() => {
    fetchCategories();
  }, []);

  const onSearch = async (value: string) => {
    try {
      setSearchQuery(value);
      let urlSearchParam = new URLSearchParams();
      urlSearchParam.set('catering_services', 'true');
      if (value.length > 0) {
        urlSearchParam.set('search', value);
      }
      const apiRes = await apis.category.get(urlSearchParam.toString());
      setCategories(apiRes?.data);
    } catch (error) {
      Toast.error('Search failed');
    }
  };

  const addCategory = async () => {
    if (!name) {
      Toast.error('Enter valid name!');
      return;
    }
    if (!image) {
      Toast.error('Upload image!');
      return;
    }
    try {
      let payload = {
        category_name: name,
        category_image: image,
        catering_services: true
      };
      const apiRes: any = catId
        ? await apis.category.update(catId, payload)
        : await apis.category.add(payload);
      if (apiRes) {
        setName('');
        setImage('');
        setCatId('');
        setIsOpen(false);
        Toast.success(catId ? 'Category updated successfully' : 'Category added successfully');
        setTimeout(() => {
          fetchCategories();
        }, 300);
      }
    } catch (error) {
      Toast.error(error);
    }
  };

  const handleUpdate = (category: Category) => {
    setCatId(category._id);
    setIsOpen(true);
    setName(category.category_name);
    setImage(category.category_image);
  };

  const handleDelete = async () => {
    if (!selectedCategory) return;

    try {
      setLoading(true);
      await apis.category.delete(selectedCategory._id);
      Toast.success('Category deleted successfully!');
      setOpenConfirm(false);
      setSelectedCategory(null);
      setTimeout(() => {
        fetchCategories();
      }, 300);
    } catch (error) {
      Toast.error(error);
    } finally {
      setLoading(false);
    }
  };

  const getImageUrl = (image: string) => {
    if (image?.startsWith('http')) {
      return image;
    }
    return `${BUCKET_ROOT}${image}`;
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center h-64">
        <Loader loading={loading} />
      </div>
    );
  }

  return (
    <div className="w-full mx-auto">
      {/* Header with Search and Add */}
      <div className="mb-6 flex flex-col gap-4">
        <h2 className="text-2xl font-semibold text-gray-900">Categories</h2>

        <div className="flex flex-row gap-2">
          <div className="relative flex items-center bg-white flex-1">
            <Search stroke="var(--primary-brand)" className="absolute left-3 h-4 w-4" />
            <Input
              type="text"
              value={searchQuery}
              onChange={(e) => onSearch(e?.target?.value)}
              placeholder="Search any Category"
              className="h-9 w-full rounded-md border pl-9 pr-4 text-sm font-medium"
            />
          </div>
          <div
            onClick={() => {
              setCatId('');
              setName('');
              setImage('');
              setIsOpen(true);
            }}
            className="flex h-9 cursor-pointer items-center justify-center rounded-lg bg-[var(--primary-brand)] px-4 text-[16px] font-[600] text-white hover:bg-[var(--primary-brand)]"
          >
            Add+
          </div>
        </div>
      </div>

      {/* Categories Grid */}
      {categories.length === 0 ? (
        <div className="text-center py-12">
          <p className="text-gray-500 mb-4">No categories found.</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
          {categories.map((category) => (
            <Card
              key={category._id}
              className="relative group overflow-hidden border-2 border-gray-200 hover:border-yellow-500 transition-all duration-200 cursor-pointer"
              onClick={() => router.push(`/caterMenu/food-items?categoryId=${category._id}&categoryName=${encodeURIComponent(category.category_name)}`)}
            >
              <CardContent className="p-0">
                {/* Image */}
                <div className="relative w-full h-40 bg-gray-100">
                  <img
                    src={getImageUrl(category.category_image)}
                    alt={category.category_name}
                    className="w-full h-full object-cover"
                    onError={(e) => {
                      const target = e.target as HTMLImageElement;
                      target.src = '/placeholder-food.jpg';
                    }}
                  />

                  {/* Item Count Badge */}
                  {((category.total_item_add ?? category.total_food_add ?? 0) > 0) && (
                    <div className="absolute top-2 right-2 flex gap-1">
                      {[...Array(Math.min(category.total_item_add ?? category.total_food_add ?? 0, 3))].map((_, i) => (
                        <div
                          key={i}
                          className="w-2 h-2 rounded-full bg-[var(--primary-brand)]"
                        />
                      ))}
                    </div>
                  )}

                  {/* Edit/Delete Icons - Show only if vendor_id exists or no _id */}
                  {(category?.vendor_id || !category?._id) && (
                    <div className="absolute bottom-2 right-2 flex gap-2 opacity-0 group-hover:opacity-100 transition-opacity duration-200">
                      <div
                        className="bg-white rounded-full p-2 shadow-lg cursor-pointer hover:bg-gray-100"
                        onClick={(e) => {
                          e.stopPropagation();
                          handleUpdate(category);
                        }}
                      >
                        <Pencil className="h-4 w-4 text-green-600" />
                      </div>
                      <div
                        className="bg-white rounded-full p-2 shadow-lg cursor-pointer hover:bg-gray-100"
                        onClick={(e) => {
                          e.stopPropagation();
                          setSelectedCategory(category);
                          setOpenConfirm(true);
                        }}
                      >
                        <Trash2 className="h-4 w-4 text-red-600" strokeWidth={1} />
                      </div>
                    </div>
                  )}
                </div>

                {/* Category Name and Food Count */}
                <div className="p-3 bg-white">
                  <h3 className="font-semibold text-gray-900 text-sm truncate">
                    {category.category_name}
                  </h3>
                  {((category.total_item_add ?? category.total_food_add ?? 0) > 0) && (
                    <p className="text-xs text-gray-600 mt-1">
                      {category.total_item_add ?? category.total_food_add} Food item{(category.total_item_add ?? category.total_food_add ?? 0) > 1 ? 's' : ''} added
                    </p>
                  )}
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      {/* Add/Edit Category Dialog */}
      <Dialog open={isOpen} onOpenChange={() => setIsOpen(false)}>
        <DialogContent className="h-[400px] border-none bg-white">
          <div className="flex w-full flex-row items-center justify-between">
            <span className="text-[16px] font-[600]">
              {catId ? 'Edit Category' : 'Add Category'}
            </span>
            <CircleX
              className="cursor-pointer"
              onClick={() => setIsOpen(false)}
            />
          </div>
          <div className="w-full">
            <AddCategory
              setImage={setImage}
              setName={setName}
              cat_name={name}
              image={image}
            />
          </div>
          <Button
            className="theme-background btn-text-color h-11 w-full text-white"
            variant={'default'}
            onClick={addCategory}
          >
            Save
          </Button>
        </DialogContent>
      </Dialog>

      {/* Delete Confirmation Modal */}
      <AlertDialog open={openConfirm} onOpenChange={setOpenConfirm}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Category</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to delete{' '}
              <span className="font-semibold">{selectedCategory?.category_name}</span>? This action
              cannot be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>

          <AlertDialogFooter>
            <AlertDialogCancel onClick={() => setOpenConfirm(false)}>
              Cancel
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDelete}
              className="bg-red-500 hover:bg-red-600 text-white"
            >
              Delete
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
};

export default function CateringCategoriesPage() {
  return (
    <DashboardLayout>
      <div className="h-full overflow-y-auto p-6 bg-gray-50">
        <CateringCategoriesList />
      </div>
    </DashboardLayout>
  );
}