'use client';

import { useRef, useEffect, useState, useCallback } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';

import Box from '@mui/material/Box';
import Card from '@mui/material/Card';
import Grid from '@mui/material/Unstable_Grid2';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
import Avatar from '@mui/material/Avatar';
import Tooltip from '@mui/material/Tooltip';
import Typography from '@mui/material/Typography';
import IconButton from '@mui/material/IconButton';
import CardContent from '@mui/material/CardContent';
import CardActionArea from '@mui/material/CardActionArea';
import CircularProgress from '@mui/material/CircularProgress';

import { CONFIG } from 'src/config-global';
import { Iconify } from 'src/components/iconify';
import { DashboardContent } from 'src/layouts/dashboard';
import { useAuthContext } from 'src/auth/hooks';
import { getMyBoards, getSharedBoards, getOrCreateMentorStudentBoard } from 'src/utils/board-api';
import { getMentorStudents } from 'src/utils/dashboard-api';

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

function buildExcalidrawSrc(boardId, user) {
  const token =
    typeof window !== 'undefined'
      ? localStorage.getItem('jwt_access_token') || localStorage.getItem('access_token') || ''
      : '';

  const serverUrl = CONFIG.site.serverUrl || '';
  const apiUrl = serverUrl.replace(/\/api\/?$/, '') || '';
  const isMentor = user?.role === 'mentor';

  const excalidrawUrl = (process.env.NEXT_PUBLIC_EXCALIDRAW_URL || '').trim().replace(/\/?$/, '');
  const excalidrawPath = process.env.NEXT_PUBLIC_EXCALIDRAW_PATH || '';
  const excalidrawPort = process.env.NEXT_PUBLIC_EXCALIDRAW_PORT || '3001';
  const yjsPort = process.env.NEXT_PUBLIC_YJS_PORT || '1236';

  if (excalidrawUrl && excalidrawUrl.startsWith('http')) {
    const url = new URL(`${excalidrawUrl}/`);
    url.searchParams.set('boardId', boardId);
    url.searchParams.set('apiUrl', apiUrl);
    url.searchParams.set('yjsPort', yjsPort);
    if (token) url.searchParams.set('token', token);
    if (isMentor) url.searchParams.set('isMentor', '1');
    return url.toString();
  }

  const origin = excalidrawPath
    ? (typeof window !== 'undefined' ? window.location.origin : '')
    : `${typeof window !== 'undefined' ? window.location.protocol : 'https:'}//${typeof window !== 'undefined' ? window.location.hostname : ''}:${excalidrawPort}`;
  const pathname = excalidrawPath ? `/${excalidrawPath.replace(/^\//, '')}/` : '/';
  const params = new URLSearchParams({ boardId, apiUrl });
  params.set('yjsPort', yjsPort);
  if (token) params.set('token', token);
  if (isMentor) params.set('isMentor', '1');
  return `${origin}${pathname}?${params.toString()}`;
}

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

