import 'dayjs/locale/ru';
import dayjs from 'dayjs';
import { z as zod } from 'zod';
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { useMemo, useState, useCallback } from 'react';

// ----------------------------------------------------------------------

import { useRouter } from 'next/navigation';

import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog';
import Avatar from '@mui/material/Avatar';
import Switch from '@mui/material/Switch';
import Tooltip from '@mui/material/Tooltip';
import MenuItem from '@mui/material/MenuItem';
import IconButton from '@mui/material/IconButton';
import LoadingButton from '@mui/lab/LoadingButton';
import DialogTitle from '@mui/material/DialogTitle';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import InputAdornment from '@mui/material/InputAdornment';
import FormControlLabel from '@mui/material/FormControlLabel';

import { paths } from 'src/routes/paths';

import { createLiveKitRoom } from 'src/utils/livekit-api';

import { useGetStudents, useGetSubjects } from 'src/actions/calendar';

import { Iconify } from 'src/components/iconify';
import { Form, Field } from 'src/components/hook-form';

// ----------------------------------------------------------------------

dayjs.locale('ru');

// ----------------------------------------------------------------------

const DURATION_OPTIONS = [
  { value: 30, label: '30 минут' },
  { value: 45, label: '45 минут' },
  { value: 60, label: '1 час' },
  { value: 90, label: '1.5 часа' },
  { value: 120, label: '2 часа' },
];

