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

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

import axios from 'src/utils/axios';

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

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

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

async function getPaymentInfo() {
  const res = await axios.get('/payments/subscriptions/');
  const {data} = res;
  if (Array.isArray(data)) return data;
  return data?.results ?? [];
}

async function getPaymentHistory() {
  const res = await axios.get('/payments/history/');
  const {data} = res;
  if (Array.isArray(data)) return data;
  return data?.results ?? [];
}

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

function formatDate(ts) {
  if (!ts) return '—';
  try {
    return new Date(ts).toLocaleDateString('ru-RU');
  } catch {
    return ts;
  }
}

function formatAmount(amount, currency) {
  if (amount == null) return '—';
  return `${amount} ${currency || '₽'}`;
}

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

export function PaymentPlatformView() {
  const [subscriptions, setSubscriptions] = useState([]);
  const [history, setHistory] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const load = useCallback(async () => {
    try {
      setLoading(true);
      const [subs, hist] = await Promise.all([
        getPaymentInfo().catch(() => []),
        getPaymentHistory().catch(() => []),
      ]);
      setSubscriptions(subs);
      setHistory(hist);
    } catch (e) {
      setError(e?.response?.data?.detail || e?.message || 'Ошибка загрузки');
    } finally {
      setLoading(false);
    }
  }, []);

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

  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}>
          {/* Subscriptions */}
          {subscriptions.length > 0 ? (
            <Card variant="outlined">
              <CardContent>
                <Typography variant="subtitle1" sx={{ mb: 2 }}>
                  Активные подписки
                </Typography>
                <Stack spacing={1.5}>
                  {subscriptions.map((sub, idx) => (
                    // eslint-disable-next-line react/no-array-index-key
                    <Box key={idx}>
                      {idx > 0 && <Divider sx={{ mb: 1.5 }} />}
                      <Stack direction="row" alignItems="center" justifyContent="space-between" flexWrap="wrap" gap={1}>
                        <Box>
                          <Typography variant="subtitle2">
                            {sub.plan_name || sub.name || 'Подписка'}
                          </Typography>
                          {sub.expires_at && (
                            <Typography variant="caption" color="text.secondary">
                              До {formatDate(sub.expires_at)}
                            </Typography>
                          )}
                        </Box>
                        <Stack direction="row" spacing={1} alignItems="center">
                          {sub.status && (
                            <Chip
                              label={sub.status}
                              size="small"
                              color={sub.status === 'active' ? 'success' : 'default'}
                            />
                          )}
                          {sub.price != null && (
                            <Typography variant="subtitle2">
                              {formatAmount(sub.price, sub.currency)}
                            </Typography>
                          )}
                        </Stack>
                      </Stack>
                    </Box>
                  ))}
                </Stack>
              </CardContent>
            </Card>
          ) : (
            <Card variant="outlined">
              <CardContent>
                <Stack alignItems="center" spacing={2} sx={{ py: 3 }}>
                  <Iconify icon="eva:credit-card-outline" width={48} color="text.disabled" />
                  <Typography variant="body1" color="text.secondary">
                    Нет активных подписок
                  </Typography>
                  <Button variant="contained" startIcon={<Iconify icon="eva:plus-fill" />}>
                    Подключить подписку
                  </Button>
                </Stack>
              </CardContent>
            </Card>
          )}

          {/* Payment history */}
          {history.length > 0 && (
            <Card variant="outlined">
              <CardContent>
                <Typography variant="subtitle1" sx={{ mb: 2 }}>
                  История платежей
                </Typography>
                <Stack spacing={1}>
                  {history.map((item, idx) => (
                    // eslint-disable-next-line react/no-array-index-key
                    <Stack key={idx} direction="row" alignItems="center" justifyContent="space-between" sx={{ py: 0.75 }}>
                      <Box>
                        <Typography variant="body2">
                          {item.description || item.plan_name || 'Платёж'}
                        </Typography>
                        <Typography variant="caption" color="text.secondary">
                          {formatDate(item.created_at || item.date)}
                        </Typography>
                      </Box>
                      <Stack direction="row" spacing={1} alignItems="center">
                        <Typography variant="subtitle2">
                          {formatAmount(item.amount, item.currency)}
                        </Typography>
                        {item.status && (
                          <Chip
                            label={item.status}
                            size="small"
                            color={item.status === 'success' || item.status === 'paid' ? 'success' : 'default'}
                          />
                        )}
                      </Stack>
                    </Stack>
                  ))}
                </Stack>
              </CardContent>
            </Card>
          )}
        </Stack>
      )}
    </DashboardContent>
  );
}