function WhiteboardIframe({ boardId, user }) {
  const containerRef = useRef(null);
  const iframeRef = useRef(null);
  const createdRef = useRef(false);
  const username = user ? `${user.first_name || ''} ${user.last_name || ''}`.trim() || user.email : 'Пользователь';

  useEffect(() => {
    if (typeof window === 'undefined' || !containerRef.current || !boardId) return undefined;
    if (createdRef.current) return undefined;

    const excalidrawUrl = (process.env.NEXT_PUBLIC_EXCALIDRAW_URL || '').trim();
    const excalidrawPath = process.env.NEXT_PUBLIC_EXCALIDRAW_PATH || '';
    const iframeSrc = buildExcalidrawSrc(boardId, user);

    const sendUsername = (iframe) => {
      if (!iframe.contentWindow) return;
      try {
        const targetOrigin = excalidrawUrl.startsWith('http')
          ? new URL(excalidrawUrl).origin
          : window.location.origin;
        iframe.contentWindow.postMessage({ type: 'excalidraw-username', username }, targetOrigin);
      } catch (_e) {
        // ignore cross-origin errors
      }
    };

    const iframe = document.createElement('iframe');
    iframe.src = iframeSrc;
    iframe.style.cssText = 'width:100%;height:100%;border:none;display:block';
    iframe.title = 'Интерактивная доска';
    iframe.setAttribute('allow', 'camera; microphone; fullscreen');
    iframe.setAttribute('sandbox', 'allow-same-origin allow-scripts allow-forms allow-popups allow-modals');
    iframe.onload = () => { sendUsername(iframe); setTimeout(() => sendUsername(iframe), 500); };

    containerRef.current.appendChild(iframe);
    iframeRef.current = iframe;
    createdRef.current = true;
    setTimeout(() => sendUsername(iframe), 300);

    return () => {
      createdRef.current = false;
      iframeRef.current = null;
      iframe.remove();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [boardId]);

  return <div ref={containerRef} style={{ width: '100%', height: '100%' }} />;
}

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

function getUserName(u) {
  if (!u) return '—';
  if (typeof u === 'object') return [u.first_name, u.last_name].filter(Boolean).join(' ') || u.email || '—';
  return String(u);
}

function getUserInitials(u) {
  if (!u || typeof u !== 'object') return '?';
  return [u.first_name?.[0], u.last_name?.[0]].filter(Boolean).join('').toUpperCase() || (u.email?.[0] || '?').toUpperCase();
}

function BoardCard({ board, currentUser, onClick }) {
  const isMentor = currentUser?.role === 'mentor';
  const otherPerson = isMentor ? board.student : board.mentor;
  const otherName = getUserName(otherPerson);
  const otherInitials = getUserInitials(otherPerson);
  const lastEdited = board.last_edited_at
    ? new Date(board.last_edited_at).toLocaleDateString('ru-RU', { day: 'numeric', month: 'short' })
    : null;

  return (
    <Card sx={{ borderRadius: 2, height: '100%' }}>
      <CardActionArea onClick={onClick} sx={{ height: '100%' }}>
        {/* Preview area */}
        <Box
          sx={{
            height: 140,
            bgcolor: 'primary.lighter',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            position: 'relative',
          }}
        >
          <Iconify icon="solar:pen-new-square-bold-duotone" width={48} sx={{ color: 'primary.main', opacity: 0.4 }} />
          {board.elements_count > 0 && (
            <Box
              sx={{
                position: 'absolute',
                bottom: 8,
                right: 8,
                bgcolor: 'background.paper',
                borderRadius: 1,
                px: 1,
                py: 0.25,
              }}
            >
              <Typography variant="caption" color="text.secondary">
                {board.elements_count} элем.
              </Typography>
            </Box>
          )}
        </Box>

        <CardContent>
          <Typography variant="subtitle2" noWrap mb={0.5}>
            {board.title || 'Без названия'}
          </Typography>

          <Stack direction="row" alignItems="center" spacing={1}>
            <Avatar sx={{ width: 24, height: 24, fontSize: 11, bgcolor: 'primary.main' }}>
              {otherInitials}
            </Avatar>
            <Typography variant="caption" color="text.secondary" noWrap>
              {isMentor ? 'Ученик: ' : 'Ментор: '}{otherName}
            </Typography>
          </Stack>

          {lastEdited && (
            <Typography variant="caption" color="text.disabled" display="block" mt={0.5}>
              Изменено {lastEdited}
            </Typography>
          )}
        </CardContent>
      </CardActionArea>
    </Card>
  );
}

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

function BoardListView({ onOpen }) {
  const { user } = useAuthContext();
  const [myBoards, setMyBoards] = useState([]);
  const [sharedBoards, setSharedBoards] = useState([]);
  const [loading, setLoading] = useState(true);
  const [creating, setCreating] = useState(false);
  const [students, setStudents] = useState([]);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const [mine, shared] = await Promise.all([
        getMyBoards().catch(() => []),
        getSharedBoards().catch(() => []),
      ]);
      setMyBoards(Array.isArray(mine) ? mine : []);
      setSharedBoards(Array.isArray(shared) ? shared : []);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => { load(); }, [load]);

  // Ментор может создать доску с учеником
  useEffect(() => {
    if (user?.role !== 'mentor') return;
    getMentorStudents()
      .then((res) => {
        const list = Array.isArray(res) ? res : res?.results || [];
        setStudents(list);
      })
      .catch(() => {});
  }, [user?.role]);

  const handleCreateWithStudent = async (student) => {
    setCreating(true);
    try {
      const board = await getOrCreateMentorStudentBoard(user.id, student.id ?? student.user?.id ?? student);
      await load();
      onOpen(board.board_id);
    } catch (e) {
      console.error(e);
    } finally {
      setCreating(false);
    }
  };

  const excalidrawAvailable = !!(
    process.env.NEXT_PUBLIC_EXCALIDRAW_URL ||
    process.env.NEXT_PUBLIC_EXCALIDRAW_PATH ||
    process.env.NEXT_PUBLIC_EXCALIDRAW_PORT
  );

  if (loading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}>
        <CircularProgress />
      </Box>
    );
  }

  const allBoards = [...myBoards, ...sharedBoards];
  const uniqueBoards = allBoards.filter((b, i, arr) => arr.findIndex((x) => x.board_id === b.board_id) === i);

  return (
    <Box>
      {!excalidrawAvailable && (
        <Box sx={{ mb: 3, p: 2, bgcolor: 'warning.lighter', borderRadius: 2 }}>
          <Typography variant="body2" color="warning.dark">
            Excalidraw не настроен. Укажите NEXT_PUBLIC_EXCALIDRAW_URL или NEXT_PUBLIC_EXCALIDRAW_PATH в .env
          </Typography>
        </Box>
      )}

      <Stack direction="row" alignItems="center" justifyContent="space-between" mb={3} flexWrap="wrap" gap={2}>
        <Typography variant="h4">Доски</Typography>

        {user?.role === 'mentor' && students.length > 0 && (
          <Stack direction="row" spacing={1} flexWrap="wrap">
            {students.slice(0, 6).map((s) => {
              const name = getUserName(s.user || s);
              const initials = getUserInitials(s.user || s);
              return (
                <Tooltip key={s.id} title={`Открыть доску с ${name}`}>
                  <Button
                    variant="outlined"
                    size="small"
                    startIcon={<Avatar sx={{ width: 20, height: 20, fontSize: 10 }}>{initials}</Avatar>}
                    onClick={() => handleCreateWithStudent(s.user || s)}
                    disabled={creating}
                  >
                    {name.split(' ')[0]}
                  </Button>
                </Tooltip>
              );
            })}
          </Stack>
        )}
      </Stack>

      {uniqueBoards.length === 0 ? (
        <Box
          sx={{
            py: 10,
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            gap: 2,
            color: 'text.secondary',
          }}
        >
          <Iconify icon="solar:pen-new-square-linear" width={64} sx={{ opacity: 0.3 }} />
          <Typography variant="body1">Досок пока нет</Typography>
          {user?.role === 'mentor' && (
            <Typography variant="body2">
              Нажмите на имя ученика выше, чтобы открыть совместную доску
            </Typography>
          )}
        </Box>
      ) : (
        <Grid container spacing={2.5}>
          {uniqueBoards.map((board) => (
            <Grid key={board.board_id} xs={12} sm={6} md={4} lg={3}>
              <BoardCard board={board} currentUser={user} onClick={() => onOpen(board.board_id)} />
            </Grid>
          ))}
        </Grid>
      )}
    </Box>
  );
}

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

