import React, { useEffect } from 'react'
import { useForm, Controller } from 'react-hook-form'
import {
  Box,
  Card,
  CardBody,
  CardHeader,
  Heading,
  Button,
  CloseButton,
  VStack,
  FormControl,
  FormLabel,
  FormHelperText,
  FormErrorMessage,
  Input,
  Flex,
  Icon,
  Text,
  Badge,
  useColorModeValue,
  HStack,
  Divider,
  SimpleGrid,
  Skeleton,
  SkeletonText,
  useStyleConfig
} from '@chakra-ui/react'
import { AddIcon, CheckIcon, WarningIcon, RepeatIcon } from '@chakra-ui/icons'
import { useTranslation } from 'react-i18next'
import { FaRobot } from 'react-icons/fa'
import dayjs from 'dayjs'
import { formatDate } from '../../../utils/dayjs-config'

import { dateToCalendarFormat } from '../../../utils/time'
import { Lesson } from '../../../__data__/model'
import { ErrorSpan } from '../style'

interface NewLessonForm {
  name: string
  date: string
}

interface LessonFormProps {
  lesson?: Partial<Lesson> | any // Разрешаем передавать как Lesson, так и AI-сгенерированный урок
  isLoading: boolean
  onCancel: () => void
  onSubmit: (lesson: Lesson) => void
  error?: string
  title: string
  nameButton: string
  aiSuggestions?: any[] // Список предложений от ИИ 
  isLoadingAiSuggestions?: boolean // Индикатор загрузки предложений
  onSelectAiSuggestion?: (suggestion: any) => void // Обработчик выбора предложения
  selectedAiSuggestion?: any // Выбранное предложение
  onRetryAiGeneration?: () => void // Функция для повторного запуска генерации
}

