'use client';

import React from 'react';
import { useState } from 'react';
import { useForm, useFieldArray } from 'react-hook-form';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import AuthLayout from '@/components/layout/layout';
import authBanner from '@/assets/images/AuthImages/address.png';
import {
  Form,
  FormField,
  FormItem,
  FormLabel,
  FormControl,
  FormMessage
} from '@/components/ui/form';
import { Button } from '@/components/ui/button';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import { MultiImages } from '@/components/common/MultipleDropzone';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { useRouter, useSearchParams } from 'next/navigation';
import { Minus, Plus } from 'lucide-react';
import apis from '@/utils/apis';
import { toUTC } from '@/lib/utils';

// ------------------ Validation ------------------
const formSchema = z.object({
  startTime: z.string().min(1, 'Start time is required'),
  endTime: z.string().min(1, 'End time is required'),
  items: z.array(
    z.object({
      menuType: z.string().min(1, 'Please select a menu type'),
      restaurantPhotos: z.array(z.string()).min(3, 'At least 3 images are required'),
      foodName: z.string().min(1, 'Food name is required'),
      foodDescription: z.string().min(1, 'Food description is required'),
      price: z
        .string()
        .regex(/^\d+$/, 'Price must be a valid number')
        .min(1, 'Price is required'),
      estimatedTime: z
        .string()
        .regex(/^\d+$/, 'Estimated time must be a valid number')
        .min(1, 'Estimated time is required')
    })
  ),
  orderAcceptLimit: z.number().min(1, 'Order accept limit must be greater than 0')
});

type MenuForm = z.infer<typeof formSchema>;

