'use client';

import React, { useState, useEffect, useRef } from 'react';

import DashboardLayout from '@/app/dashboard/layout';
import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Plus } from 'lucide-react';
import { useGlobalContext } from '@/context/Provider';
import dynamic from 'next/dynamic';
import 'react-quill/dist/quill.snow.css';
import apis from '@/utils/apis';


const ReactQuill = dynamic(() => import('react-quill'), {
  ssr: false,
  loading: () => <div className="h-[150px] w-full bg-gray-50 animate-pulse rounded-xl border border-gray-100" />
});

const grocerySchema = z.object({
  name: z.string().min(2, 'Name is required'),
  category: z.string().min(2, 'Category is required'),
  stock: z.coerce.number().min(0, 'Stock must be non-negative').max(99999, 'Stock cannot exceed 5 digits'),
  quantity: z.coerce.number().min(0, 'Quantity must be non-negative').max(99999, 'Quantity cannot exceed 5 digits'),
  unit: z.string().min(1, 'Unit is required'),
  price: z.coerce.number().min(0, 'Price must be non-negative').max(99999, 'Price cannot exceed 5 digits'),
  description: z.string().optional(),
  image: z.any().optional(),
  barcode_id: z.string().optional(),
});

type GroceryValues = z.infer<typeof grocerySchema>;