export function BoardView() {
  const { user } = useAuthContext();
  const searchParams = useSearchParams();
  const router = useRouter();

  const boardId = searchParams.get('id') || searchParams.get('board_id');

  const handleOpen = (id) => {
    router.push(`/dashboard/board?id=${id}`);
  };

  const handleBack = () => {
    router.push('/dashboard/board');
  };

  if (boardId) {
    return (
      <Box
        sx={{
          display: 'flex',
          flexDirection: 'column',
          height: {
            xs: 'calc(100dvh - var(--layout-header-mobile-height))',
            lg: 'calc(100dvh - var(--layout-header-desktop-height))',
          },
          overflow: 'hidden',
        }}
      >
        <Box
          sx={{
            px: 2,
            py: 1.5,
            borderBottom: '1px solid',
            borderColor: 'divider',
            display: 'flex',
            alignItems: 'center',
            gap: 1,
            flexShrink: 0,
          }}
        >
          <IconButton size="small" onClick={handleBack}>
            <Iconify icon="solar:arrow-left-linear" />
          </IconButton>
          <Typography variant="h6">Интерактивная доска</Typography>
          <Typography variant="body2" color="text.secondary">#{boardId}</Typography>
        </Box>
        <Box sx={{ flex: 1, minHeight: 0, overflow: 'hidden' }}>
          <WhiteboardIframe boardId={boardId} user={user} />
        </Box>
      </Box>
    );
  }

  return (
    <DashboardContent maxWidth="xl">
      <BoardListView onOpen={handleOpen} />
    </DashboardContent>
  );
}
