'use client';

import { 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 Divider from '@mui/material/Divider';
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 CardContent from '@mui/material/CardContent';
import InputAdornment from '@mui/material/InputAdornment';
import CircularProgress from '@mui/material/CircularProgress';

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

import { getMyReferrals, getReferralStats, getReferralProfile } from 'src/utils/referrals-api';

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

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

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

function StatCard({ label, value, icon, color }) {
  return (
    <Card variant="outlined" sx={{ flex: 1, minWidth: 140 }}>
      <CardContent>
        <Stack direction="row" alignItems="center" spacing={1.5} sx={{ mb: 1 }}>
          <Box
            sx={{
              width: 40,
              height: 40,
              borderRadius: 1.5,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              bgcolor: `${color}.lighter`,
            }}
          >
            <Iconify icon={icon} width={22} color={`${color}.main`} />
          </Box>
          <Typography variant="h5" fontWeight="bold">
            {value ?? '—'}
          </Typography>
        </Stack>
        <Typography variant="caption" color="text.secondary">
          {label}
        </Typography>
      </CardContent>
    </Card>
  );
}

function ReferralTable({ title, items }) {
  if (!items || items.length === 0) return null;
  return (
    <Box>
      <Typography variant="subtitle2" sx={{ mb: 1.5, color: 'text.secondary' }}>
        {title}
      </Typography>
      <Stack spacing={1}>
        {items.map((item, idx) => (
          // eslint-disable-next-line react/no-array-index-key
          <Stack key={idx} direction="row" alignItems="center" justifyContent="space-between" sx={{ px: 2, py: 1, bgcolor: 'background.neutral', borderRadius: 1 }}>
            <Typography variant="body2">{item.email}</Typography>
            <Stack direction="row" spacing={1} alignItems="center">
              <Chip label={item.level} size="small" variant="outlined" />
              <Typography variant="caption" color="text.secondary">
                {item.total_points} pts
              </Typography>
            </Stack>
          </Stack>
        ))}
      </Stack>
    </Box>
  );
}

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

export function ReferralsView() {
  const [profile, setProfile] = useState(null);
  const [stats, setStats] = useState(null);
  const [referrals, setReferrals] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [copied, setCopied] = useState(false);

  const load = useCallback(async () => {
    try {
      setLoading(true);
      const [p, s, r] = await Promise.all([
        getReferralProfile(),
        getReferralStats(),
        getMyReferrals().catch(() => null),
      ]);
      setProfile(p);
      setStats(s);
      setReferrals(r);
    } catch (e) {
      setError(e?.response?.data?.detail || e?.message || 'Ошибка загрузки');
    } finally {
      setLoading(false);
    }
  }, []);

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

  const handleCopyLink = () => {
    const link = profile?.referral_link || stats?.referral_code || '';
    if (!link) return;
    navigator.clipboard.writeText(link).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    });
  };

  const handleCopyCode = () => {
    const code = profile?.referral_code || stats?.referral_code || '';
    if (!code) return;
    navigator.clipboard.writeText(code).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    });
  };

  const referralCode = profile?.referral_code || stats?.referral_code || '';
  const referralLink = profile?.referral_link || '';

  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: 8 }}>
          <CircularProgress />
        </Box>
      ) : (
        <Stack spacing={3}>
          {/* Stats */}
          {stats && (
            <Stack direction="row" flexWrap="wrap" gap={2}>
              <StatCard
                label="Прямые рефералы"
                value={stats.referrals?.direct}
                icon="eva:people-outline"
                color="primary"
              />
              <StatCard
                label="Непрямые рефералы"
                value={stats.referrals?.indirect}
                icon="eva:person-add-outline"
                color="info"
              />
              <StatCard
                label="Всего баллов"
                value={stats.total_points}
                icon="eva:star-outline"
                color="warning"
              />
              <StatCard
                label="Заработано"
                value={stats.earnings?.total !== undefined ? `${stats.earnings.total} ₽` : '—'}
                icon="eva:credit-card-outline"
                color="success"
              />
              <StatCard
                label="Бонусный баланс"
                value={stats.bonus_account?.balance !== undefined ? `${stats.bonus_account.balance} ₽` : '—'}
                icon="eva:gift-outline"
                color="error"
              />
            </Stack>
          )}

          {/* Level */}
          {stats?.current_level && (
            <Card variant="outlined">
              <CardContent>
                <Stack direction="row" alignItems="center" spacing={2}>
                  <Iconify icon="eva:award-outline" width={32} color="warning.main" />
                  <Box>
                    <Typography variant="subtitle1">
                      Уровень {stats.current_level.level} — {stats.current_level.name}
                    </Typography>
                    <Typography variant="body2" color="text.secondary">
                      Ваш текущий реферальный уровень
                    </Typography>
                  </Box>
                </Stack>
              </CardContent>
            </Card>
          )}

          {/* Referral code & link */}
          {referralCode && (
            <Card variant="outlined">
              <CardContent>
                <Typography variant="subtitle1" sx={{ mb: 2 }}>
                  Ваш реферальный код
                </Typography>
                <Stack spacing={2}>
                  <TextField
                    label="Реферальный код"
                    value={referralCode}
                    InputProps={{
                      readOnly: true,
                      endAdornment: (
                        <InputAdornment position="end">
                          <Tooltip title={copied ? 'Скопировано!' : 'Копировать'}>
                            <IconButton onClick={handleCopyCode} size="small">
                              <Iconify icon={copied ? 'eva:checkmark-outline' : 'eva:copy-outline'} />
                            </IconButton>
                          </Tooltip>
                        </InputAdornment>
                      ),
                    }}
                    fullWidth
                    size="small"
                  />
                  {referralLink && (
                    <TextField
                      label="Реферальная ссылка"
                      value={referralLink}
                      InputProps={{
                        readOnly: true,
                        endAdornment: (
                          <InputAdornment position="end">
                            <Tooltip title={copied ? 'Скопировано!' : 'Копировать'}>
                              <IconButton onClick={handleCopyLink} size="small">
                                <Iconify icon={copied ? 'eva:checkmark-outline' : 'eva:copy-outline'} />
                              </IconButton>
                            </Tooltip>
                          </InputAdornment>
                        ),
                      }}
                      fullWidth
                      size="small"
                    />
                  )}
                  <Button
                    variant="outlined"
                    startIcon={<Iconify icon="eva:share-outline" />}
                    onClick={handleCopyLink || handleCopyCode}
                    sx={{ alignSelf: 'flex-start' }}
                  >
                    Поделиться
                  </Button>
                </Stack>
              </CardContent>
            </Card>
          )}

          {/* Referrals list */}
          {referrals && (referrals.direct?.length > 0 || referrals.indirect?.length > 0) && (
            <Card variant="outlined">
              <CardContent>
                <Typography variant="subtitle1" sx={{ mb: 2 }}>
                  Мои рефералы
                </Typography>
                <Stack spacing={3}>
                  <ReferralTable title="Прямые" items={referrals.direct} />
                  {referrals.direct?.length > 0 && referrals.indirect?.length > 0 && <Divider />}
                  <ReferralTable title="Непрямые" items={referrals.indirect} />
                </Stack>
              </CardContent>
            </Card>
          )}

          {!referralCode && !loading && (
            <Typography variant="body1" color="text.secondary">
              Реферальная программа недоступна
            </Typography>
          )}
        </Stack>
      )}
    </DashboardContent>
  );
}
