'use client';

import React from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Plus, Pencil, Trash2, ArrowLeft, 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 { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Textarea } from '@/components/ui/textarea';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { MultiImages } from '@/components/common/MultipleDropzone';
import { cn } from '@/lib/utils';

interface FoodItem {
  _id: string;
  name: string;
  description: string;
  discounted_price?: number;
  image: string[];
  food_type: string;
  is_available: boolean;
  category_id: string;
}

interface Category {
  _id: string;
  category_name: string;
  category_image: string;
}

const addItemSchema = z.object({
  name: z.string().min(2, 'Item name is required'),
  food_type: z.enum(['veg', 'non_veg', 'egg'], {
    required_error: 'Please select food type',
  }),
  description: z.string().min(10, 'Description must be at least 10 characters'),
  image: z.array(z.record(z.any())).min(3, 'At least 3 images are required'),
});

type AddItemFormValues = z.infer<typeof addItemSchema>;

const AddOrEditItemModal = ({
  open,
  onClose,
  categoryId,
  onSuccess,
  editData,
}: {
  open: boolean;
  onClose: () => void;
  categoryId: string | null;
  onSuccess: () => void;
  editData?: FoodItem | null;
}) => {
  const { Toast, userInfo } = useGlobalContext();
  const [loading, setLoading] = React.useState(false);
  const [fetchingDetails, setFetchingDetails] = React.useState(false);

  const form = useForm<AddItemFormValues>({
    resolver: zodResolver(addItemSchema),
    defaultValues: {
      name: '',
      food_type: undefined,
      description: '',
      image: [],
    },
  });

  const fetchItemDetails = async (itemId: string) => {
    try {
      setFetchingDetails(true);
      const params = new URLSearchParams({
        food_id: itemId,
      });
      const apiRes = await apis.FoodList.detail(params);
      const itemData = apiRes?.data?.[0];

      if (itemData) {
        form.reset({
          name: itemData.name,
          food_type: itemData.food_type as any,
          description: itemData.description,
          image:
            itemData.image?.map((img: string) => ({
              id: img,
              url: img,
              fullUrl: img.startsWith('http') ? img : `${BUCKET_ROOT}${img}`,
              name: img,
            })) || [],
        });
      }
    } catch (error) {
      console.error('Error fetching item details:', error);
      Toast.error('Failed to load item details');
    } finally {
      setFetchingDetails(false);
    }
  };

  React.useEffect(() => {
    if (open && editData?._id) {
      fetchItemDetails(editData._id);
    } else if (open && !editData) {
      form.reset({
        name: '',
        food_type: undefined,
        description: '',
        image: [],
      });
    }
  }, [open, editData]);

  const handleImages = (data: any) => {
    form.setValue('image', data);
    form.trigger('image');
  };

  const onSubmit = async (data: AddItemFormValues) => {
    if (!categoryId) {
      Toast.error('Category ID is missing');
      return;
    }

    try {
      setLoading(true);

      const payload = {
        category_id: categoryId,
        name: data.name,
        food_type: data.food_type,
        description: data.description,
        image: data?.image?.map((img) => img.id) || [],
      };

      if (editData) {
        // UPDATE item
        const apiRes = await apis.Food.update(payload, editData._id);
        if (apiRes?.data || apiRes?.success) {
          Toast.success(apiRes?.message || 'Food item updated successfully');
          onSuccess();
          onClose();
        } else {
          Toast.error(apiRes?.message || apiRes?.error || 'Failed to update food item');
        }
      } else {
        // ADD item
        const apiRes = await apis.Food.add(payload, userInfo?.restaurant_id?._id);
        if (apiRes?.data || apiRes?.success) {
          Toast.success(apiRes?.message || 'Food item added successfully');
          form.reset();
          onSuccess();
          onClose();
        } else {
          Toast.error(apiRes?.message || apiRes?.error || 'Failed to add food item');
        }
      }
    } catch (error: any) {
      console.error('Error saving item:', error);
      Toast.error(error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="max-w-md p-0 overflow-hidden">
        <DialogHeader className="px-6 pt-6 pb-2 border-b">
          <DialogTitle className="text-lg font-semibold">
            {editData ? 'Edit Item' : 'Add Item'}
          </DialogTitle>
        </DialogHeader>

        {fetchingDetails ? (
          <div className="flex justify-center items-center py-20">
            <Loader loading={fetchingDetails} />
          </div>
        ) : (
          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col max-h-[80vh]">
              <div className="flex-1 overflow-y-auto px-6 py-4 space-y-4">
                {/* Item Name */}
                <FormField
                  control={form.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Item Name</FormLabel>
                      <FormControl>
                        <Input placeholder="Enter item name" {...field} className="h-10" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                {/* Food Type */}
                <FormField
                  control={form.control}
                  name="food_type"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Food Type</FormLabel>
                      <Select onValueChange={field.onChange} value={field.value}>
                        <FormControl>
                          <SelectTrigger className="h-10">
                            <SelectValue placeholder="Select food type" />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value="veg">Veg</SelectItem>
                          <SelectItem value="non_veg">Non-Veg</SelectItem>
                          <SelectItem value="egg">Egg</SelectItem>
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                {/* Description */}
                <FormField
                  control={form.control}
                  name="description"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Item Description</FormLabel>
                      <FormControl>
                        <Textarea
                          placeholder="Enter Item Description..."
                          {...field}
                          className="min-h-[80px] resize-none"
                          maxLength={200}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                {/* Images */}
                <FormField
                  control={form.control}
                  name="image"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Item Image</FormLabel>
                      <FormControl>
                        <MultiImages addImages={handleImages} images={field.value} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              {/* Action Buttons */}
              <div className="px-6 py-4 border-t flex gap-3 bg-white">
                <Button
                  type="button"
                  variant="outline"
                  onClick={onClose}
                  className="flex-1 h-10"
                  disabled={loading || fetchingDetails}
                >
                  Cancel
                </Button>
                <Button
                  type="submit"
                  className="flex-1 h-10 bg-[var(--primary-brand)] hover:bg-[var(--primary-brand)] text-white"
                  disabled={loading || fetchingDetails}
                >
                  {loading ? 'Saving...' : editData ? 'Update Item' : 'Add Item'}
                </Button>
              </div>
            </form>
          </Form>
        )}
      </DialogContent>
    </Dialog>
  );
};

const CateringFoodItems: React.FC = () => {
  const [foodItems, setFoodItems] = React.useState<FoodItem[]>([]);
  const [category, setCategory] = React.useState<Category | null>(null);
  const [loading, setLoading] = React.useState(false);
  const [selectedFood, setSelectedFood] = React.useState<FoodItem | null>(null);
  const [openConfirm, setOpenConfirm] = React.useState(false);
  const [searchQuery, setSearchQuery] = React.useState('');
  const [showModal, setShowModal] = React.useState(false);
  const [editData, setEditData] = React.useState<FoodItem | null>(null);

  const { Toast, userInfo } = useGlobalContext();
  const router = useRouter();
  const searchParams = useSearchParams();
  const categoryId = searchParams.get('categoryId');
  const categoryName = searchParams.get('categoryName');

  const fetchFoodItems = async () => {
    if (!categoryId) return;
    try {
      setLoading(true);
      const params = new URLSearchParams({
        restaurant_id: userInfo?.restaurant_id?._id,
        category_id: categoryId,
        page: '1',
        limit: '100',
      });
      const apiRes = await apis.FoodList.get(params);
      setFoodItems(apiRes?.data || []);
    } catch {
      Toast.error('Failed to load food items');
    } finally {
      setLoading(false);
    }
  };

  React.useEffect(() => {
    if (!userInfo?.restaurant_id?._id || !categoryId) return;

    fetchFoodItems();
    if (categoryName) {
      setCategory({ _id: categoryId, category_name: categoryName, category_image: '' });
    }
  }, [categoryId, categoryName, userInfo]);

  const handleDelete = async () => {
    if (!selectedFood) return;
    try {
      setLoading(true);
      await apis.Food.delete(selectedFood._id);
      Toast.success('Food item deleted');
      setOpenConfirm(false);
      fetchFoodItems();
    } catch {
      Toast.error('Failed to delete food item');
    } finally {
      setLoading(false);
    }
  };

  const handleAvailability = async (item: FoodItem) => {
    try {
      const apiRes = await apis.Food.available(
        {},
        `${item._id}?status=${!item.is_available}`
      );
      Toast.success(`Item ${!item.is_available ? 'marked as available' : 'marked as unavailable'}`);
      fetchFoodItems();
    } catch (error) {
      Toast.error('Failed to update availability');
    }
  };

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

  const filteredFoodItems = foodItems.filter((item) =>
    item.name.toLowerCase().includes(searchQuery.toLowerCase())
  );

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

  return (
    <div className="w-full mx-auto">
      {/* Header */}
      <div className="mb-6 flex items-center gap-4">
        <Button variant="ghost" onClick={() => router.back()} className="p-2">
          <ArrowLeft className="h-5 w-5" />
        </Button>
        <h2 className="text-2xl font-semibold text-gray-900">{category?.category_name}</h2>
      </div>

      {/* Search + Add */}
      <div className="mb-6 flex 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) => setSearchQuery(e.target.value)}
            placeholder="Search food items"
            className="h-9 w-full rounded-md border pl-9 pr-4 text-sm font-medium"
          />
        </div>
        <Button
          onClick={() => {
            setEditData(null);
            setShowModal(true);
          }}
          className="bg-[var(--primary-brand)] hover:bg-[var(--primary-brand)] text-white font-semibold px-4"
        >
          Add Item
        </Button>
      </div>

      {/* Food Items */}
      {filteredFoodItems.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-20 text-gray-500">
          <p className="text-lg font-medium">No food items found</p>
          <p className="text-sm mt-1">
            {searchQuery ? 'Try adjusting your search' : 'Add your first item to get started'}
          </p>
        </div>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-5">
          {filteredFoodItems.map((item) => (
            <Card key={item._id} className="border rounded-xl shadow-sm hover:shadow-md">
              <CardContent className="p-4 space-y-3">
                <div className="w-full h-40 bg-gray-100 rounded-lg overflow-hidden">
                  <img
                    src={getImageUrl(item.image?.[0])}
                    alt={item.name}
                    className="w-full h-full object-cover"
                  />
                </div>
                <div>
                  <div className="flex justify-between">
                    <h3 className="font-semibold text-base text-gray-900">{item.name}</h3>
                    {!item.is_available && (
                      <Badge variant="outline" className="text-xs text-red-500 border-red-500">
                        Unavailable
                      </Badge>
                    )}
                  </div>
                  <p className="text-sm text-gray-600 line-clamp-2 mt-1">{item.description}</p>
                  <Badge
                    className={`mt-2 ${item.food_type === 'veg' ? 'bg-green-500' : 'bg-red-500'
                      } text-white`}
                  >
                    {item.food_type === 'veg' ? 'Veg' : item.food_type === 'non_veg' ? 'Non-Veg' : 'Egg'}
                  </Badge>
                </div>

                {/* Edit and Delete Actions */}
                <div className="flex justify-between items-center border-t pt-3 mt-3">
                  <Button
                    variant="ghost"
                    size="sm"
                    className="text-orange-500 hover:text-orange-500 hover:bg-transparent px-2"
                    onClick={() => {
                      setEditData(item);
                      setShowModal(true);
                    }}
                  >
                    <Pencil className="h-4 w-4 mr-1" />
                    Edit
                  </Button>

                  <span className="text-gray-300">|</span>

                  <Button
                    variant="ghost"
                    size="sm"
                    className="text-red-500 hover:text-red-500 hover:bg-transparent px-2"
                    onClick={() => {
                      setSelectedFood(item);
                      setOpenConfirm(true);
                    }}
                  >
                    <Trash2 className="h-4 w-4 mr-1" />
                    Delete
                  </Button>
                </div>

                {/* Availability Toggle */}
                <div className="flex w-full items-center justify-between pt-3 border-t">
                  <span className="cursor-pointer text-sm font-semibold text-gray-900">
                    Availability{' '}
                    <span className="text-xs font-normal text-gray-400">
                      ({item.is_available ? 'In stock' : 'Out of stock'})
                    </span>
                  </span>
                  <div
                    className={cn(
                      'relative h-6 w-12 cursor-pointer rounded-full transition-colors',
                      item.is_available ? 'bg-emerald-500' : 'bg-red-400'
                    )}
                    onClick={() => handleAvailability(item)}
                  >
                    <div
                      className={cn(
                        'absolute top-0.5 h-5 w-5 rounded-full bg-white transition-all',
                        item.is_available ? 'left-[26px]' : 'left-0.5'
                      )}
                    />
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      {/* Add/Edit Modal */}
      <AddOrEditItemModal
        open={showModal}
        onClose={() => {
          setShowModal(false);
          setEditData(null);
        }}
        categoryId={categoryId}
        onSuccess={fetchFoodItems}
        editData={editData}
      />

      {/* Delete Confirmation */}
      <AlertDialog open={openConfirm} onOpenChange={setOpenConfirm}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Food Item</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to delete{' '}
              <span className="font-semibold">{selectedFood?.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 CateringFoodItemsPage() {
  return (
    <DashboardLayout>
      <div className="h-full overflow-y-auto p-6 bg-gray-50">
        <CateringFoodItems />
      </div>
    </DashboardLayout>
  );
}