// ------------------ Component ------------------
const AddItemForm = () => {
  const router = useRouter();
  const searchParams = useSearchParams();
  const mealType = searchParams?.get('mealType');
  const serviceId = searchParams?.get('id');

  const form = useForm<MenuForm>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      startTime: '',
      endTime: '',
      items: [
        {
          menuType: 'veg',
          restaurantPhotos: [],
          foodName: '',
          foodDescription: '',
          price: '',
          estimatedTime: ''
        }
      ],
      orderAcceptLimit: 10
    }
  });

  const { fields, append, remove } = useFieldArray({
    control: form.control,
    name: 'items'
  });

  // ------------------ Submit ------------------
  const onSubmit = async (data: MenuForm) => {

    const payload = {
      home_cooked_service_id: serviceId,
      start_time: toUTC(data?.startTime),
      end_time: toUTC(data?.endTime),
      menu: data?.items?.map((item) => ({
        image: item?.restaurantPhotos || [],
        name: item?.foodName,
        price: Number(item?.price),
        food_type: item?.menuType,
        estimated_time: Number(item?.estimatedTime),
        description: item?.foodDescription
      })),
      order_accept_limit: data.orderAcceptLimit
    };

    try {
      const res = await apis.HomeCooked.addHomeCookedMenu(payload);
      sessionStorage.setItem('food', 'complete');
      router.push(`/auth/complete-profile`);

    } catch (err) {
      console.error('API Error:', err);
      alert('Failed to add menu.');
    }
  };


  // ------------------ Helpers ------------------
  const getButtonText = () => {
    switch (mealType) {
      case 'breakfast':
        return 'Add Breakfast';
      case 'lunch':
        return 'Add Lunch';
      case 'dinner':
        return 'Add Dinner';
      default:
        return 'Add Item';
    }
  };

  const handleAddMore = () => {
    append({
      menuType: 'veg',
      restaurantPhotos: [],
      foodName: '',
      foodDescription: '',
      price: '',
      estimatedTime: ''
    });
  };

  const handleDelete = (index: number) => remove(index);

  const incrementOrderLimit = () => form.setValue('orderAcceptLimit', form.getValues('orderAcceptLimit') + 1);
  const decrementOrderLimit = () => form.getValues('orderAcceptLimit') > 1 && form.setValue('orderAcceptLimit', form.getValues('orderAcceptLimit') - 1);

  // ------------------ UI ------------------
  return (
    <section className="no-scrollbar h-[75vh] w-full overflow-y-auto">
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">

          {/* Time Section */}
          <h3 className="mt-4 mb-4 text-lg font-semibold text-black">Add Time</h3>
          <div className="flex space-x-4">
            <div className="flex-1">
              <FormField
                name="startTime"
                control={form.control}
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Start Time</FormLabel>
                    <FormControl>
                      <Input type="time" {...field} className="h-[48px] bg-white" />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
            <div className="flex-1">
              <FormField
                name="endTime"
                control={form.control}
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>End Time</FormLabel>
                    <FormControl>
                      <Input type="time" {...field} className="h-[48px] bg-white" />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
          </div>

          {/* Order Accept Limit */}
          <h3 className="mt-8 mb-4 text-lg font-semibold text-black">Order Accept Limit</h3>
          <div className="mb-4 flex items-center justify-between rounded-lg border p-4 shadow-sm">
            <div className="text-sm font-medium text-gray-900">Order Accept Limit</div>
            <div className="flex items-center gap-4 rounded-md border bg-yellow-50 px-3 py-1.5">
              <Button type="button" variant="ghost" size="icon" onClick={decrementOrderLimit}>
                <Minus className="h-4 w-4" />
              </Button>
              <span className="text-base font-semibold">{form.watch('orderAcceptLimit')}</span>
              <Button type="button" variant="ghost" size="icon" onClick={incrementOrderLimit}>
                <Plus className="h-4 w-4" />
              </Button>
            </div>
          </div>

          {/* Add Menu */}
          <h2 className="mt-4 text-xl font-semibold text-black">Add Menu</h2>
          {fields.map((item, index) => (
            <div key={item.id} className="space-y-6 mt-2">

              {/* Menu Type */}
              <FormField
                name={`items.${index}.menuType`}
                control={form.control}
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Select Menu Type</FormLabel>
                    <FormControl>
                      <Select onValueChange={field.onChange} value={field.value}>
                        <SelectTrigger className="w-full h-11 bg-white">
                          <SelectValue placeholder="Select a menu type" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="veg">Veg</SelectItem>
                          <SelectItem value="non_veg">Non-Veg</SelectItem>
                          <SelectItem value="egg">Egg</SelectItem>
                          <SelectItem value="jain">Jain</SelectItem>
                        </SelectContent>
                      </Select>
                    </FormControl>
                  </FormItem>
                )}
              />

              {/* Photos */}
              <FormField
                name={`items.${index}.restaurantPhotos`}
                control={form.control}
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Upload vendor photos</FormLabel>
                    <FormControl>
                      <MultiImages
                        addImages={(newImages: any[]) => field.onChange(newImages.map(img => img.fullUrl))}
                        images={field.value?.map((url: string) => ({ id: url, url })) || []}
                      />
                    </FormControl>
                  </FormItem>
                )}
              />

              {/* Food Name */}
              <FormField
                name={`items.${index}.foodName`}
                control={form.control}
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Food Name</FormLabel>
                    <FormControl>
                      <Input placeholder="Enter food name" {...field} className="h-[48px] bg-white" />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Description */}
              <FormField
                name={`items.${index}.foodDescription`}
                control={form.control}
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Food Description</FormLabel>
                    <FormControl>
                      <Textarea placeholder="Enter food description" {...field} className="h-[120px] bg-white" />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Price + Estimated Time */}
              <div className="flex space-x-4">
                <div className="flex-1">
                  <FormField
                    name={`items.${index}.price`}
                    control={form.control}
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Price</FormLabel>
                        <FormControl>
                          <Input placeholder="Enter price" {...field} className="h-[48px] bg-white" />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
                <div className="flex-1">
                  <FormField
                    name={`items.${index}.estimatedTime`}
                    control={form.control}
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Estimated Time (minutes)</FormLabel>
                        <FormControl>
                          <Input placeholder="Enter estimated time" {...field} className="h-[48px] bg-white" />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
              </div>

              {/* Delete */}
              {index > 0 && (
                <Button
                  type="button"
                  onClick={() => handleDelete(index)}
                  className="w-full h-11 text-red-500 border border-red-500 rounded-md hover:bg-transparent"
                >
                  Delete
                </Button>
              )}
            </div>
          ))}

          {/* Add More */}
          <Button type="button" onClick={handleAddMore} className="w-full h-11 text-yellow-500 border border-yellow-500 rounded-md">
            + Add More
          </Button>

          {/* Submit */}
          <Button type="submit" className="w-full h-11 theme-background btn-text-color text-white">
            {getButtonText()}
          </Button>
        </form>
      </Form>
    </section>
  );
};

// ------------------ Wrapper ------------------
export default function FormOne() {
  return (
    <AuthLayout
      title="Add your home-cooked Service"
      des="Access your account or create a new one."
      image={authBanner.src}
    >
      <AddItemForm />
    </AuthLayout>
  );
}
