/* eslint-disable react/no-unstable-nested-components */
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { api, formatTime, Status, Table, findCurrency, usePaymentContext } from '@blocklet/payment-react';
import type { TProductExpanded, TMeter } from '@blocklet/payment-types';
import { Add } from '@mui/icons-material';
import { Box, Button, Typography, Alert, Tabs, Tab, Stack } from '@mui/material';
import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';

import ProductsCreate from '../../pages/admin/products/products/create';
import InfoCard from '../info-card';
import ProductActions from '../product/actions';
import { formatProductPrice } from '../../libs/util';

interface MeterProductsProps {
  meterId: string;
  meter?: TMeter;
}

export interface MeterProductsRef {
  refresh: () => void;
}

type ProductType = 'meter' | 'credit';

const fetchMeterProducts = (meterId: string): Promise<{ list: TProductExpanded[]; count: number }> => {
  return api.get(`/api/products?meter_id=${meterId}`).then((res: any) => res.data);
};

const fetchCreditProducts = (meterId: string): Promise<{ list: TProductExpanded[]; count: number }> => {
  return api.get(`/api/products?type=credit&meter_id=${meterId}`).then((res: any) => res.data);
};

export default function MeterProducts({ meterId, meter = undefined }: MeterProductsProps) {
  const { t, locale } = useLocaleContext();
  const { settings } = usePaymentContext();
  const [products, setProducts] = useState<TProductExpanded[]>([]);
  const [loading, setLoading] = useState(false);
  const [creating, setCreating] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState<ProductType>('credit');

  const loadProducts = async (type: ProductType = activeTab) => {
    setLoading(true);
    setError(null);
    try {
      const result = type === 'meter' ? await fetchMeterProducts(meterId) : await fetchCreditProducts(meterId);
      setProducts(result.list);
    } catch (err) {
      console.error('Failed to fetch products:', err);
      setError('Failed to load products');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadProducts();
  }, [meterId, activeTab]);

  const handleTabChange = (_: React.SyntheticEvent, newValue: ProductType) => {
    setActiveTab(newValue);
  };

  const handleCreateProduct = () => {
    setCreating(true);
  };

  const handleCloseCreate = () => {
    setCreating(false);
    loadProducts(); // 刷新产品列表
  };

  if (error) {
    return (
      <Alert severity="error" sx={{ mt: 1 }}>
        {error}
      </Alert>
    );
  }

  const columns = [
    {
      label: t('admin.product.name.label'),
      name: 'name',
      options: {
        filter: false,
        customBodyRenderLite: (_: string, index: number) => {
          const item = products[index];
          if (!item) return null;
          const currency =
            findCurrency(settings.paymentMethods, item.prices[0]?.currency_id ?? '') || settings.baseCurrency;
          return (
            <Link to={`/admin/products/${item.id}`}>
              <InfoCard
                name={item.name}
                description={formatProductPrice(item as any, currency!, locale)}
                logo={item.images[0]}
              />
            </Link>
          );
        },
      },
    },
    {
      label: t('common.status'),
      name: 'active',
      options: {
        filter: false,
        customBodyRenderLite: (_: string, index: number) => {
          const item = products[index];
          if (!item) return null;
          return (
            <Link to={`/admin/products/${item.id}`}>
              <Status label={item?.active ? 'Active' : 'Archived'} color={item?.active ? 'success' : 'default'} />
            </Link>
          );
        },
      },
    },
    {
      label: t('common.createdAt'),
      name: 'created_at',
      options: {
        sort: false,
        customBodyRenderLite: (_: string, index: number) => {
          const item = products[index];
          if (!item) return null;
          return <Link to={`/admin/products/${item.id}`}>{formatTime(item.created_at)}</Link>;
        },
      },
    },
    {
      label: t('common.actions'),
      name: 'id',
      width: 100,
      align: 'center',
      options: {
        sort: false,
        customBodyRenderLite: (_: string, index: number) => {
          const product = products[index];
          if (!product) return null;
          return <ProductActions data={product} onChange={() => loadProducts()} />;
        },
      },
    },
  ];

  const getEmptyText = () => {
    if (activeTab === 'meter') {
      return {
        text: t('admin.meter.products.emptyTip'),
        buttonText: t('admin.meter.products.create'),
      };
    }
    return {
      text: t('admin.meter.creditProducts.emptyTip'),
      buttonText: t('admin.creditProduct.create'),
    };
  };

  const emptyConfig = getEmptyText();

  return (
    <Box>
      <Stack
        direction="row"
        sx={{
          justifyContent: 'space-between',
          alignItems: 'center',
        }}>
        <Tabs
          value={activeTab}
          onChange={handleTabChange}
          sx={{
            flex: '1 0 auto',
            maxWidth: '100%',
            fontSize: 14,
            borderBottom: 1,
            borderColor: 'divider',
            '.Mui-selected': {
              fontSize: '14px !important',
              color: 'primary.main',
            },
          }}>
          <Tab label={t('admin.meter.products.creditCharge')} value="credit" />
          <Tab label={t('admin.meter.products.meterService')} value="meter" />
        </Tabs>
      </Stack>
      <Stack
        direction="row"
        sx={{
          justifyContent: 'flex-end',
          mb: 2,
        }}>
        <Button
          variant="text"
          color="inherit"
          size="small"
          sx={{ color: 'text.link', float: 'right' }}
          startIcon={<Add />}
          onClick={handleCreateProduct}>
          {activeTab === 'meter' ? t('admin.meter.products.create') : t('admin.creditProduct.create')}
        </Button>
      </Stack>
      <Table
        hasRowLink
        data={products}
        columns={columns}
        options={{
          count: products.length,
          page: 0,
          rowsPerPage: products.length,
          pagination: false,
          search: false,
          filter: false,
          sort: false,
          viewColumns: false,
          download: false,
          print: false,
          selectableRows: 'none',
        }}
        loading={loading}
        emptyNodeText={
          <Box>
            <Typography>{emptyConfig.text}</Typography>
            <Button
              size="small"
              variant="text"
              startIcon={<Add />}
              onClick={handleCreateProduct}
              sx={{ mt: 1, color: 'text.link' }}>
              {emptyConfig.buttonText}
            </Button>
          </Box>
        }
      />
      {creating && (
        <ProductsCreate
          open={creating}
          onClose={handleCloseCreate}
          onSubmit={() => loadProducts(activeTab)}
          mode={activeTab === 'credit' ? 'credit' : 'standard'}
          meterId={meterId}
          initialPrice={
            activeTab === 'meter'
              ? {
                  currency_id: meter?.currency_id || '',
                  priceModel: 'credit_metered',
                }
              : {
                  metadata: {
                    credit_config: {
                      currency_id: meter?.currency_id || '',
                    },
                  },
                  name: meter?.unit || '',
                }
          }
        />
      )}
    </Box>
  );
}
