'use client';

import { useMemo, useState, useEffect, useCallback } from 'react';

import Box from '@mui/material/Box';
import Card from '@mui/material/Card';
import Chip from '@mui/material/Chip';
import Stack from '@mui/material/Stack';
import Alert from '@mui/material/Alert';
import Button from '@mui/material/Button';
import Typography from '@mui/material/Typography';
import CardContent from '@mui/material/CardContent';
import CardActionArea from '@mui/material/CardActionArea';
import CircularProgress from '@mui/material/CircularProgress';

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

import { getHomework, getHomeworkById, getHomeworkStatus } from 'src/utils/homework-api';

import { DashboardContent } from 'src/layouts/dashboard';

import { Iconify } from 'src/components/iconify';
import { CustomBreadcrumbs } from 'src/components/custom-breadcrumbs';

import { useAuthContext } from 'src/auth/hooks';

import { HomeworkEditDrawer } from '../homework-edit-drawer';
import { HomeworkSubmitDrawer } from '../homework-submit-drawer';
import { HomeworkDetailsDrawer } from '../homework-details-drawer';

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

function formatDate(s) {
  if (!s) return null;
  const d = new Date(s);
  return Number.isNaN(d.getTime())
    ? null
    : d.toLocaleDateString('ru-RU', { day: 'numeric', month: 'long', year: 'numeric' });
}

function formatTime(s) {
  if (!s) return null;
  const d = new Date(s);
  return Number.isNaN(d.getTime())
    ? null
    : d.toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' });
}

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

function HomeworkCard({ hw, userRole, onView, onSubmit, onEdit }) {
  const status = getHomeworkStatus(hw);
  const isFillLater = hw.fill_later === true;

  const statusConfig = {
    pending: { label: hw.is_overdue ? 'Просрочено' : 'Ожидает сдачи', color: hw.is_overdue ? 'error' : 'default' },
    submitted: { label: 'На проверке', color: 'info' },
    returned: { label: 'На доработке', color: 'warning' },
    reviewed: { label: 'Проверено', color: 'success' },
  };
  const statusInfo = statusConfig[status] || statusConfig.pending;

  return (
    <Card variant="outlined">
      <CardActionArea onClick={onView}>
        <CardContent>
          <Stack direction="row" alignItems="flex-start" justifyContent="space-between" spacing={1} sx={{ mb: 1 }}>
            <Typography variant="subtitle2" sx={{ flex: 1 }}>
              {hw.title}
            </Typography>
            <Chip
              label={isFillLater ? 'Заполнить позже' : statusInfo.label}
              color={isFillLater ? 'warning' : statusInfo.color}
              size="small"
              sx={{ flexShrink: 0 }}
            />
          </Stack>

          {userRole === 'client' && (
            <Stack direction="row" alignItems="center" spacing={0.5} sx={{ mb: 0.5 }}>
              <Iconify icon="eva:person-outline" width={14} color="text.secondary" />
              <Typography variant="caption" color="text.secondary">
                {hw.mentor?.first_name} {hw.mentor?.last_name}
              </Typography>
            </Stack>
          )}

          {userRole === 'mentor' && hw.total_submissions > 0 && (
            <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mb: 0.5 }}>
              Решений: {hw.total_submissions}
              {hw.checked_submissions > 0 && ` • Проверено: ${hw.checked_submissions}`}
            </Typography>
          )}

          {hw.deadline && (
            <Stack direction="row" alignItems="center" spacing={0.5}>
              <Iconify icon="eva:calendar-outline" width={14} color="text.secondary" />
              <Typography
                variant="caption"
                color={hw.is_overdue ? 'error' : 'text.secondary'}
              >
                {formatDate(hw.deadline)} {formatTime(hw.deadline)}
              </Typography>
            </Stack>
          )}

          {hw.student_score?.score != null && (
            <Typography variant="caption" color="primary" fontWeight={600} sx={{ display: 'block', mt: 1 }}>
              Оценка: {hw.student_score.score} / {hw.max_score || 5}
            </Typography>
          )}

          {hw.ai_draft_count > 0 && userRole === 'mentor' && (
            <Chip
              label={`ИИ-черновик: ${hw.ai_draft_count}`}
              size="small"
              color="info"
              variant="outlined"
              sx={{ mt: 1 }}
            />
          )}
        </CardContent>
      </CardActionArea>

      {((userRole === 'client' && status === 'pending' && !hw.is_overdue && hw.status === 'published') ||
        (userRole === 'mentor' && isFillLater)) && (
        <Box sx={{ px: 2, pb: 2 }}>
          {userRole === 'client' && (
            <Button
              variant="contained"
              size="small"
              fullWidth
              onClick={(e) => { e.stopPropagation(); onSubmit(); }}
            >
              Сдать ДЗ
            </Button>
          )}
          {userRole === 'mentor' && isFillLater && (
            <Button
              variant="outlined"
              size="small"
              fullWidth
              color="warning"
              onClick={(e) => { e.stopPropagation(); onEdit(); }}
              startIcon={<Iconify icon="eva:edit-outline" />}
            >
              Заполнить задание
            </Button>
          )}
        </Box>
      )}
    </Card>
  );
}

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