export const LessonForm = ({
  lesson,
  isLoading,
  onCancel,
  onSubmit,
  error,
  title,
  nameButton,
  aiSuggestions = [],
  isLoadingAiSuggestions = false,
  onSelectAiSuggestion = () => {},
  selectedAiSuggestion,
  onRetryAiGeneration = () => {}
}: LessonFormProps) => {
  const { t } = useTranslation()
  const isAiSuggested = lesson && !lesson._id && !lesson.id
  const aiHighlightColor = useColorModeValue('blue.100', 'blue.800')
  const suggestionBgColor = useColorModeValue('blue.50', 'blue.900')
  const suggestionHoverBgColor = useColorModeValue('blue.100', 'blue.800')
  const borderColor = useColorModeValue('blue.200', 'blue.700')
  const textSecondaryColor = useColorModeValue('gray.600', 'gray.400')
  
  const getNearestTimeSlot = () => {
    const now = new Date();
    const minutes = now.getMinutes();
    
    if (minutes < 30) {
      // Округляем до начала текущего часа
      now.setMinutes(0, 0, 0);
    } else {
      // Округляем до начала следующего часа
      now.setHours(now.getHours() + 1);
      now.setMinutes(0, 0, 0);
    }
    
    return dateToCalendarFormat(now.toISOString());
  };

  const {
    control,
    handleSubmit,
    reset,
    setValue,
    formState: { errors },
  } = useForm<NewLessonForm>({
    defaultValues: (lesson && {
      ...lesson,
      date: dateToCalendarFormat(lesson.date),
    }) || {
      name: '',
      date: getNearestTimeSlot(),
    },
  })

  // Рендерим скелетон для предложений ИИ
  const renderSkeletons = () => {
    return (
      <VStack spacing={3} align="stretch" mt={4}>
        <Skeleton height="20px" width="70%" />
        <SimpleGrid columns={{ base: 1, md: 2 }} spacing={3}>
          {[1, 2, 3, 4, 5, 6].map(idx => (
            <Skeleton key={idx} height="60px" borderRadius="md" />
          ))}
        </SimpleGrid>
      </VStack>
    )
  }

  // Применяем выбранное предложение к форме
  const handleSelectSuggestion = (suggestion) => {
    setValue('name', suggestion.name)
    setValue('date', dateToCalendarFormat(suggestion.date))
    onSelectAiSuggestion(suggestion)
  }

  return (
    <Card align="left" bg={isAiSuggested ? aiHighlightColor : undefined}>
      <CardHeader display="flex">
        <Flex align="center">
          <Heading as="h2" mt="0">
            {title}
          </Heading>
          {isAiSuggested && (
            <Badge colorScheme="blue" ml={2} display="flex" alignItems="center">
              <Icon as={FaRobot} mr={1} />
              <Text>{t('journal.pl.lesson.aiGenerated')}</Text>
            </Badge>
          )}
        </Flex>
        <CloseButton
          ml="auto"
          onClick={() => {
            reset()
            onCancel()
          }}
        />
      </CardHeader>
      <CardBody>
        <form onSubmit={handleSubmit(onSubmit)}>
          <VStack spacing="10" align="left">
            <Controller
              control={control}
              name="date"
              rules={{ required: t('journal.pl.common.required') }}
              render={({ field }) => (
                <FormControl>
                  <FormLabel>{t('journal.pl.lesson.form.date')}</FormLabel>
                  <Input
                    {...field}
                    required={false}
                    placeholder={t('journal.pl.lesson.form.datePlaceholder')}
                    size="md"
                    type="datetime-local"
                  />
                  {errors.date ? (
                    <FormErrorMessage>{errors.date?.message}</FormErrorMessage>
                  ) : (
                    <FormHelperText>{t('journal.pl.lesson.form.dateTime')}</FormHelperText>
                  )}
                </FormControl>
              )}
            />

            <Controller
              control={control}
              name="name"
              rules={{ required: t('journal.pl.common.required') }}
              render={({ field }) => (
                <FormControl isRequired isInvalid={Boolean(errors.name)}>
                  <FormLabel>{t('journal.pl.lesson.form.title')}</FormLabel>
                  <Input
                    {...field}
                    required={false}
                    placeholder={t('journal.pl.lesson.form.namePlaceholder')}
                    size="md"
                  />
                  {errors.name && (
                    <FormErrorMessage>{errors.name.message}</FormErrorMessage>
                  )}
                </FormControl>
              )}
            />
            <Box mt="10">
              <Button
                size="lg"
                type="submit"
                leftIcon={isAiSuggested ? <Icon as={FaRobot} /> : <AddIcon />}
                colorScheme={isAiSuggested ? "blue" : "blue"}
                isLoading={isLoading}
              >
                {nameButton}
              </Button>
            </Box>
          </VStack>

          {error && <ErrorSpan>{error}</ErrorSpan>}
        </form>

        {/* Блок с предложениями ИИ */}
        {((Array.isArray(aiSuggestions) && aiSuggestions.length > 0) || isLoadingAiSuggestions || typeof aiSuggestions === 'string') && (
          <>
            <Divider my={6} />
            
            <Flex align="center" mb={4}>
              <Icon as={FaRobot} color="blue.500" mr={2} />
              <Heading size="sm" color="blue.500">
                {t('journal.pl.lesson.aiSuggested')}
              </Heading>
              {!isLoadingAiSuggestions && Array.isArray(aiSuggestions) && (
                <Badge colorScheme="blue" ml={2}>
                  {aiSuggestions.length} {t('journal.pl.common.lesson').toLowerCase()}
                </Badge>
              )}
            </Flex>
            
            {isLoadingAiSuggestions ? (
              renderSkeletons()
            ) : typeof aiSuggestions === 'string' ? (
              <Box 
                p={4} 
                bg={useColorModeValue('red.50', 'red.900')} 
                color={useColorModeValue('red.600', 'red.200')}
                borderRadius="md"
                borderLeft="3px solid"
                borderLeftColor="red.500"
              >
                <Flex align="center" mb={2}>
                  <Icon as={WarningIcon} color="red.500" mr={2} />
                  <Text fontWeight="bold">{t('journal.pl.lesson.aiGenerationError')}</Text>
                </Flex>
                <Text fontSize="sm" mb={3}>{t('journal.pl.lesson.tryAgainLater')}</Text>
                <Button 
                  size="sm" 
                  colorScheme="red" 
                  variant="outline"
                  leftIcon={<RepeatIcon />}
                  onClick={onRetryAiGeneration}
                  isLoading={isLoadingAiSuggestions}
                >
                  {t('journal.pl.lesson.retryGeneration')}
                </Button>
              </Box>
            ) : (
              <>
                <Text fontSize="sm" color={textSecondaryColor} mb={4}>
                  {t('journal.pl.lesson.aiSuggestedDescription')}
                </Text>
                
                <SimpleGrid columns={{ base: 1, md: 2 }} spacing={4}>
                  {aiSuggestions.map((suggestion, index) => {
                    const isSelected = selectedAiSuggestion && 
                      selectedAiSuggestion.name === suggestion.name && 
                      selectedAiSuggestion.date === suggestion.date;
                      
                    return (
                      <Box 
                        key={`ai-suggestion-${index}`}
                        bg={isSelected ? suggestionHoverBgColor : suggestionBgColor}
                        p={3}
                        borderRadius="md"
                        borderLeft="3px solid"
                        borderLeftColor={isSelected ? "green.400" : borderColor}
                        cursor="pointer"
                        onClick={() => handleSelectSuggestion(suggestion)}
                        transition="all 0.2s"
                        _hover={{ 
                          bg: suggestionHoverBgColor,
                          transform: 'translateY(-2px)',
                          boxShadow: 'sm'
                        }}
                      >
                        <Flex justify="space-between" align="center" mb={1}>
                          <HStack>
                            <Icon as={FaRobot} color="blue.500" boxSize="3" />
                            <Text fontWeight="bold">{suggestion.name}</Text>
                          </HStack>
                          {isSelected && <CheckIcon color="green.400" />}
                        </Flex>
                        <Text fontSize="sm" color={textSecondaryColor}>
                          {formatDate(suggestion.date, 'DD.MM.YYYY HH:mm')}
                        </Text>
                      </Box>
                    );
                  })}
                </SimpleGrid>
              </>
            )}
          </>
        )}
      </CardBody>
    </Card>
  )
}
