'use client';

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

import Tab from '@mui/material/Tab';
import Box from '@mui/material/Box';
import Card from '@mui/material/Card';
import Tabs from '@mui/material/Tabs';
import List from '@mui/material/List';
import Stack from '@mui/material/Stack';
import Alert from '@mui/material/Alert';
import Avatar from '@mui/material/Avatar';
import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog';
import Divider from '@mui/material/Divider';
import ListItem from '@mui/material/ListItem';
import TextField from '@mui/material/TextField';
import Typography from '@mui/material/Typography';
import CardHeader from '@mui/material/CardHeader';
import DialogTitle from '@mui/material/DialogTitle';
import CardContent from '@mui/material/CardContent';
import ListItemText from '@mui/material/ListItemText';
import DialogContent from '@mui/material/DialogContent';
import DialogActions from '@mui/material/DialogActions';
import InputAdornment from '@mui/material/InputAdornment';
import ListItemAvatar from '@mui/material/ListItemAvatar';
import CircularProgress from '@mui/material/CircularProgress';

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

import {
  getStudents,
  getMyMentors,
  getMyInvitations,
  addStudentInvitation,
  sendMentorshipRequest,
  acceptMentorshipRequest,
  rejectMentorshipRequest,
  rejectInvitationAsStudent,
  confirmInvitationAsStudent,
  getMentorshipRequestsPending,
} from 'src/utils/students-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 avatarUrl(href) {
  if (!href) return null;
  if (href.startsWith('http://') || href.startsWith('https://')) return href;
  const base = CONFIG.site.serverUrl?.replace('/api', '') || '';
  return base + (href.startsWith('/') ? href : `/${href}`);
}

function initials(firstName, lastName) {
  return `${(firstName || '')[0] || ''}${(lastName || '')[0] || ''}`.toUpperCase();
}

// ----------------------------------------------------------------------
// MENTOR VIEWS