function HomeworkColumn({ title, items, userRole, onView, onSubmit, onEdit, emptyText }) {
  return (
    <Box sx={{ minWidth: 0 }}>
      <Typography
        variant="subtitle1"
        fontWeight={600}
        sx={{ mb: 2, pb: 1, borderBottom: '2px solid', borderColor: 'divider' }}
      >
        {title}
        {items.length > 0 && (
          <Typography component="span" variant="body2" color="text.secondary" sx={{ ml: 1 }}>
            ({items.length})
          </Typography>
        )}
      </Typography>
      <Stack spacing={1.5}>
        {items.length === 0 ? (
          <Typography variant="body2" color="text.secondary">
            {emptyText || 'Нет заданий'}
          </Typography>
        ) : (
          items.map((hw) => (
            <HomeworkCard
              key={hw.id}
              hw={hw}
              userRole={userRole}
              onView={() => onView(hw)}
              onSubmit={() => onSubmit(hw)}
              onEdit={() => onEdit(hw)}
            />
          ))
        )}
      </Stack>
    </Box>
  );
}

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

export function HomeworkView() {
  const { user } = useAuthContext();
  const userRole = user?.role ?? '';

  const [homework, setHomework] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  // Drawers
  const [selectedHw, setSelectedHw] = useState(null);
  const [detailsOpen, setDetailsOpen] = useState(false);
  const [submitOpen, setSubmitOpen] = useState(false);
  const [submitHwId, setSubmitHwId] = useState(null);
  const [editOpen, setEditOpen] = useState(false);
  const [editHw, setEditHw] = useState(null);

  const loadHomework = useCallback(async () => {
    try {
      setLoading(true);
      const res = await getHomework({ page_size: 1000 });
      setHomework(res.results);
    } catch (e) {
      setError(e?.response?.data?.detail || e?.message || 'Ошибка загрузки');
    } finally {
      setLoading(false);
    }
  }, []);

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

  const handleViewDetails = useCallback(async (hw) => {
    try {
      const full = await getHomeworkById(hw.id);
      setSelectedHw(full);
    } catch {
      setSelectedHw(hw);
    }
    setDetailsOpen(true);
  }, []);

  const handleOpenSubmit = useCallback((hw) => {
    setSubmitHwId(hw.id);
    setSubmitOpen(true);
  }, []);

  const handleOpenEdit = useCallback((hw) => {
    setEditHw(hw);
    setEditOpen(true);
  }, []);

  // Categorize
  const pending = useMemo(
    () => homework.filter((hw) => getHomeworkStatus(hw) === 'pending' && hw.status === 'published'),
    [homework]
  );
  const submitted = useMemo(
    () => homework.filter((hw) => getHomeworkStatus(hw) === 'submitted'),
    [homework]
  );
  const returned = useMemo(
    () => homework.filter((hw) => getHomeworkStatus(hw) === 'returned'),
    [homework]
  );
  const reviewed = useMemo(
    () => homework.filter((hw) => getHomeworkStatus(hw) === 'reviewed'),
    [homework]
  );
  const fillLater = useMemo(
    () => (userRole === 'mentor' ? homework.filter((hw) => hw.fill_later === true) : []),
    [homework, userRole]
  );
  const aiDraft = useMemo(
    () => (userRole === 'mentor' ? homework.filter((hw) => (hw.ai_draft_count ?? 0) > 0) : []),
    [homework, userRole]
  );

  return (
    <DashboardContent>
      <CustomBreadcrumbs
        heading="Домашние задания"
        links={[
          { name: 'Главная', href: paths.dashboard.root },
          { name: 'Домашние задания' },
        ]}
        sx={{ mb: 3 }}
      />

      {error && (
        <Alert severity="error" sx={{ mb: 3 }}>
          {error}
        </Alert>
      )}

      {loading ? (
        <Box sx={{ display: 'flex', justifyContent: 'center', py: 6 }}>
          <CircularProgress />
        </Box>
      ) : homework.length === 0 ? (
        <Typography variant="body1" color="text.secondary" sx={{ py: 4 }}>
          Нет домашних заданий
        </Typography>
      ) : (
        <Box
          sx={{
            display: 'grid',
            gridTemplateColumns: {
              xs: '1fr',
              sm: 'repeat(2, 1fr)',
              lg: 'repeat(3, 1fr)',
            },
            gap: 3,
          }}
        >
          {userRole === 'mentor' && fillLater.length > 0 && (
            <HomeworkColumn
              title="Ожидают заполнения"
              items={fillLater}
              userRole={userRole}
              onView={handleViewDetails}
              onSubmit={handleOpenSubmit}
              onEdit={handleOpenEdit}
            />
          )}

          <HomeworkColumn
            title="Ожидают сдачи"
            items={pending}
            userRole={userRole}
            onView={handleViewDetails}
            onSubmit={handleOpenSubmit}
            onEdit={handleOpenEdit}
          />

          <HomeworkColumn
            title="На проверке"
            items={submitted}
            userRole={userRole}
            onView={handleViewDetails}
            onSubmit={handleOpenSubmit}
            onEdit={handleOpenEdit}
          />

          {userRole === 'mentor' && aiDraft.length > 0 && (
            <HomeworkColumn
              title="Черновик от ИИ"
              items={aiDraft}
              userRole={userRole}
              onView={handleViewDetails}
              onSubmit={handleOpenSubmit}
              onEdit={handleOpenEdit}
            />
          )}

          <HomeworkColumn
            title="На доработке"
            items={returned}
            userRole={userRole}
            onView={handleViewDetails}
            onSubmit={handleOpenSubmit}
            onEdit={handleOpenEdit}
          />

          <HomeworkColumn
            title="Проверено"
            items={reviewed}
            userRole={userRole}
            onView={handleViewDetails}
            onSubmit={handleOpenSubmit}
            onEdit={handleOpenEdit}
          />
        </Box>
      )}

      {/* Details Drawer */}
      <HomeworkDetailsDrawer
        open={detailsOpen}
        homework={selectedHw}
        userRole={userRole}
        onClose={() => { setDetailsOpen(false); setSelectedHw(null); }}
        onSuccess={loadHomework}
        onOpenSubmit={() => {
          setSubmitHwId(selectedHw?.id);
          setSubmitOpen(true);
        }}
        onOpenEdit={(hw) => {
          setEditHw(hw);
          setEditOpen(true);
        }}
      />

      {/* Submit Drawer */}
      <HomeworkSubmitDrawer
        open={submitOpen}
        homeworkId={submitHwId}
        onClose={() => { setSubmitOpen(false); setSubmitHwId(null); }}
        onSuccess={loadHomework}
      />

      {/* Edit Draft Drawer */}
      <HomeworkEditDrawer
        open={editOpen}
        homework={editHw}
        onClose={() => { setEditOpen(false); setEditHw(null); }}
        onSuccess={loadHomework}
      />
    </DashboardContent>
  );
}