export default function AddGroceryPage() {
  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 fileInputRef = useRef<HTMLInputElement>(null);
  const [previewImage, setPreviewImage] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [allCategories, setAllCategories] = useState<any[]>([]);

  const form = useForm<GroceryValues>({
    resolver: zodResolver(grocerySchema),
    defaultValues: {
      name: '',
      category: '',
      stock: 0,
      quantity: 0,
      unit: '',
      price: 0,
      description: '',
      barcode_id: '',
    },
  });

  const fetchCategories = async () => {
    try {
      const res = await apis.category.get();
      if (res?.data) {
        setAllCategories(res.data);
      }
    } catch (error) {
      console.error('Error fetching categories:', error);
    }
  };

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

  const barcodeRef = React.useRef<string>('');
  const lastKeyTimeRef = React.useRef<number>(0);

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Shift' || e.key === 'Control' || e.key === 'Alt' || e.key === 'Meta') {
        return;
      }

      const activeElement = document.activeElement;
      const isInput = activeElement && (activeElement.tagName === 'INPUT' || activeElement.tagName === 'TEXTAREA');

      if (activeElement && (activeElement as HTMLInputElement).placeholder === 'Barcode ID') {
        return;
      }

      if (isInput) {
        return;
      }

      const currentTime = Date.now();
      if (currentTime - lastKeyTimeRef.current > 50) {
        barcodeRef.current = '';
      }
      lastKeyTimeRef.current = currentTime;

      if (e.key === 'Enter') {
        if (barcodeRef.current.length > 2) {
          e.preventDefault();
          e.stopPropagation();
          form.setValue('barcode_id', barcodeRef.current);
          barcodeRef.current = '';
          Toast.success('Barcode scanned successfully');
        }
      } else {
        if (e.key.length === 1) {
          barcodeRef.current += e.key;
        }
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => {
      window.removeEventListener('keydown', handleKeyDown);
    };
  }, [form, Toast]);

  const onImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onloadend = () => {
        setPreviewImage(reader.result as string);
        form.setValue('image', file);
      };
      reader.readAsDataURL(file);
    }
  };

  const onSubmit = async (values: GroceryValues) => {
    setIsSubmitting(true);
    try {
      let imageUrl = '';

      if (values.image instanceof File) {
        const uploadRes = await apis.Common.uploadSingle('file', values.image);
        if (uploadRes?.key) {
          imageUrl = uploadRes.key;
        }
      }

      let category_id = '';
      const selectedCat = allCategories.find(c => c.category_name === values.category);
      if (selectedCat) {
        category_id = selectedCat._id;
      }

      const payload = {
        type: rawType,
        category_id,
        name: values.name,
        description: values.description,
        quantity: values.quantity.toString(),
        unit: values.unit,
        price: values.price,
        imageUrl,
        stock: values.stock,
        barcode_id: values.barcode_id || '',
      };

      const res = await apis.Item.add(payload);
      if (res?.success) {
        Toast.success(res.message || `${typeLabel} item added successfully`);
        router.push('/grocery');
      } else {
        Toast.error(res?.message || 'Failed to add item');
      }
    } catch (error: any) {
      Toast.error(error || `Error adding ${typeLabel.toLowerCase()} item`);
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <DashboardLayout>
      <main className="flex-1 bg-gray-50 p-6 overflow-y-auto">
        <div className="w-full max-w-4xl mx-auto bg-white rounded-3xl shadow-sm border border-gray-100 p-8">
          <h1 className="text-2xl font-bold mb-8">Add {typeLabel} Item</h1>

          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
              <div className="space-y-3">
                <label className="text-sm font-medium text-gray-700">{typeLabel} Image</label>
                <input
                  type="file"
                  ref={fileInputRef}
                  className="hidden"
                  accept="image/*"
                  onChange={onImageChange}
                />
                <div
                  className="w-28 h-28 rounded-2xl border-2 border-dashed border-gray-200 flex flex-col items-center justify-center cursor-pointer hover:border-gray-300 transition-all bg-[#F9FAFB] overflow-hidden"
                  onClick={() => fileInputRef.current?.click()}
                >
                  {previewImage ? (
                    <img src={previewImage} alt="Preview" className="w-full h-full object-cover" />
                  ) : (
                    <>
                      <Plus className="w-7 h-7 text-gray-400 mb-1" />
                      <span className="text-[10px] font-semibold text-gray-400">Upload</span>
                    </>
                  )}
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <FormField
                  control={form.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Name <span className="text-red-500">*</span></FormLabel>
                      <FormControl>
                        <Input placeholder={`${typeLabel} Name`} {...field} className="h-11 bg-[#F9FAFB] border-gray-100 rounded-xl" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="category"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Category <span className="text-red-500">*</span></FormLabel>
                      <FormControl>
                        <select
                          {...field}
                          className="h-11 w-full bg-[#F9FAFB] border border-gray-100 rounded-xl px-3 text-sm focus:outline-none"
                        >
                          <option value="">Select Category</option>
                          {allCategories.map((cat, index) => {
                            const name = cat.category_name || cat.name || 'Unnamed';
                            return (
                              <option key={cat._id || index} value={name}>
                                {name}
                              </option>
                            );
                          })}
                        </select>
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="stock"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Stock <span className="text-red-500">*</span></FormLabel>
                      <FormControl>
                        <Input
                          type="number"
                          placeholder="Stock"
                          {...field}
                          onChange={(e) => {
                            const value = e.target.value;
                            if (value.length <= 5) {
                              field.onChange(e);
                            }
                          }}
                          className="h-11 bg-[#F9FAFB] border-gray-100 rounded-xl"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <FormField
                  control={form.control}
                  name="quantity"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Quantity <span className="text-red-500">*</span></FormLabel>
                      <FormControl>
                        <Input
                          type="number"
                          placeholder="Quantity"
                          {...field}
                          onChange={(e) => {
                            const value = e.target.value;
                            if (value.length <= 5) {
                              field.onChange(e);
                            }
                          }}
                          className="h-11 bg-[#F9FAFB] border-gray-100 rounded-xl"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="unit"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Unit <span className="text-red-500">*</span></FormLabel>
                      <FormControl>
                        <Input placeholder="Unit" {...field} className="h-11 bg-[#F9FAFB] border-gray-100 rounded-xl" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="price"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Price <span className="text-red-500">*</span></FormLabel>
                      <FormControl>
                        <Input
                          type="number"
                          placeholder="Price"
                          {...field}
                          onChange={(e) => {
                            const value = e.target.value;
                            if (value.length <= 5) {
                              field.onChange(e);
                            }
                          }}
                          className="h-11 bg-[#F9FAFB] border-gray-100 rounded-xl"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <FormField
                  control={form.control}
                  name="barcode_id"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Barcode ID</FormLabel>
                      <FormControl>
                        <Input placeholder="Barcode ID" {...field} className="h-11 bg-[#F9FAFB] border-gray-100 rounded-xl" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              <FormField
                control={form.control}
                name="description"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Description</FormLabel>
                    <FormControl>
                      <div onKeyDownCapture={(e) => e.stopPropagation()}>
                        <ReactQuill
                          theme="snow"
                          defaultValue={field.value || ''}
                          onChange={(content) => field.onChange(content)}
                          modules={{
                            toolbar: [
                              [{ header: [1, 2, false] }],
                              ['bold', 'italic', 'underline', 'strike'],
                              [{ list: 'ordered' }, { list: 'bullet' }],
                              ['link', 'clean'],
                            ],
                          }}
                          className="bg-[#F9FAFB] rounded-xl overflow-hidden"
                          placeholder="Description"
                        />
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <div className="flex gap-4 pt-4">
                <Button
                  type="submit"
                  variant="theme"
                  className="flex-1 h-11 rounded-xl text-base font-semibold"
                  disabled={isSubmitting}
                >
                  {isSubmitting ? 'Adding...' : `Add ${typeLabel}`}
                </Button>
                <Button
                  type="button"
                  variant="outline"
                  className="flex-1 h-11 rounded-xl text-base font-semibold border-gray-200"
                  onClick={() => router.push('/grocery')}
                >
                  Cancel
                </Button>
              </div>
            </form>
          </Form>
        </div>
      </main>
    </DashboardLayout>
  );
}
