'use client';
import { Button } from '@/components/ui/button';
import React, { use, useEffect, useRef, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import Loader from '@/components/common/loader';
import AuthLayout from '@/components/layout/layout';
import { Icons } from '@/components/icons';
import burger from '@/assets/images/AuthImages/burger.jpg';
import cake from '@/assets/images/AuthImages/cake.jpg';
import { Plus, Search, Upload } from 'lucide-react';
import { ArrowLeft } from "lucide-react";

import noodles from '@/assets/images/AuthImages/noodles.jpg';
import { Avatar } from '@radix-ui/react-avatar';
import { AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Input } from '@/components/ui/input';
import UploadFile from '@/components/automation/uploadAutomation';
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader
} from '@/components/ui/dialog';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage
} from '@/components/ui/form';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import authBanner from '@/assets/images/AuthImages/menu.png';
import { Textarea } from '@/components/ui/textarea';
import AddCategory from '../add/addCategory';
import apis from '@/utils/apis';
import { useGlobalContext } from '@/context/Provider';
import toast from 'react-hot-toast';

const Login = (props: any) => {
  const searchParams = useSearchParams();
  const category = searchParams.get('category');
  const categoryName = searchParams.get('category_name');
  const restaurantType = searchParams.get('restaurant_type');
  const router = useRouter();
  const { userInfo } = useGlobalContext();
  const [options, setOptions] = useState<any>([
    {
      id: 1,
      name: '',
      type: '',
      itemPrice: '',
      itemDescription: '',
      itemImage: '',
      isDefault: true
    }
  ]);
  const { Toast, getProfile } = useGlobalContext();

  const isFoodCategory =
    userInfo?.restaurant_id?.type === 'food';

  const fileInputRefs = useRef<{ [key: number]: HTMLInputElement | null }>({});

  const isFormValid = () => {
    return options.every((option: any) => {
      const hasBasicFields =
        option.name?.trim().length > 0 &&
        parseFloat(option.itemPrice) > 0 &&
        option.itemDescription?.trim().length > 0 &&
        option.itemImage;

      // if it's a food category, `type` is required
      if (isFoodCategory) {
        return hasBasicFields && option.type;
      }

      // if it's not food, skip `type` check
      return hasBasicFields;
    });
  };

  const addOption = () => {
    setOptions([
      ...options,
      {
        id: options.length + 1,
        name: '',
        type: '',
        itemPrice: '',
        itemDescription: '',
        itemImage: '',
        isDefault: false
      }
    ]);
  };

  useEffect(() => {
    const resId: any = sessionStorage.getItem('resId');
    if (category) {
      getFoodList(resId, category);
    } else {
      const foodItems: any = JSON.parse(
        localStorage.getItem('category_foods') || '[]'
      );
      if (foodItems?.length > 0) {
        const mappedOptions = foodItems.map((item: any, index: any) => ({
          id: index + 1,
          name: item.title,
          type: item.food_type,
          itemPrice: parseFloat(item.price),
          itemDescription: item.description,
          itemImage: '',
          isDefault: index === 0
        }));

        setOptions(mappedOptions);
      }
    }
  }, []);

  const getFoodList = async (restaurantId: any, categoryId: any) => {
    try {
      let apiRes;

      if (restaurantType === 'home-cooked-meal') {
        // For home-cooked-meal, categoryId is actually the food item's _id
        apiRes = await apis.Food.getFoodById(categoryId);

        if (apiRes?.data) {
          const item = apiRes.data;
          const mappedOptions = [
            {
              id: 1,
              name: item.name,
              type: item.food_type,
              itemPrice: parseFloat(item.price),
              itemDescription: item.description,
              itemImage: item.image?.[0],
              isDefault: true,
              food_id: item._id
            }
          ];
          setOptions(mappedOptions);
          return;
        }
      } else {
        // For regular restaurants, use category_id to get list of foods
        const params = new URLSearchParams({
          restaurant_id: restaurantId,
          category_id: categoryId
        });
        apiRes = await apis.FoodList.get(params);

        if (apiRes?.data?.length > 0) {
          const mappedOptions = apiRes.data.map((item: any, index: any) => ({
            id: index + 1,
            name: item.name,
            type: item.food_type,
            itemPrice: parseFloat(item.price),
            itemDescription: item.description,
            itemImage: item.image?.[0],
            isDefault: index === 0,
            food_id: item._id
          }));
          setOptions(mappedOptions);
          return;
        }
      }

      // Fallback to localStorage if API calls don't return data
      const foodItems: any = JSON.parse(
        localStorage.getItem('category_foods') || '[]'
      );
      if (foodItems?.length > 0) {
        const mappedOptions = foodItems.map((item: any, index: any) => ({
          id: index + 1,
          name: item.title,
          type: item.food_type,
          itemPrice: parseFloat(item.price),
          itemDescription: item.description,
          itemImage: '',
          isDefault: index === 0
        }));

        setOptions(mappedOptions);
      }
    } catch (error) {
      // Toast.error(error);
      console.error('Error fetching food list:', error);
    }
  };

  const removeOption = (id: any) => {
    setOptions(options.filter((option: any) => option?.id !== id));
  };

  const handleSave = async () => {
    let resId: any = sessionStorage.getItem('resId');

    // Check if restaurant type is home-cooked-meal
    const isHomeCooked = restaurantType === 'home-cooked-meal';

    try {
      let apiRes;

      if (isHomeCooked) {
        // For home-cooked-meal: send each item individually to /food/{id}
        const promises = options.map(async (option: any) => {
          const singleItemPayload = {
            ...(category
              ? { category_id: category }
              : { category_name: categoryName }),
            name: option.name,
            food_type: option.type,
            price: parseFloat(option.itemPrice) || 0,
            description: option.itemDescription,
            image: option.itemImage
          };

          return await apis.Food.add(singleItemPayload, resId);
        });

        const results = await Promise.all(promises);

        // Store the food item IDs for future reference
        if (results.length > 0 && results[0]?.data?._id) {
          const foodIds = results.map((result) => result.data._id);
          sessionStorage.setItem(
            'homecooked_food_ids',
            JSON.stringify(foodIds)
          );
        }

        Toast.success('Food items added successfully!');
      } else {
        // For other restaurant types: send all items as bulk
        const items = options.map((option: any) => ({
          ...(category
            ? { category_id: category }
            : { category_name: categoryName }),
          name: option.name,
          food_type: option.type,
          price: parseFloat(option.itemPrice) || 0,
          description: option.itemDescription,
          image: option.itemImage,
          _id: option.food_id || null
        }));

        const payLoad = { items };
        apiRes = await apis.FoodList.addFoods(resId, payLoad);

        Toast.success('Food items added successfully!');
      }

      router.replace('/auth/menu/add');
    } catch (error) {
      Toast.error('Failed to add food items.');
      console.error(error);
    }
  };

  const handleFileSelect = (id: number) => {
    if (fileInputRefs.current[id]) {
      fileInputRefs.current[id]!.click();
    }
  };

  const handleFileChange = (
    event: React.ChangeEvent<HTMLInputElement>,
    optionId: number
  ) => {
    const file = event.target.files?.[0];
    if (!file) return;

    const maxFileSize = 5 * 1024 * 1024;
    const allowedTypes = ['image/jpeg', 'image/png', 'image/jpg'];

    if (!allowedTypes.includes(file.type)) return;
    if (file.size > maxFileSize) return;

    handleUploadImage(file, optionId);
  };

  const handleUploadImage = async (file: File, optionId: number) => {
    try {
      const apiRes = await apis.Common.uploadFile('file', file);
      if (!apiRes?.key) throw new Error('No image key returned');

      setOptions((prev: any) =>
        prev.map((option: any) =>
          option.id === optionId ? { ...option, itemImage: apiRes.key } : option
        )
      );

      Toast.success('Image uploaded successfully!');
    } catch (error) {
      Toast.error('Failed to upload image.');
    }
  };

  const updateOption = (id: number, field: string, value: any) => {
    const updated = options.map((opt: any) =>
      opt.id === id ? { ...opt, [field]: value } : opt
    );
    setOptions(updated);
  };

  useEffect(() => {
    getProfile();
  }, []);

  return (
    <>
      <div className="mb-4">
        <Button
          variant="theme"
          className="w-15 h-11"
          onClick={() => router.back()}
        >
          <ArrowLeft size={18} />
          Back
        </Button>

      </div>
      <div className="space-y-6">
        <div className="space-y-4">
          {options.map((option: any, index: number) => (
            <div
              key={option.id}
              className="space-y-4 rounded-xl border border-gray-100 bg-white p-5 shadow-sm"
            >
              {isFoodCategory && (
                <div className="flex flex-wrap gap-2">
                  {/* Veg */}
                  <Button
                    type="button"
                    variant="outline"
                    className={`rounded-lg border ${
                      option.type === 'veg'
                        ? 'border-green-500 bg-green-50 text-green-700 font-semibold'
                        : 'border-gray-200 hover:bg-gray-50'
                    }`}
                    onClick={() => updateOption(option.id, 'type', 'veg')}
                  >
                    <Icons.VegIcon />
                    <span style={{ color: '#248853' }}>Veg</span>
                  </Button>

                  {/* Non-Veg */}
                  <Button
                    type="button"
                    variant="outline"
                    className={`rounded-lg border ${
                      option.type === 'non_veg'
                        ? 'border-red-500 bg-red-50 text-red-700 font-semibold'
                        : 'border-gray-200 hover:bg-gray-50'
                    }`}
                    onClick={() => updateOption(option.id, 'type', 'non_veg')}
                  >
                    <Icons.NonVegIcon />
                    <span style={{ color: '#BF2A34' }}>Non Veg</span>
                  </Button>

                  {/* Egg */}
                  <Button
                    type="button"
                    variant="outline"
                    className={`rounded-lg border ${
                      option.type === 'egg'
                        ? 'border-[var(--primary-brand)] bg-orange-50 font-semibold'
                        : 'border-gray-200 hover:bg-gray-50'
                    }`}
                    onClick={() => updateOption(option.id, 'type', 'egg')}
                  >
                    <Icons.EggIcon />
                    <span style={{ color: 'var(--primary-brand)' }}>Egg</span>
                  </Button>

                  {/* Jain - only for home-cooked-meal */}
                  {restaurantType === 'home-cooked-meal' && (
                    <Button
                      type="button"
                      variant="outline"
                      className={`rounded-lg border ${
                        option.type === 'jain'
                          ? 'border-purple-500 bg-purple-50 font-semibold'
                          : 'border-gray-200 hover:bg-gray-50'
                      }`}
                      onClick={() => updateOption(option.id, 'type', 'jain')}
                    >
                      <Icons.JainIcon />
                      <span style={{ color: '#6B21A8' }}>Jain</span>
                    </Button>
                  )}
                </div>
              )}

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="text-xs font-medium text-gray-600 mb-1 block">Item Name</label>
                  <Input
                    placeholder="e.g. Butter Paneer"
                    className="w-full"
                    value={option.name}
                    onChange={(e) =>
                      updateOption(option.id, 'name', e.target.value)
                    }
                    maxLength={50}
                  />
                </div>

                <div>
                  <label className="text-xs font-medium text-gray-600 mb-1 block">Item Price</label>
                  <Input
                    placeholder="e.g. 250"
                    type="number"
                    className="w-full"
                    value={option.itemPrice}
                    onChange={(e) =>
                      updateOption(option.id, 'itemPrice', e.target.value)
                    }
                    maxLength={10}
                  />
                </div>
              </div>

              <div>
                <label className="text-xs font-medium text-gray-600 mb-1 block">Item Description</label>
                <Textarea
                  placeholder="Enter item description..."
                  value={option.itemDescription}
                  onChange={(e) =>
                    updateOption(option.id, 'itemDescription', e.target.value)
                  }
                  maxLength={120}
                  rows={2}
                  className="resize-none"
                />
              </div>

              {option.itemImage ? (
                <div className="relative flex h-[85px] items-center justify-center rounded-lg border-2 border-dashed border-gray-300 bg-gray-50/50 p-2">
                  <img
                    src={
                      option.itemImage.startsWith('http')
                        ? option.itemImage
                        : apis.BUCKET_ROOT + option.itemImage
                    }
                    alt="Preview"
                    className="h-14 w-14 rounded-lg object-cover shadow-sm"
                  />
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    className="absolute right-2 top-2 h-7 px-2 text-xs text-red-500 hover:bg-red-50 hover:text-red-600"
                    onClick={() => updateOption(option.id, 'itemImage', '')}
                  >
                    Change
                  </Button>
                </div>
              ) : (
                <div
                  className="w-full"
                  onClick={(e) => {
                    e.stopPropagation();
                  }}
                >
                  <div
                    className="flex h-[80px] w-full cursor-pointer flex-col items-center justify-center gap-1 rounded-lg border-2 border-dashed border-gray-300 bg-gray-50/50 text-sm text-gray-500 hover:border-gray-400 hover:bg-gray-50 transition-colors"
                    onClick={() => handleFileSelect(option.id)}
                  >
                    <div className="flex items-center gap-2">
                      <Upload className="h-4 w-4 text-[var(--primary-brand)]" />
                      <span className="font-medium text-gray-700">Upload item image</span>
                    </div>
                    <span className="text-xs text-gray-400">PNG, JPG up to 5MB</span>
                  </div>
                  <Input
                    type="file"
                    accept=".jpg,.jpeg,.png"
                    hidden
                    ref={(el) => (fileInputRefs.current[option.id] = el)}
                    onChange={(e) => handleFileChange(e, option.id)}
                    className="hidden"
                  />
                </div>
              )}

              <div className="flex justify-end pt-1">
                {option.isDefault ? (
                  <span className="text-xs font-semibold text-[var(--primary-brand)] bg-orange-50 px-2.5 py-1 rounded-full border border-orange-200">
                    Default option
                  </span>
                ) : (
                  <Button
                    variant="ghost"
                    size="sm"
                    className="h-7 text-xs text-red-500 hover:bg-red-50 hover:text-red-600"
                    onClick={() => removeOption(option.id)}
                  >
                    Remove Option
                  </Button>
                )}
              </div>

              {index !== options.length - 1 && (
                <div className="my-4 border-b border-gray-100" />
              )}
            </div>
          ))}
        </div>

        {restaurantType !== 'home-cooked-meal' && (
          <Button
            variant="ghost"
            className="w-full border-2 border-dashed border-[var(--primary-brand)]/20 text-[var(--primary-brand)] hover:text-[var(--primary-brand)]/80 hover:bg-[var(--primary-brand)]/5 hover:border-[var(--primary-brand)]/40 transition-colors"
            onClick={addOption}
          >
            <Plus className="mr-2 h-4 w-4" />
            ADD MORE OPTION
          </Button>
        )}

        <Button
          className="h-11 w-full"
          variant={'theme'} onClick={handleSave}
          disabled={!isFormValid()}
        >
          Save
        </Button>
      </div>
    </>
  );
};

export default function LoginPage(props: any) {
  return (
    <AuthLayout
      title={'Add Food Delivery Items'}
      des={'Add dishes, options, and prices to your food delivery menu.'}
      image={authBanner.src}
    >
      <Login {...props} />
    </AuthLayout>
  );
}
