'use client';

import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import ImagePicker from '../../components/image-picker';
import { PostMediaData } from '@/lib/database';
import { Controller, useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import z from 'zod';
import { IconPicker } from '../../components/icon-picker';
import { useEffect } from 'react';
import { toast } from 'sonner';

const schema = z.object({
  icon: z.any().nullable(),
  title: z.string().trim().min(1),
  text: z.string().trim().min(1),
  media: z.any().nullable()
});

type TimelineItemForm = z.infer<typeof schema>;

const defaultValues: TimelineItemForm = {
  icon: null,
  title: '',
  text: '',
  media: null
};

type Props = {
  open: boolean;
  onOpenChange: (v: boolean) => void;
  initialValues?: TimelineItemForm;
  onSubmit: (data: TimelineItemForm) => void;
  title: string;
};

export function TimelineItemDialog({
  open,
  onOpenChange,
  initialValues,
  onSubmit,
  title
}: Props) {
  const { register, reset, control, handleSubmit } = useForm<TimelineItemForm>({
    resolver: zodResolver(schema),
    defaultValues: initialValues ?? defaultValues,
    mode: 'onChange'
  });
  useEffect(() => {
    if (open) {
      reset(initialValues ?? defaultValues);
    }
  }, [open, initialValues, reset]);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{title}</DialogTitle>
        </DialogHeader>

        <div className='flex max-h-[70vh] flex-col gap-3 overflow-y-auto'>
          <Controller
            name='icon'
            control={control}
            render={({ field }) => (
              <IconPicker value={field.value} onChange={field.onChange} />
            )}
          />
          <Input
            className='shrink-0'
            placeholder='Title'
            {...register('title')}
          />
          <Controller
            name='media'
            control={control}
            render={({ field }) => (
              <div className='rounded-lg border p-3'>
                <ImagePicker
                  ids={field.value?.map((item: PostMediaData) => item.id) || []}
                  onSelect={field.onChange}
                />
              </div>
            )}
          />
          <Textarea rows={4} placeholder='Text' {...register('text')} />

          <DialogFooter>
            <Button
              type='button'
              variant='outline'
              onClick={() => {
                onOpenChange(false);
                reset(defaultValues);
              }}
            >
              Cancel
            </Button>
            <Button
              type='button'
              onClick={handleSubmit(onSubmit, () => {
                toast.error('Please fill Title and Text fields');
              })}
            >
              Save
            </Button>
          </DialogFooter>
        </div>
      </DialogContent>
    </Dialog>
  );
}
