'use client';
import React, { useEffect, useState, useRef } 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, Sparkles } 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()
    .max(50, 'Title must be under 50 characters')
    .optional()
    .or(z.literal('')),
  description: z
    .string()
    .max(100, 'Description must be under 100 characters')
    .optional()
    .or(z.literal('')),
  image: z.string().min(1, 'Image is required'),
  start_date: z.string().min(1, 'Start date is required'),
  end_date: z.string().min(1, 'End date is required')
}).superRefine((data, ctx) => {
  const todayStr = new Date().toISOString().split('T')[0];

  const getNormDate = (str?: string) => {
    if (!str) return '';
    return str.includes('T') ? str.split('T')[0] : str;
  };

  const startNorm = getNormDate(data.start_date);
  const endNorm = getNormDate(data.end_date);

  if (startNorm && startNorm < todayStr) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message: 'Start date cannot be in the past',
      path: ['start_date']
    });
  }

  if (endNorm && endNorm < todayStr) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message: 'End date cannot be in the past',
      path: ['end_date']
    });
  }

  if (startNorm && endNorm && endNorm < startNorm) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message: 'End date must be equal to or after start date',
      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 editFormRef = useRef<HTMLDivElement>(null);
  const form = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      title: '',
      description: '',
      image: '',
      start_date: '',
      end_date: ''
    },
    mode: 'onChange'
  });

  const getErrorMessage = (err: any, fallback: string) =>
    err?.response?.body?.message ||
    err?.response?.data?.message ||
    err?.message ||
    (typeof err === 'string' ? err : fallback);

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

      if (response?.banners) {
        setBanners(response.banners);
      } else {
        Toast.error('No banners found.');
      }
    } catch (error: any) {
      Toast.error(getErrorMessage(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: any) {
      Toast.error(getErrorMessage(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(getErrorMessage(err, 'Something went wrong'));
    } finally {
      setLoading(false);
    }
  };

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

  const cancelEdit = () => {
    setIsEdit(false);
    setSelectedBannerId(null);
    form.reset();
    setImage('');
    setShowPreview(false);
  };

  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
        const fullImg = banner.banner_url?.startsWith('http') ? banner.banner_url : `${BUCKET_ROOT}${banner.banner_url}`;
        setImage(fullImg);

        // Show the form in edit mode
        setIsEdit(true);

        // Smooth scroll to edit form so user immediately notices the edit section
        setTimeout(() => {
          editFormRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }, 100);
      } else {
        Toast.error('Banner not found');
      }
    } catch (error: any) {
      console.error('Failed to fetch banner data:', error);
      Toast.error(getErrorMessage(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);

      cancelEdit();
      fetchBanners();
      Toast.success('Banner updated successfully.');
    } catch (err: any) {
      Toast.error(getErrorMessage(err, '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: any) {
      Toast.error(getErrorMessage(err, 'Failed to delete banner'));
    }
  };

  return (
    <div className="h-full w-full overflow-y-auto bg-white p-6 pb-24">
      {banners.length > 0 && (
        <div className="mb-10">
          <h2 className="mb-4 text-lg font-semibold text-gray-900">All Banners</h2>
          <div className="grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3">
            {banners.map((banner: any) => {
              const isCurrentlyEditing = isEdit && selectedBannerId === banner._id;
              const bannerImageUrl = banner.banner_url?.startsWith('http')
                ? banner.banner_url
                : `${BUCKET_ROOT}${banner.banner_url}`;

              const rawStatus = banner.status || (banner.is_active ? 'active' : 'inactive');
              const statusLower = rawStatus.toLowerCase();
              const statusBadgeStyle =
                statusLower === 'active'
                  ? 'text-green-700 bg-green-50 border-green-200'
                  : statusLower === 'upcoming'
                  ? 'text-amber-700 bg-amber-50 border-amber-200'
                  : 'text-gray-700 bg-gray-50 border-gray-200';

              return (
                <div
                  key={banner._id}
                  className={`relative overflow-hidden rounded-xl transition-all duration-300 outline-none focus:outline-none ${
                    isCurrentlyEditing
                      ? 'border-2 border-orange-500 shadow-lg shadow-orange-500/10 bg-orange-50/20'
                      : 'border border-gray-200 shadow-md hover:shadow-lg'
                  }`}
                >
                  {isCurrentlyEditing && (
                    <div className="absolute top-2 right-2 z-10 flex items-center gap-1.5 rounded-full bg-orange-500 px-3 py-1 text-xs font-semibold text-white shadow-md animate-pulse">
                      <Edit size={12} />
                      <span>Editing Now</span>
                    </div>
                  )}
                  <img
                    src={bannerImageUrl}
                    alt={banner.title || 'Banner'}
                    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 flex items-center justify-between">
                      <span>{banner.title || 'Untitled Banner'}</span>
                    </h3>
                    {banner.description && (
                      <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 className="flex items-center gap-1.5 pt-1">
                        <span>Status:</span>
                        <span className={`px-2 py-0.5 rounded text-[11px] font-bold border capitalize ${statusBadgeStyle}`}>
                          {rawStatus}
                        </span>
                      </p>
                    </div>

                    {/* Buttons */}
                    <div className="flex gap-2">
                      <button
                        onClick={() => getBannerByID(banner._id)}
                        className={`rounded-lg p-2 transition outline-none focus:outline-none focus:ring-0 ${
                          isCurrentlyEditing
                            ? 'bg-orange-500 text-white font-medium'
                            : 'text-green-600 hover:bg-green-600/10'
                        }`}
                        title="Edit Banner"
                      >
                        <Edit size={18} />
                      </button>
                      <button
                        onClick={() => openDeleteDialog(banner._id)}
                        className="rounded-lg p-2 text-red-600 transition hover:bg-red-600/10"
                        title="Delete"
                      >
                        <Trash2 size={18} />
                      </button>
                    </div>
                  </div>
                </div>
              );
            })}
          </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>
      )}

      {isEdit && (
        <div ref={editFormRef} className="mx-auto max-w-6xl scroll-mt-8 pt-4">
          {/* Visual Edit Banner Alert / Notice */}
          <div className="mb-6 flex flex-wrap items-center justify-between gap-4 rounded-xl border border-orange-200 bg-gradient-to-r from-orange-50 via-amber-50 to-orange-50 p-4 shadow-sm">
            <div className="flex items-center gap-3">
              <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-orange-500 text-white shadow-sm">
                <Edit size={20} />
              </div>
              <div>
                <div className="flex items-center gap-2">
                  <h3 className="text-base font-bold text-gray-900">
                    Editing Banner
                  </h3>
                  <span className="rounded-full bg-orange-200/70 px-2.5 py-0.5 text-xs font-semibold text-orange-800">
                    Active Mode
                  </span>
                </div>
                <p className="text-xs text-gray-600 mt-0.5">
                  Modifying details for <span className="font-semibold text-orange-700">"{watchValues.title || 'Selected Banner'}"</span>. Make your changes below and click "Update Banner".
                </p>
              </div>
            </div>
            <div className="flex items-center gap-2">
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={cancelEdit}
                className="border-orange-300 bg-white text-gray-700 hover:bg-orange-100 hover:text-orange-900"
              >
                <ArrowLeft className="mr-1.5 h-4 w-4" /> Cancel Editing
              </Button>
            </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-xl border border-orange-200 bg-white p-6 shadow-sm ring-1 ring-orange-100">
                <FormLabel className="font-semibold text-gray-900">Upload Banner Image</FormLabel>
                <div className="mt-2 rounded-lg border-2 border-dashed border-orange-200 bg-orange-50/30 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 font-medium text-red-500 hover:underline"
                        onClick={() => {
                          setImage('');
                          form.setValue('image', '', { shouldValidate: true });
                        }}
                      >
                        Clear Image
                      </button>
                    </div>
                  ) : (
                    <div className="flex flex-col items-center">
                      <Upload className="mb-2 h-8 w-8 text-orange-400" />
                      <label className="cursor-pointer">
                        <span className="font-medium text-[var(--primary-brand)] hover:underline">+ 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-xl border border-orange-200 bg-white p-6 shadow-sm ring-1 ring-orange-100">
                <FormField
                  name="title"
                  control={form.control}
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="font-semibold text-gray-900">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 className="font-semibold text-gray-900">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 className="font-semibold text-gray-900">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 className="font-semibold text-gray-900">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={'outline'}
                    onClick={() => setShowPreview(true)}
                    disabled={isPreviewDisabled}
                  >
                    Preview
                  </Button>

                  <Button
                    type="submit"
                    className="w-full bg-orange-600 hover:bg-orange-700 text-white"
                  >
                    {loading ? 'Updating...' : 'Update Banner'}
                  </Button>
                </div>
              </div>
            </form>
          </Form>

          {/* Preview Section */}
          {showPreview && (
            <div className="mt-10">
              <h2 className="mb-4 text-lg font-semibold text-gray-900">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>
  );
}
