'use client';

import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
  DialogDescription
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import { useForm, Controller, useWatch } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import z from 'zod';
import { useEffect } from 'react';
import { WidgetPosition } from '@/config/enums/tip-tap';
import { PostPicker } from '@/components/dashboard/post/post-picker';
import { Label } from '@/components/ui/label';
import { toast } from 'sonner';

const options = [
  {
    label: 'Default',
    value: WidgetPosition.CENTER
  },
  {
    label: 'Left column',
    value: WidgetPosition.LEFT_COL
  }
];

const schema = z.object({
  title: z.string().optional(),
  description: z.string().optional(),
  variant: z.string().min(1),
  postId: z.string().min(1)
});

type MapSettingsForm = z.infer<typeof schema>;

const defaultValues: MapSettingsForm = {
  title: '',
  description: '',
  variant: WidgetPosition.CENTER,
  postId: ''
};

type Props = {
  open: boolean;
  onOpenChange: (v: boolean) => void;
  initialValues: MapSettingsForm;
  onSubmit: (data: MapSettingsForm) => void;
};

export default function MapSettingsDialog({
  open,
  onOpenChange,
  initialValues,
  onSubmit
}: Props) {
  const { register, handleSubmit, reset, control } = useForm<MapSettingsForm>({
    resolver: zodResolver(schema),
    defaultValues: initialValues ?? defaultValues,
    mode: 'onChange'
  });

  const postId = useWatch({
    control,
    name: 'postId'
  });

  useEffect(() => {
    if (open) {
      reset(initialValues ?? defaultValues);
    }
  }, [open, initialValues, reset]);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Map settings</DialogTitle>
          <DialogDescription>Configure map appearance</DialogDescription>
        </DialogHeader>

        <div className='flex flex-col gap-2'>
          <Controller
            control={control}
            name='variant'
            render={({ field }) => (
              <Select value={field.value} onValueChange={field.onChange}>
                <SelectTrigger>
                  <SelectValue placeholder='Select variant' />
                </SelectTrigger>
                <SelectContent>
                  <SelectGroup>
                    {options.map((option) => (
                      <SelectItem key={option.value} value={option.value}>
                        {option.label}
                      </SelectItem>
                    ))}
                  </SelectGroup>
                </SelectContent>
              </Select>
            )}
          />
        </div>

        <div className='flex flex-col gap-3'>
          <Input placeholder='Widget title' {...register('title')} />
          <Textarea
            rows={4}
            placeholder='Widget description'
            {...register('description')}
          />
        </div>
        <div className='flex flex-wrap items-center justify-between gap-2'>
          <Label>
            {postId ? (
              <span>
                Post location has been chosen{' '}
                <span className='text-sm text-green-700'>✓</span>
              </span>
            ) : (
              <span>
                Choose post for setting location{' '}
                <span className='text-client-red text-lg'>*</span>
              </span>
            )}
          </Label>
          <Controller
            control={control}
            name='postId'
            render={({ field }) => (
              <PostPicker
                selected={field.value ? [field.value] : []}
                onSelect={(ids: string[]) => {
                  field.onChange(ids[0] ?? '');
                }}
              />
            )}
          />
        </div>
        <DialogFooter>
          <Button
            type='button'
            variant='outline'
            onClick={() => reset(defaultValues)}
          >
            Reset
          </Button>
          <Button
            type='button'
            onClick={handleSubmit(onSubmit, () => {
              toast.error('Please choose post location');
            })}
          >
            Save
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
