import { z } from 'zod/v4';
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { Box, TextField, Button, Rating } from '@mui/material';

const bookSchema = z.object({
  title: z
    .string()
    .min(4, 'Der Titel muss mindestens 4 Zeichen lang sein.')
    .max(25, 'Der Titel darf höchstens 25 Zeichen lang sein.'),
  author: z.string().min(1, 'Autor ist erforderlich.'),
  isbn: z.string().min(1, 'ISBN ist erforderlich.'),
  rating: z.number().min(0).max(5),
});

type Book = z.infer<typeof bookSchema>;

const BookForm: React.FC = () => {
  const {
    register,
    control,
    handleSubmit,
    formState: { errors },
  } = useForm<Book>({
    resolver: zodResolver(bookSchema),
    defaultValues: { title: '', author: '', isbn: '', rating: 0 },
  });

  function onSave(data: Book) {
    console.log('Gespeichert:', data);
  }

  return (
    <Box
      component="form"
      onSubmit={handleSubmit(onSave)}
      sx={{ maxWidth: 480 }}
    >
      <TextField
        label="Titel"
        id="title"
        margin="normal"
        fullWidth
        {...register('title')}
        error={!!errors.title}
        helperText={errors.title?.message}
      />

      <TextField
        label="Autor"
        id="author"
        margin="normal"
        fullWidth
        {...register('author')}
        error={!!errors.author}
        helperText={errors.author?.message}
      />

      <TextField
        label="ISBN"
        id="isbn"
        margin="normal"
        fullWidth
        {...register('isbn')}
        error={!!errors.isbn}
        helperText={errors.isbn?.message}
      />

      <Controller
        name="rating"
        control={control}
        render={({ field }) => (
          <Box sx={{ display: 'flex', alignItems: 'center', mt: 1, mb: 2 }}>
            <Box sx={{ mr: 2 }}>Bewertung</Box>
            <Rating
              value={typeof field.value === 'number' ? field.value : 0}
              onChange={(_, value) => field.onChange(value ?? 0)}
              precision={1}
              max={5}
            />
          </Box>
        )}
      />

      <Box sx={{ mt: 2 }}>
        <Button variant="contained" color="primary" type="submit">
          Speichern
        </Button>
      </Box>
    </Box>
  );
};

export default BookForm;
