'use client';

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

import Box from '@mui/material/Box';
import Card from '@mui/material/Card';
import Grid from '@mui/material/Grid';
import Stack from '@mui/material/Stack';
import Alert from '@mui/material/Alert';
import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog';
import Tooltip from '@mui/material/Tooltip';
import TextField from '@mui/material/TextField';
import Typography from '@mui/material/Typography';
import IconButton from '@mui/material/IconButton';
import DialogTitle from '@mui/material/DialogTitle';
import CardContent from '@mui/material/CardContent';
import DialogContent from '@mui/material/DialogContent';
import DialogActions from '@mui/material/DialogActions';
import InputAdornment from '@mui/material/InputAdornment';
import CircularProgress from '@mui/material/CircularProgress';

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

import {
  getMaterials,
  createMaterial,
  deleteMaterial,
  getMaterialTypeIcon,
} from 'src/utils/materials-api';

import { CONFIG } from 'src/config-global';
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';

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

function fileUrl(href) {
  if (!href) return '';
  if (href.startsWith('http://') || href.startsWith('https://')) return href;
  const base = CONFIG.site.serverUrl?.replace('/api', '') || '';
  return base + (href.startsWith('/') ? href : `/${href}`);
}

function formatSize(bytes) {
  if (!bytes) return '';
  if (bytes >= 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(1)} МБ`;
  if (bytes >= 1024) return `${(bytes / 1024).toFixed(0)} КБ`;
  return `${bytes} Б`;
}

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

function MaterialCard({ material, onDelete, isMentor }) {
  const icon = getMaterialTypeIcon(material);
  const url = fileUrl(material.file_url || material.file || '');
  const isImage =
    material.material_type === 'image' ||
    /\.(jpe?g|png|gif|webp)$/i.test(material.file_name || material.file || '');

  return (
    <Card variant="outlined" sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      {isImage && url ? (
        <Box
          component="a"
          href={url}
          target="_blank"
          rel="noopener noreferrer"
          sx={{
            display: 'block',
            height: 140,
            overflow: 'hidden',
            borderBottom: '1px solid',
            borderColor: 'divider',
          }}
        >
          <Box
            component="img"
            src={url}
            alt={material.title}
            sx={{ width: '100%', height: '100%', objectFit: 'cover' }}
          />
        </Box>
      ) : (
        <Box
          sx={{
            height: 100,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            bgcolor: 'background.neutral',
            borderBottom: '1px solid',
            borderColor: 'divider',
          }}
        >
          <Iconify icon={icon} width={40} color="primary.main" />
        </Box>
      )}

      <CardContent sx={{ flex: 1, pb: 1 }}>
        <Typography variant="subtitle2" noWrap sx={{ mb: 0.5 }}>
          {material.title}
        </Typography>
        {material.description && (
          <Typography
            variant="caption"
            color="text.secondary"
            sx={{
              display: '-webkit-box',
              WebkitLineClamp: 2,
              WebkitBoxOrient: 'vertical',
              overflow: 'hidden',
            }}
          >
            {material.description}
          </Typography>
        )}
        {(material.file_size || material.category_name) && (
          <Stack direction="row" spacing={1} sx={{ mt: 1 }}>
            {material.category_name && (
              <Typography variant="caption" color="text.disabled">
                {material.category_name}
              </Typography>
            )}
            {material.file_size && (
              <Typography variant="caption" color="text.disabled">
                {formatSize(material.file_size)}
              </Typography>
            )}
          </Stack>
        )}
      </CardContent>

      <Stack
        direction="row"
        spacing={0.5}
        sx={{ px: 1.5, pb: 1.5, borderTop: '1px solid', borderColor: 'divider', pt: 1 }}
      >
        {url && (
          <Tooltip title="Скачать">
            <IconButton size="small" component="a" href={url} target="_blank" rel="noopener noreferrer">
              <Iconify icon="eva:download-outline" width={18} />
            </IconButton>
          </Tooltip>
        )}
        {isMentor && (
          <Tooltip title="Удалить">
            <IconButton size="small" color="error" onClick={() => onDelete(material)}>
              <Iconify icon="eva:trash-2-outline" width={18} />
            </IconButton>
          </Tooltip>
        )}
      </Stack>
    </Card>
  );
}

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

function UploadDialog({ open, onClose, onSuccess }) {
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [file, setFile] = useState(null);
  const [isPublic, setIsPublic] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const reset = () => {
    setTitle('');
    setDescription('');
    setFile(null);
    setIsPublic(false);
    setError(null);
  };

  const handleClose = () => {
    if (!loading) {
      reset();
      onClose();
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!title.trim()) {
      setError('Укажите название');
      return;
    }
    if (!file) {
      setError('Выберите файл');
      return;
    }
    try {
      setLoading(true);
      setError(null);
      await createMaterial({ title: title.trim(), description: description.trim(), file, is_public: isPublic });
      await onSuccess();
      handleClose();
    } catch (err) {
      setError(err?.response?.data?.detail || err?.message || 'Ошибка загрузки');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onClose={handleClose} maxWidth="sm" fullWidth>
      <DialogTitle>Добавить материал</DialogTitle>
      <DialogContent>
        <Stack spacing={2} sx={{ mt: 1 }}>
          <TextField
            label="Название *"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            disabled={loading}
            fullWidth
          />
          <TextField
            label="Описание"
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            disabled={loading}
            multiline
            rows={2}
            fullWidth
          />
          <Box>
            <input
              type="file"
              id="material-file"
              onChange={(e) => setFile(e.target.files?.[0] || null)}
              disabled={loading}
              style={{ display: 'none' }}
            />
            <Button
              component="label"
              htmlFor="material-file"
              variant="outlined"
              startIcon={<Iconify icon="eva:upload-outline" />}
              fullWidth
              disabled={loading}
              sx={{ py: 1.5, border: '2px dashed', '&:hover': { border: '2px dashed' } }}
            >
              {file ? file.name : 'Выбрать файл'}
            </Button>
          </Box>
          {error && <Alert severity="error">{error}</Alert>}
        </Stack>
      </DialogContent>
      <DialogActions sx={{ px: 3, pb: 2 }}>
        <Button onClick={handleClose} disabled={loading}>
          Отмена
        </Button>
        <Button
          variant="contained"
          onClick={handleSubmit}
          disabled={loading || !title.trim() || !file}
          startIcon={loading ? <Iconify icon="svg-spinners:8-dots-rotate" /> : null}
        >
          {loading ? 'Загрузка...' : 'Сохранить'}
        </Button>
      </DialogActions>
    </Dialog>
  );
}

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

export function MaterialsView() {
  const { user } = useAuthContext();
  const isMentor = user?.role === 'mentor';

  const [materials, setMaterials] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [search, setSearch] = useState('');
  const [uploadOpen, setUploadOpen] = useState(false);
  const [deleteTarget, setDeleteTarget] = useState(null);
  const [deleting, setDeleting] = useState(false);

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

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

  const handleDelete = async () => {
    if (!deleteTarget) return;
    try {
      setDeleting(true);
      await deleteMaterial(deleteTarget.id);
      setMaterials((prev) => prev.filter((m) => m.id !== deleteTarget.id));
      setDeleteTarget(null);
    } catch (e) {
      setError(e?.response?.data?.detail || e?.message || 'Ошибка удаления');
    } finally {
      setDeleting(false);
    }
  };

  const filtered = materials.filter((m) => {
    if (!search.trim()) return true;
    const q = search.toLowerCase();
    return (
      (m.title || '').toLowerCase().includes(q) ||
      (m.description || '').toLowerCase().includes(q) ||
      (m.category_name || '').toLowerCase().includes(q)
    );
  });

  return (
    <DashboardContent>
      <CustomBreadcrumbs
        heading="Материалы"
        links={[{ name: 'Главная', href: paths.dashboard.root }, { name: 'Материалы' }]}
        action={
          isMentor && (
            <Button
              variant="contained"
              startIcon={<Iconify icon="eva:plus-fill" />}
              onClick={() => setUploadOpen(true)}
            >
              Добавить
            </Button>
          )
        }
        sx={{ mb: 3 }}
      />

      <Stack direction="row" spacing={2} sx={{ mb: 3 }}>
        <TextField
          placeholder="Поиск материалов..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          size="small"
          sx={{ width: 300 }}
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <Iconify icon="eva:search-outline" />
              </InputAdornment>
            ),
          }}
        />
      </Stack>

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

      {loading ? (
        <Box sx={{ display: 'flex', justifyContent: 'center', py: 6 }}>
          <CircularProgress />
        </Box>
      ) : filtered.length === 0 ? (
        <Typography variant="body1" color="text.secondary" sx={{ py: 4 }}>
          {search ? 'Ничего не найдено' : 'Нет материалов'}
        </Typography>
      ) : (
        <Grid container spacing={2}>
          {filtered.map((material) => (
            <Grid key={material.id} item xs={12} sm={6} md={4} lg={3}>
              <MaterialCard
                material={material}
                isMentor={isMentor}
                onDelete={setDeleteTarget}
              />
            </Grid>
          ))}
        </Grid>
      )}

      {/* Upload */}
      <UploadDialog open={uploadOpen} onClose={() => setUploadOpen(false)} onSuccess={load} />

      {/* Delete confirm */}
      <Dialog open={!!deleteTarget} onClose={() => !deleting && setDeleteTarget(null)} maxWidth="xs" fullWidth>
        <DialogTitle>Удалить материал?</DialogTitle>
        <DialogContent>
          <Typography>
            &laquo;{deleteTarget?.title}&raquo; будет удалён безвозвратно.
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteTarget(null)} disabled={deleting}>
            Отмена
          </Button>
          <Button variant="contained" color="error" onClick={handleDelete} disabled={deleting}>
            {deleting ? 'Удаление...' : 'Удалить'}
          </Button>
        </DialogActions>
      </Dialog>
    </DashboardContent>
  );
}
