import React, { useEffect, useState } from 'react';
import {
  Box,
  Container,
  Tab,
  TabList,
  TabPanel,
  TabPanels,
  Tabs,
  useToast,
} from '@chakra-ui/react';
import { WebApp } from '@telegram-mini-apps/sdk';
import UserProfile from '../components/UserProfile';
import Shop from '../components/Shop';
import TransferBalance from '../components/TransferBalance';
import { IUser } from '../models/User';

const Home: React.FC = () => {
  const [user, setUser] = useState<IUser | null>(null);
  const toast = useToast();

  useEffect(() => {
    // Инициализация Telegram Mini App
    WebApp.ready();
    
    // Загрузка данных пользователя
    fetchUserData();
  }, []);

  const fetchUserData = async () => {
    try {
      const response = await fetch('/api/user');
      const data = await response.json();
      setUser(data);
    } catch (error) {
      toast({
        title: 'Ошибка',
        description: 'Не удалось загрузить данные пользователя',
        status: 'error',
        duration: 3000,
        isClosable: true,
      });
    }
  };

  const handlePurchase = async (itemId: string, price: number) => {
    try {
      const response = await fetch('/api/shop/purchase', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ itemId, price }),
      });

      if (response.ok) {
        await fetchUserData(); // Обновляем данные пользователя
        return true;
      }
      return false;
    } catch (error) {
      return false;
    }
  };

  const handleTransfer = async (recipientId: string, amount: number) => {
    try {
      const response = await fetch('/api/transfer', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ recipientId, amount }),
      });

      if (response.ok) {
        await fetchUserData(); // Обновляем данные пользователя
        return true;
      }
      return false;
    } catch (error) {
      return false;
    }
  };

  if (!user) {
    return null; // или компонент загрузки
  }

  return (
    <Container maxW="container.md" py={4}>
      <Tabs isFitted variant="enclosed">
        <TabList mb="1em">
          <Tab>Профиль</Tab>
          <Tab>Магазин</Tab>
          <Tab>Перевод</Tab>
        </TabList>

        <TabPanels>
          <TabPanel>
            <UserProfile user={user} />
          </TabPanel>

          <TabPanel>
            <Shop
              userBalance={user.balance}
              onPurchase={handlePurchase}
            />
          </TabPanel>

          <TabPanel>
            <TransferBalance
              userBalance={user.balance}
              onTransfer={handleTransfer}
            />
          </TabPanel>
        </TabPanels>
      </Tabs>
    </Container>
  );
};

export default Home; 