'use client';
import React, { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import {
  Form,
  FormField,
  FormItem,
  FormLabel,
  FormControl,
  FormMessage
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { ArrowLeft, Edit, Trash2, Upload } from 'lucide-react';
import apis, { BUCKET_ROOT } from '@/utils/apis';
import { useGlobalContext } from '@/context/Provider';
import DashboardLayout from '@/app/dashboard/layout';
import DeleteDialog from '@/components/ui/deleteModal';
import { formatDateStringToUTC, formatUTCToDateString } from '@/lib/utils';


const getTodayDate = () => {
  const today = new Date();
  const year = today.getFullYear();
  const month = String(today.getMonth() + 1).padStart(2, '0');
  const day = String(today.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

const formSchema = z.object({
  title: z
    .string()
    .min(1, 'Title is required')
    .max(25, 'Title must be under 25 characters'),
  description: z
    .string()
    .min(1, 'Description is required')
    .max(55, 'Description must be under 55 characters'),
  image: z.string().min(1, 'Image is required'),
  start_date: z.string().min(1, 'Start date is required').refine(
    (date) => {
      const selectedDate = new Date(date);
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      return selectedDate >= today;
    },
    { message: 'Start date cannot be in the past' }
  ),
  end_date: z.string().min(1, 'End date is required')
}).refine(
  (data) => {
    const start = new Date(data.start_date);
    const end = new Date(data.end_date);
    return end >= start;
  },
  {
    message: 'End date must be equal to or after start date',
    path: ['end_date']
  }
).refine(
  (data) => {
    const selectedDate = new Date(data.end_date);
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    return selectedDate >= today;
  },
  {
    message: 'End date cannot be in the past',
    path: ['end_date']
  });

type FormValues = z.infer<typeof formSchema>;
interface BannerItem {
  _id: string;
  banner_url: string;
  title: string;
  description: string;
  start_date: string;
  end_date: string;
  is_active: boolean;
}

const Banner = () => {
  const [banners, setBanners] = useState<BannerItem[]>([]);
  const { userInfo, Toast } = useGlobalContext();
  const [image, setImage] = useState('');
  const [loading, setLoading] = useState(false);
  const [showPreview, setShowPreview] = useState(false);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [selectedBannerId, setSelectedBannerId] = useState<string | null>(null);
  const [isEdit, setIsEdit] = useState(false);
  const form = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      title: '',
      description: '',
      image: '',
      start_date: '',
      end_date: ''
    },
    mode: 'onChange'
  });

  const fetchBanners = async () => {
    try {
      const response = await apis.Banner.getBanner();

      if (response?.banners) {
        setBanners(response.banners);
      } else {
        Toast.error('No banners found.');
      }
    } catch (error) {
      Toast.error('Failed to fetch banners.');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    const restaurant_id = userInfo?.restaurant_id?._id;
    if (restaurant_id) {
      fetchBanners();
    }
  }, [userInfo?.restaurant_id?._id]);

  const watchValues = form.watch();

  const handleUploadImage = async (file: File) => {
    try {
      const response = await apis.Common.uploadFile('file', file);
      if (!response?.image_url) throw new Error('Invalid upload response');
      setImage(response.image_url);
      form.setValue('image', response.image_url, { shouldValidate: true });
    } catch (error) {
      Toast.error('Image upload failed.');
    }
  };

  const onSubmit = async (data: FormValues) => {
    setLoading(true);
    try {
      const payload = {
        restaurant_id: userInfo?.restaurant_id?._id,
        banner_url: data.image,
        title: data.title,
        description: data.description,
        start_date: formatDateStringToUTC(data.start_date),
        end_date: formatDateStringToUTC(data.end_date, true),
        is_active: true
      };

      await apis.Banner.addBanner(payload);

      form.reset();
      setImage('');
      setShowPreview(false);
      fetchBanners();
      Toast.success('Banner saved successfully.');
    } catch (err: any) {
      Toast.error(err?.message || 'Something went wrong');
    } finally {
      setLoading(false);
    }
  };

  const isPreviewDisabled =
    !watchValues.title || !watchValues.description || !watchValues.image;
  const isSaveDisabled = !form.formState.isValid || loading;

  const getBannerByID = async (bannerId: string) => {
    try {
      setSelectedBannerId(bannerId);
      const res = await apis.Banner.getBannerById(bannerId); // Fetch from API
      const banner = res?.banner; // Get the first banner

      if (banner) {
        // Set form values
        form.setValue('title', banner.title);
        form.setValue('description', banner.description);
        form.setValue('start_date', formatUTCToDateString(banner.start_date));
        form.setValue('end_date', formatUTCToDateString(banner.end_date));
        form.setValue('image', banner.banner_url);

        // Set image for preview
        setImage(banner.banner_url);

        // Show the form in edit mode
        setIsEdit(true);
      } else {
        Toast.error('Banner not found');
      }
    } catch (error) {
      console.error('Failed to fetch banner data:', error);
      Toast.error('Failed to load banner data');
    }
  };

  const handleEdit = async (data: FormValues) => {
    setLoading(true);

    try {
      const payload = {
        restaurant_id: userInfo?.restaurant_id?._id,
        banner_url: data.image,
        title: data.title,
        description: data.description,
        start_date: formatDateStringToUTC(data.start_date),
        end_date: formatDateStringToUTC(data.end_date, true)
        // is_active: true
      };

      await apis.Banner.editBanner(selectedBannerId, payload);

      form.reset();
      setImage('');
      setShowPreview(false);
      setIsEdit(false);
      fetchBanners();
      Toast.success('Banner Edited successfully.');
    } catch (err: any) {
      Toast.error(err?.message || 'Something went wrong');
    } finally {
      setLoading(false);
    }
  };
  const openDeleteDialog = (id: string) => {
    setSelectedBannerId(id);
    setDeleteDialogOpen(true);
  };

  const closeDeleteDialog = () => {
    setSelectedBannerId(null);
    setDeleteDialogOpen(false);
  };

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

    try {
      const apiRes = await apis.Banner.delBanner(selectedBannerId);
      if (apiRes) {
        Toast.success('Banner Deleted Successfully');
        fetchBanners();
        closeDeleteDialog();
      }
    } catch (err) {
      Toast.error(err);
    }
  };

  return (
    <div className="h-full w-full overflow-y-auto bg-white p-6 pb-24">
      {banners.filter((banner: any) => banner.is_active).length > 0 && (
        <div className="mb-10">
          <h2 className="mb-4 text-lg font-semibold">All Banners</h2>
          <div className="grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3">
            {banners
              .filter((banner: any) => banner.is_active)
              .map((banner: any) => (
                <div
                  key={banner._id}
                  className="relative overflow-hidden rounded-lg border shadow-md transition hover:shadow-lg"
                >
                  <img
                    src={`${BUCKET_ROOT}${banner.banner_url}`}
                    alt={banner.title}
                    className="h-48 w-full object-cover"
                  />
                  <div className="bg-gray-50 p-5">
                    <h3 className="mb-1 text-lg font-semibold text-gray-800">
                      {banner.title}
                    </h3>
                    <p className="mb-3 text-sm text-gray-600">
                      {banner.description}
                    </p>
                    <div className="mb-4 space-y-1 text-xs text-gray-500">
                      <p>
                        Start: {formatUTCToDateString(banner.start_date)}
                      </p>
                      <p>End: {formatUTCToDateString(banner.end_date)}</p>
                      <p>
                        Status:{' '}
                        <span className="font-medium text-green-600">Active</span>
                      </p>
                    </div>

                    {/* Buttons */}
                    <div className="flex ">
                      <button
                        onClick={() => getBannerByID(banner._id)}
                        className="rounded p-2 text-green-500 transition hover:bg-green-600/10"
                        title="Edit"
                      >
                        <Edit size={18} />
                      </button>
                      <button
                        onClick={() => openDeleteDialog(banner._id)}
                        className="rounded p-2 text-red-600 transition hover:bg-red-600/10"
                        title="Delete"
                      >
                        <Trash2 size={18} />
                      </button>
                    </div>
                    <DeleteDialog
                      isOpen={deleteDialogOpen}
                      onClose={closeDeleteDialog}
                      handleDelete={handleDelete}
                      title="Delete Banner"
                      description="Are you sure you want to delete this banner? This action cannot be undone."
                    />
                  </div>
                </div>
              ))}
          </div>
        </div>
      )}

      {isEdit && (
        <div className="mx-auto max-w-6xl">
          <div className="flex items-center gap-1">
            <div>
              <button
                onClick={() => {
                  setIsEdit(false);
                  form.reset();
                  setImage('');
                }}
                className="mb-2 flex items-center text-sm text-gray-600 transition hover:text-black"
              >
                <ArrowLeft className="mr-2 h-5 w-5" />
              </button>
            </div>

            <div className="mb-2 text-lg font-semibold">Edit Banner</div>
          </div>

          <Form {...form}>
            <form
              onSubmit={form.handleSubmit(handleEdit)}
              className="flex flex-col gap-6 md:flex-row"
            >
              {/* CARD 1 - IMAGE UPLOAD */}
              <div className="flex-1 rounded-lg border bg-gray-50 p-6 shadow-sm">
                <FormLabel>Upload Banner Image</FormLabel>
                <div className="rounded-lg border-2 border-dashed border-gray-300 p-6">
                  {image ? (
                    <div className="flex flex-col items-center">
                      <img
                        src={image}
                        alt="Preview"
                        className="mb-2 max-h-[200px] w-full rounded-lg object-contain"
                      />
                      <button
                        type="button"
                        className="text-sm text-red-500 underline hover:text-red-500"
                        onClick={() => {
                          setImage('');
                          form.setValue('image', '', { shouldValidate: true });
                        }}
                      >
                        Clear
                      </button>
                    </div>
                  ) : (
                    <div className="flex flex-col items-center">
                      <Upload className="mb-2 h-8 w-8 text-gray-400" />
                      <label className="cursor-pointer">
                        <span className="text-[var(--primary-brand)]">+ Upload photo</span>
                        <input
                          type="file"
                          className="hidden"
                          accept=".jpg,.jpeg,.png"
                          onChange={async (e) =>
                            e.target.files?.[0] &&
                            (await handleUploadImage(e.target.files[0]))
                          }
                        />
                      </label>
                      <p className="mt-1 text-sm text-gray-500">
                        Supported: .jpg .jpeg .png
                      </p>
                    </div>
                  )}
                </div>
              </div>

              {/* CARD 2 - FORM FIELDS */}
              <div className="flex-1 space-y-4 rounded-lg border bg-gray-50 p-6 shadow-sm">
                <FormField
                  name="title"
                  control={form.control}
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Title</FormLabel>
                      <FormControl>
                        <div>
                          <Input
                            {...field}
                            placeholder="Enter title"
                            maxLength={50}
                          />
                        </div>
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  name="description"
                  control={form.control}
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Description</FormLabel>
                      <FormControl>
                        <div>
                          <Input
                            {...field}
                            placeholder="Enter description"
                            maxLength={100}
                          />
                        </div>
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <div className="flex flex-col md:flex-row md:space-x-4">
                  <FormField
                    name="start_date"
                    control={form.control}
                    render={({ field }) => (
                      <FormItem className="w-full">
                        <FormLabel>Start Date</FormLabel>
                        <FormControl>
                          <Input type="date" {...field} min={getTodayDate()} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    name="end_date"
                    control={form.control}
                    render={({ field }) => (
                      <FormItem className="w-full">
                        <FormLabel>End Date</FormLabel>
                        <FormControl>
                          <Input type="date" {...field} min={form.watch('start_date') || getTodayDate()} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>

                <div className="flex justify-between gap-4 pt-2">
                  <Button
                    type="button"
                    className="w-full"
                    variant={'theme'}
                    onClick={() => setShowPreview(true)}
                    disabled={isPreviewDisabled}
                  >
                    Preview
                  </Button>

                  <Button
                    type="submit"
                    // disabled={isSaveDisabled}
                    className="w-full"
                    variant={'theme'}
                  >
                    {loading ? 'Saving...' : 'Save'}
                  </Button>
                </div>
              </div>
            </form>
          </Form>

          {/* Preview Section */}
          {showPreview && (
            <div className="mt-10">
              <h2 className="mb-4 text-lg font-semibold">Banner Preview</h2>
              <div className="relative h-[250px] w-full max-w-6xl overflow-hidden rounded-lg shadow-lg">
                <img
                  src={image}
                  alt="Banner Preview"
                  className="h-full w-full object-cover"
                />
                <div className="absolute inset-0 ml-20 flex items-center justify-start">
                  <div className=" max-w-[60%] rounded-l-lg p-6">
                    <h3 className="break-words text-2xl font-bold text-white">
                      {watchValues.title}
                    </h3>
                    <p className="mt-2 break-words text-sm text-white">
                      {watchValues.description}
                    </p>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      )}

      {!isEdit && (
        <div className="mx-auto max-w-6xl">
          <div className="mb-2 text-lg font-semibold">Add Banner</div>
          <Form {...form}>
            <form
              onSubmit={form.handleSubmit(onSubmit)}
              className="flex flex-col gap-6 md:flex-row"
            >
              {/* CARD 1 - IMAGE UPLOAD */}
              <div className="flex-1 rounded-lg border bg-gray-50 p-6 shadow-sm">
                <FormLabel>Upload Banner Image</FormLabel>
                <div className="rounded-lg border-2 border-dashed border-gray-300 p-6">
                  {image ? (
                    <div className="flex flex-col items-center">
                      <img
                        src={image}
                        alt="Preview"
                        className="mb-2 max-h-[200px] w-full rounded-lg object-contain"
                      />
                      <button
                        type="button"
                        className="text-sm text-red-500 underline hover:text-red-500"
                        onClick={() => {
                          setImage('');
                          form.setValue('image', '', { shouldValidate: true });
                        }}
                      >
                        Clear
                      </button>
                    </div>
                  ) : (
                    <div className="flex flex-col items-center">
                      <Upload className="mb-2 h-8 w-8 text-gray-400" />
                      <label className="cursor-pointer">
                        <span className="text-[var(--primary-brand)]">+ Upload photo</span>
                        <input
                          type="file"
                          className="hidden"
                          accept=".jpg,.jpeg,.png"
                          onChange={async (e) =>
                            e.target.files?.[0] &&
                            (await handleUploadImage(e.target.files[0]))
                          }
                        />
                      </label>
                      <p className="mt-1 text-sm text-gray-500">
                        Supported: .jpg .jpeg .png
                      </p>
                    </div>
                  )}
                </div>
              </div>

              {/* CARD 2 - FORM FIELDS */}
              <div className="flex-1 space-y-4 rounded-lg border bg-gray-50 p-6 shadow-sm">
                <FormField
                  name="title"
                  control={form.control}
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Title</FormLabel>
                      <FormControl>
                        <div>
                          <Input
                            {...field}
                            placeholder="Enter title"
                            maxLength={50}
                          />
                        </div>
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  name="description"
                  control={form.control}
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Description</FormLabel>
                      <FormControl>
                        <div>
                          <Input
                            {...field}
                            placeholder="Enter description"
                            maxLength={100}
                          />
                        </div>
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <div className="flex flex-col md:flex-row md:space-x-4">
                  <FormField
                    name="start_date"
                    control={form.control}
                    render={({ field }) => (
                      <FormItem className="w-full">
                        <FormLabel>Start Date</FormLabel>
                        <FormControl>
                          <Input type="date" {...field} min={getTodayDate()} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    name="end_date"
                    control={form.control}
                    render={({ field }) => (
                      <FormItem className="w-full">
                        <FormLabel>End Date</FormLabel>
                        <FormControl>
                          <Input type="date" {...field} min={form.watch('start_date') || getTodayDate()} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>

                <div className="flex justify-between gap-4 pt-2">
                  <Button
                    type="button"
                    className="w-full"
                    variant={'theme'}
                    onClick={() => setShowPreview(true)}
                    disabled={isPreviewDisabled}
                  >
                    Preview
                  </Button>

                  <Button
                    type="submit"
                    disabled={isSaveDisabled}
                    className="w-full"
                    variant={'theme'}
                  >
                    {loading ? 'Saving...' : 'Save'}
                  </Button>
                </div>
              </div>
            </form>
          </Form>

          {/* Preview Section */}
          {showPreview && (
            <div className="mt-10">
              <h2 className="mb-4 text-lg font-semibold">Banner Preview</h2>
              <div className="relative h-[250px] w-full max-w-6xl overflow-hidden rounded-lg shadow-lg">
                <img
                  src={image}
                  alt="Banner Preview"
                  className="h-full w-full object-cover"
                />
                <div className="absolute inset-0 ml-20 flex items-center justify-start">
                  <div className=" max-w-[60%] rounded-l-lg p-6">
                    <h3 className="break-words text-2xl font-bold text-white">
                      {watchValues.title}
                    </h3>
                    <p className="mt-2 break-words text-sm text-white">
                      {watchValues.description}
                    </p>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
};

export default function JobAutomationPage() {
  return (
    <DashboardLayout>
      <Banner />
    </DashboardLayout>
  );
}