function MentorStudentList({ onRefresh }) {
  const [students, setStudents] = useState([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [error, setError] = useState(null);

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

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

  const filtered = students.filter((s) => {
    if (!search.trim()) return true;
    const q = search.toLowerCase();
    const u = s.user || {};
    return (
      (u.first_name || '').toLowerCase().includes(q) ||
      (u.last_name || '').toLowerCase().includes(q) ||
      (u.email || '').toLowerCase().includes(q)
    );
  });

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

  return (
    <Stack spacing={2}>
      <TextField
        placeholder="Поиск учеников..."
        value={search}
        onChange={(e) => setSearch(e.target.value)}
        size="small"
        InputProps={{
          startAdornment: <InputAdornment position="start"><Iconify icon="eva:search-outline" /></InputAdornment>,
        }}
      />

      {error && <Alert severity="error">{error}</Alert>}

      {filtered.length === 0 ? (
        <Typography variant="body2" color="text.secondary">
          {search ? 'Ничего не найдено' : 'Нет учеников'}
        </Typography>
      ) : (
        <List disablePadding>
          {filtered.map((s) => {
            const u = s.user || {};
            return (
              <ListItem
                key={s.id}
                divider
                sx={{ borderRadius: 1, '&:hover': { bgcolor: 'action.hover' } }}
              >
                <ListItemAvatar>
                  <Avatar src={avatarUrl(u.avatar_url || u.avatar)}>
                    {initials(u.first_name, u.last_name)}
                  </Avatar>
                </ListItemAvatar>
                <ListItemText
                  primary={`${u.first_name || ''} ${u.last_name || ''}`.trim() || u.email}
                  secondary={u.email}
                />
                {s.total_lessons != null && (
                  <Typography variant="caption" color="text.secondary">
                    {s.total_lessons} уроков
                  </Typography>
                )}
              </ListItem>
            );
          })}
        </List>
      )}
    </Stack>
  );
}

function MentorRequests({ onRefresh }) {
  const [requests, setRequests] = useState([]);
  const [loading, setLoading] = useState(true);
  const [processing, setProcessing] = useState(null);
  const [error, setError] = useState(null);

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

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

  const handle = async (id, action) => {
    try {
      setProcessing(id);
      if (action === 'accept') await acceptMentorshipRequest(id);
      else await rejectMentorshipRequest(id);
      await load();
      onRefresh();
    } catch (e) {
      setError(e?.response?.data?.detail || e?.message || 'Ошибка');
    } finally {
      setProcessing(null);
    }
  };

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

  return (
    <Stack spacing={2}>
      {error && <Alert severity="error">{error}</Alert>}
      {requests.length === 0 ? (
        <Typography variant="body2" color="text.secondary">Нет входящих заявок</Typography>
      ) : (
        <List disablePadding>
          {requests.map((r) => {
            const s = r.student || {};
            return (
              <ListItem
                key={r.id}
                divider
                secondaryAction={
                  <Stack direction="row" spacing={1}>
                    <Button
                      size="small"
                      variant="contained"
                      color="success"
                      onClick={() => handle(r.id, 'accept')}
                      disabled={processing === r.id}
                    >
                      Принять
                    </Button>
                    <Button
                      size="small"
                      variant="outlined"
                      color="error"
                      onClick={() => handle(r.id, 'reject')}
                      disabled={processing === r.id}
                    >
                      Отклонить
                    </Button>
                  </Stack>
                }
              >
                <ListItemAvatar>
                  <Avatar src={avatarUrl(s.avatar)}>
                    {initials(s.first_name, s.last_name)}
                  </Avatar>
                </ListItemAvatar>
                <ListItemText
                  primary={`${s.first_name || ''} ${s.last_name || ''}`.trim() || s.email}
                  secondary={s.email}
                />
              </ListItem>
            );
          })}
        </List>
      )}
    </Stack>
  );
}

function InviteDialog({ open, onClose, onSuccess }) {
  const [mode, setMode] = useState('email'); // 'email' | 'code'
  const [value, setValue] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [successMsg, setSuccessMsg] = useState(null);

  const reset = () => { setValue(''); setError(null); setSuccessMsg(null); };

  const handleSend = async () => {
    if (!value.trim()) return;
    try {
      setLoading(true);
      setError(null);
      const payload = mode === 'email' ? { email: value.trim() } : { universal_code: value.trim() };
      const res = await addStudentInvitation(payload);
      setSuccessMsg(res?.message || 'Приглашение отправлено');
      onSuccess();
    } catch (e) {
      setError(e?.response?.data?.detail || e?.response?.data?.email?.[0] || e?.message || 'Ошибка');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onClose={() => { if (!loading) { reset(); onClose(); } }} maxWidth="xs" fullWidth>
      <DialogTitle>Пригласить ученика</DialogTitle>
      <DialogContent>
        <Stack spacing={2} sx={{ mt: 1 }}>
          <Tabs value={mode} onChange={(_, v) => setMode(v)} size="small">
            <Tab value="email" label="По email" />
            <Tab value="code" label="По коду" />
          </Tabs>
          <TextField
            label={mode === 'email' ? 'Email ученика' : 'Код приглашения'}
            value={value}
            onChange={(e) => setValue(e.target.value)}
            disabled={loading}
            fullWidth
            size="small"
          />
          {error && <Alert severity="error">{error}</Alert>}
          {successMsg && <Alert severity="success">{successMsg}</Alert>}
        </Stack>
      </DialogContent>
      <DialogActions sx={{ px: 3, pb: 2 }}>
        <Button onClick={() => { reset(); onClose(); }} disabled={loading}>Закрыть</Button>
        <Button variant="contained" onClick={handleSend} disabled={loading || !value.trim()}>
          {loading ? 'Отправка...' : 'Пригласить'}
        </Button>
      </DialogActions>
    </Dialog>
  );
}

// ----------------------------------------------------------------------
// CLIENT VIEWS

function ClientMentorList() {
  const [mentors, setMentors] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    getMyMentors()
      .then((list) => setMentors(Array.isArray(list) ? list : []))
      .catch(() => setMentors([]))
      .finally(() => setLoading(false));
  }, []);

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

  return (
    <Stack spacing={1}>
      <Typography variant="subtitle2" sx={{ mb: 1 }}>Мои менторы</Typography>
      {mentors.length === 0 ? (
        <Typography variant="body2" color="text.secondary">Нет подключённых менторов</Typography>
      ) : (
        <List disablePadding>
          {mentors.map((m) => (
            <ListItem key={m.id} divider>
              <ListItemAvatar>
                <Avatar src={avatarUrl(m.avatar_url)}>
                  {initials(m.first_name, m.last_name)}
                </Avatar>
              </ListItemAvatar>
              <ListItemText
                primary={`${m.first_name || ''} ${m.last_name || ''}`.trim() || m.email}
                secondary={m.email}
              />
            </ListItem>
          ))}
        </List>
      )}
    </Stack>
  );
}

function ClientInvitations({ onRefresh }) {
  const [invitations, setInvitations] = useState([]);
  const [loading, setLoading] = useState(true);
  const [processing, setProcessing] = useState(null);
  const [error, setError] = useState(null);

  const load = useCallback(async () => {
    try {
      setLoading(true);
      const res = await getMyInvitations();
      setInvitations(Array.isArray(res) ? res.filter((i) => i.status === 'pending') : []);
    } catch {
      setInvitations([]);
    } finally {
      setLoading(false);
    }
  }, []);

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

  const handle = async (id, action) => {
    try {
      setProcessing(id);
      if (action === 'confirm') await confirmInvitationAsStudent(id);
      else await rejectInvitationAsStudent(id);
      await load();
      onRefresh();
    } catch (e) {
      setError(e?.response?.data?.detail || e?.message || 'Ошибка');
    } finally {
      setProcessing(null);
    }
  };

  if (loading) return null;
  if (invitations.length === 0) return null;

  return (
    <Card variant="outlined" sx={{ mb: 3 }}>
      <CardHeader title="Приглашения от менторов" titleTypographyProps={{ variant: 'subtitle1' }} />
      <Divider />
      <CardContent sx={{ pt: 1 }}>
        {error && <Alert severity="error" sx={{ mb: 1 }}>{error}</Alert>}
        <List disablePadding>
          {invitations.map((inv) => {
            const m = inv.mentor || {};
            return (
              <ListItem
                key={inv.id}
                divider
                secondaryAction={
                  <Stack direction="row" spacing={1}>
                    <Button size="small" variant="contained" color="success" onClick={() => handle(inv.id, 'confirm')} disabled={processing === inv.id}>
                      Принять
                    </Button>
                    <Button size="small" variant="outlined" color="error" onClick={() => handle(inv.id, 'reject')} disabled={processing === inv.id}>
                      Отклонить
                    </Button>
                  </Stack>
                }
              >
                <ListItemAvatar>
                  <Avatar>{initials(m.first_name, m.last_name)}</Avatar>
                </ListItemAvatar>
                <ListItemText
                  primary={`${m.first_name || ''} ${m.last_name || ''}`.trim() || m.email}
                  secondary={m.email}
                />
              </ListItem>
            );
          })}
        </List>
      </CardContent>
    </Card>
  );
}

function SendRequestDialog({ open, onClose, onSuccess }) {
  const [code, setCode] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [successMsg, setSuccessMsg] = useState(null);

  const handleSend = async () => {
    if (!code.trim()) return;
    try {
      setLoading(true);
      setError(null);
      const res = await sendMentorshipRequest(code.trim());
      setSuccessMsg(res?.message || 'Заявка отправлена');
      onSuccess();
    } catch (e) {
      setError(e?.response?.data?.detail || e?.response?.data?.mentor_code?.[0] || e?.message || 'Ошибка');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onClose={() => { if (!loading) { setCode(''); setError(null); setSuccessMsg(null); onClose(); } }} maxWidth="xs" fullWidth>
      <DialogTitle>Найти ментора</DialogTitle>
      <DialogContent>
        <Stack spacing={2} sx={{ mt: 1 }}>
          <TextField
            label="Код ментора"
            value={code}
            onChange={(e) => setCode(e.target.value.toUpperCase())}
            disabled={loading}
            fullWidth
            size="small"
            placeholder="XXXXXXXX"
          />
          {error && <Alert severity="error">{error}</Alert>}
          {successMsg && <Alert severity="success">{successMsg}</Alert>}
        </Stack>
      </DialogContent>
      <DialogActions sx={{ px: 3, pb: 2 }}>
        <Button onClick={() => { setCode(''); setError(null); setSuccessMsg(null); onClose(); }} disabled={loading}>Закрыть</Button>
        <Button variant="contained" onClick={handleSend} disabled={loading || !code.trim()}>
          {loading ? 'Отправка...' : 'Отправить заявку'}
        </Button>
      </DialogActions>
    </Dialog>
  );
}

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

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

  const [tab, setTab] = useState(0);
  const [inviteOpen, setInviteOpen] = useState(false);
  const [requestOpen, setRequestOpen] = useState(false);
  const [refreshKey, setRefreshKey] = useState(0);

  const refresh = () => setRefreshKey((k) => k + 1);

  return (
    <DashboardContent>
      <CustomBreadcrumbs
        heading={isMentor ? 'Ученики' : 'Мои менторы'}
        links={[{ name: 'Главная', href: paths.dashboard.root }, { name: isMentor ? 'Ученики' : 'Менторы' }]}
        action={
          isMentor ? (
            <Button variant="contained" startIcon={<Iconify icon="eva:person-add-outline" />} onClick={() => setInviteOpen(true)}>
              Пригласить ученика
            </Button>
          ) : (
            <Button variant="contained" startIcon={<Iconify icon="eva:search-outline" />} onClick={() => setRequestOpen(true)}>
              Найти ментора
            </Button>
          )
        }
        sx={{ mb: 3 }}
      />

      {isMentor ? (
        <>
          <Tabs value={tab} onChange={(_, v) => setTab(v)} sx={{ mb: 3 }}>
            <Tab label="Мои ученики" />
            <Tab label="Входящие заявки" />
          </Tabs>
          {tab === 0 && <MentorStudentList key={refreshKey} onRefresh={refresh} />}
          {tab === 1 && <MentorRequests key={refreshKey} onRefresh={refresh} />}
          <InviteDialog open={inviteOpen} onClose={() => setInviteOpen(false)} onSuccess={refresh} />
        </>
      ) : (
        <>
          <ClientInvitations key={refreshKey} onRefresh={refresh} />
          <ClientMentorList key={refreshKey} />
          <SendRequestDialog open={requestOpen} onClose={() => setRequestOpen(false)} onSuccess={refresh} />
        </>
      )}
    </DashboardContent>
  );
}