export function CalendarForm({
  currentEvent,
  range,
  open,
  onClose,
  onCreateEvent,
  onUpdateEvent,
  onDeleteEvent,
}) {
  const router = useRouter();
  const { students } = useGetStudents();
  const { subjects } = useGetSubjects();
  const [joiningVideo, setJoiningVideo] = useState(false);

  const EventSchema = zod.object({
    client: zod.union([zod.string(), zod.number()]).refine((val) => !!val, 'Выберите ученика'),
    subject: zod.union([zod.string(), zod.number()]).refine((val) => !!val, 'Выберите предмет'),
    description: zod.string().max(5000).optional(),
    start_time: zod.any().refine((val) => val !== null, 'Выберите начало занятия'),
    duration: zod.number().min(1, 'Выберите длительность'),
    price: zod.coerce.number().min(0, 'Цена не может быть отрицательной'),
    is_recurring: zod.boolean().optional(),
  });

  const defaultValues = useMemo(() => {
    const start = currentEvent?.start || range?.start || new Date();
    return {
      client: currentEvent?.extendedProps?.client?.id || '',
      subject: currentEvent?.extendedProps?.mentor_subject?.id || '',
      description: currentEvent?.description || '',
      start_time: dayjs(start),
      duration: 60,
      price: 1500,
      is_recurring: false,
    };
  }, [currentEvent, range]);

  const methods = useForm({
    resolver: zodResolver(EventSchema),
    defaultValues,
  });

  const {
    reset,
    watch,
    control,
    handleSubmit,
    formState: { isSubmitting },
  } = methods;

  const values = watch();

  const onSubmit = handleSubmit(async (data) => {
    try {
      const startTime = dayjs(data.start_time);
      const endTime = startTime.add(data.duration, 'minute');

      // Формируем динамический title: Предмет - Преподаватель - Ученик #ID
      const selectedSubject = subjects.find(s => s.id === data.subject);
      const selectedStudent = students.find(s => s.id === data.client);
      
      const subjectName = selectedSubject?.name || selectedSubject?.subject_name || 'Урок';
      
      const studentFullName = selectedStudent?.user ? `${selectedStudent.user.last_name} ${selectedStudent.user.first_name}` : (selectedStudent?.full_name || 'Ученик');
      
      const mentorFullName = currentEvent?.extendedProps?.mentor ? `${currentEvent.extendedProps.mentor.last_name} ${currentEvent.extendedProps.mentor.first_name}` : 'Ментор';
      
      const lessonNumber = currentEvent?.id ? ` №${currentEvent.id}` : '';
      
      const displayTitle = `${subjectName} ${mentorFullName} - ${studentFullName}${lessonNumber}`.trim();

      const payload = {
        title: displayTitle,
        client: data.client,
        subject: data.subject,
        description: data.description,
        start_time: startTime.toISOString(),
        duration: data.duration,
        price: data.price,
        is_recurring: data.is_recurring,
      };

      if (currentEvent?.id) {
        await onUpdateEvent({ ...payload, id: currentEvent.id });
      } else {
        await onCreateEvent(payload);
      }
      onClose();
      reset();
    } catch (error) {
      console.error(error);
    }
  });

  const onJoinVideo = useCallback(async () => {
    if (!currentEvent?.id) return;
    setJoiningVideo(true);
    try {
      const room = await createLiveKitRoom(currentEvent.id);
      const token = room.access_token || room.token;
      router.push(`${paths.videoCall}?token=${encodeURIComponent(token)}&lesson_id=${currentEvent.id}`);
      onClose();
    } catch (e) {
      console.error('LiveKit join error', e);
    } finally {
      setJoiningVideo(false);
    }
  }, [currentEvent?.id, router, onClose]);

  const onDelete = useCallback(async () => {
    try {
      await onDeleteEvent(`${currentEvent?.id}`);
      onClose();
      reset();
    } catch (error) {
      console.error(error);
    }
  }, [currentEvent?.id, onDeleteEvent, onClose, reset]);

  return (
    <Dialog fullWidth maxWidth="xs" open={open} onClose={onClose}>
      <Form methods={methods} onSubmit={onSubmit}>
        <DialogTitle sx={{ p: 3 }}>
          {currentEvent?.id ? 'Редактировать занятие' : 'Создать занятие'}
        </DialogTitle>

        <DialogContent sx={{ p: 3, pb: 0, overflow: 'unset' }}>
          <Stack spacing={3}>
            
            <Field.Select name="client" label="Ученик *">
              <MenuItem value="" disabled>Выберите ученика</MenuItem>
              {students.map((student) => {
                const studentName = student.user?.full_name || 
                                    student.full_name || 
                                    (student.user?.first_name ? `${student.user.first_name} ${student.user.last_name || ''}` : '') ||
                                    student.email ||
                                    `ID: ${student.id}`;
                
                const studentAvatar = student.user?.avatar || student.avatar;
                const letter = studentName.charAt(0).toUpperCase();

                return (
                  <MenuItem key={student.id} value={student.id}>
                    <Stack direction="row" alignItems="center" spacing={1.5}>
                      <Avatar 
                        src={studentAvatar} 
                        sx={{ width: 24, height: 24, fontSize: 12 }}
                      >
                        {letter}
                      </Avatar>
                      <Box component="span">{studentName}</Box>
                    </Stack>
                  </MenuItem>
                );
              })}
            </Field.Select>

            <Field.Select name="subject" label="Предмет *">
              <MenuItem value="" disabled>Выберите предмет</MenuItem>
              {subjects.map((sub) => (
                <MenuItem key={sub.id} value={sub.id}>
                  {sub.name || sub.subject_name || sub.title || `Предмет ID: ${sub.id}`}
                </MenuItem>
              ))}
            </Field.Select>

            <Field.Text 
               name="description" 
               label="Описание" 
               placeholder="Дополнительная информация о занятии"
               multiline 
               rows={2} 
            />

            <Field.MobileDateTimePicker 
              name="start_time" 
              label="Начало занятия *" 
              format="DD.MM.YYYY HH:mm"
              ampm={false}
              slotProps={{
                toolbar: {
                  hidden: false,
                },
                actionBar: {
                  actions: ['clear', 'cancel', 'accept'],
                },
              }}
              localeText={{
                cancelButtonLabel: 'Отмена',
                okButtonLabel: 'ОК',
                clearButtonLabel: 'Очистить',
                todayButtonLabel: 'Сегодня',
                startLabel: 'Начало',
                endLabel: 'Конец',
                toolbarTitle: 'Выберите дату и время',
              }}
              sx={{ width: 1 }} 
            />

            <Stack direction="row" spacing={2}>
              <Field.Select name="duration" label="Длительность *">
                {DURATION_OPTIONS.map((option) => (
                  <MenuItem key={option.value} value={option.value}>
                    {option.label}
                  </MenuItem>
                ))}
              </Field.Select>

              <Field.Text
                name="price"
                label="Стоимость (₽) *"
                type="number"
                InputProps={{
                  startAdornment: (
                    <InputAdornment position="start">₽</InputAdornment>
                  ),
                }}
              />
            </Stack>

            <FormControlLabel
              control={
                <Controller
                  name="is_recurring"
                  control={control}
                  render={({ field }) => <Switch {...field} checked={field.value} />}
                />
              }
              label="Постоянное занятие (повторяется еженедельно)"
              sx={{ ml: 0 }}
            />
          </Stack>
        </DialogContent>

        <DialogActions sx={{ p: 3 }}>
          {currentEvent?.id && (
            <Tooltip title="Удалить">
              <IconButton onClick={onDelete} color="error">
                <Iconify icon="solar:trash-bin-trash-bold" />
              </IconButton>
            </Tooltip>
          )}

          <Box sx={{ flexGrow: 1 }} />

          {currentEvent?.id && currentEvent?.extendedProps?.status !== 'completed' && (
            <LoadingButton
              variant="soft"
              color="success"
              loading={joiningVideo}
              onClick={onJoinVideo}
              startIcon={<Iconify icon="solar:videocamera-record-bold" />}
            >
              Войти
            </LoadingButton>
          )}

          <Button variant="outlined" color="inherit" onClick={onClose}>
            Отмена
          </Button>

          <LoadingButton type="submit" variant="contained" loading={isSubmitting}>
            {currentEvent?.id ? 'Сохранить изменения' : 'Создать'}
          </LoadingButton>
        </DialogActions>
      </Form>
    </Dialog>
  );
}
