import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Toast from '@arcblock/ux/lib/Toast';
import { api, findCurrency, formatError, formatTime, useMobile, usePaymentContext } from '@blocklet/payment-react';
import type { TPrice, TProduct, TProductExpanded } from '@blocklet/payment-types';
import { ArrowBackOutlined, InfoOutlined } from '@mui/icons-material';
import {
  Alert,
  AlertTitle,
  Avatar,
  Box,
  Button,
  CircularProgress,
  Divider,
  Stack,
  Tooltip,
  Typography,
} from '@mui/material';
import { styled } from '@mui/system';
import { useRequest, useSetState } from 'ahooks';
import { useNavigate } from 'react-router-dom';

import { isEmpty } from 'lodash';
import { dispatch } from 'use-bus';
import Copyable from '../../../../components/copyable';
import EventList from '../../../../components/event/list';
import InfoMetric from '../../../../components/info-metric';
import InfoRow from '../../../../components/info-row';
import InfoRowGroup from '../../../../components/info-row-group';
import MetadataEditor from '../../../../components/metadata/editor';
import MetadataList from '../../../../components/metadata/list';
import ProductActions from '../../../../components/product/actions';
import AddPrice from '../../../../components/product/add-price';
import ProductCrossSell from '../../../../components/product/cross-sell';
import EditProduct from '../../../../components/product/edit';
import SectionHeader from '../../../../components/section/header';
import { formatProductPrice, goBackOrFallback } from '../../../../libs/util';
import PricesList from '../prices/list';

const getProduct = (id: string): Promise<TProductExpanded> => {
  return api.get(`/api/products/${id}`).then((res: any) => res.data);
};

export default function ProductDetail(props: { id: string }) {
  const { t, locale } = useLocaleContext();
  const { isMobile } = useMobile();
  const navigate = useNavigate();
  const { settings, setLivemode } = usePaymentContext();
  const [state, setState] = useSetState({
    adding: {
      price: false,
    },
    editing: {
      metadata: false,
      product: false,
    },
    loading: {
      metadata: false,
      price: false,
      product: false,
    },
  });

  const { loading, error, data, runAsync } = useRequest(() => getProduct(props.id), {
    onSuccess: (res) => {
      setLivemode(!!res.livemode);
    },
  });

  if (error) {
    return <Alert severity="error">{error.message}</Alert>;
  }

  if (loading || !data) {
    return <CircularProgress />;
  }

  const createProductUpdater = (key: string) => async (updates: TProduct) => {
    try {
      setState((prev) => ({ loading: { ...prev.loading, [key]: true } }));
      await api.put(`/api/products/${props.id}`, updates).then((res: any) => res.data);
      Toast.success(t('common.saved'));
      dispatch('product.updated');
      runAsync();
    } catch (err) {
      console.error(err);
      Toast.error(formatError(err));
    } finally {
      setState((prev) => ({ loading: { ...prev.loading, [key]: false } }));
    }
  };

  const onAddPrice = async (price: TPrice) => {
    try {
      setState((prev) => ({ loading: { ...prev.loading, price: true } }));
      await api.post('/api/prices', { ...price, product_id: props.id });
      Toast.success(t('common.saved'));
      dispatch('price.created');
      runAsync();
    } catch (err) {
      console.error(err);
      Toast.error(formatError(err));
      throw err;
    } finally {
      setState((prev) => ({ loading: { ...prev.loading, price: false } }));
    }
  };

  const onUpdateMetadata = createProductUpdater('metadata');
  const onUpdateAll = createProductUpdater('product');
  const onChange = (action: string) => {
    if (action === 'remove') {
      navigate('/admin/products');
    } else {
      runAsync();
    }
  };

  const isLocked = data.locked || (!isEmpty(data.prices) && data.prices.some((x) => x.locked));
  const handleEditMetadata = () => {
    setState((prev) => ({ editing: { ...prev.editing, metadata: true } }));
  };

  const defaultCurrency =
    findCurrency(settings.paymentMethods, data?.default_price?.currency_id) || settings.baseCurrency;

  return (
    <Root direction="column" spacing={2.5} sx={{ mb: 4 }}>
      <Box>
        {data.active === false && (
          <Alert severity="warning">
            <AlertTitle>{t('admin.product.archived')}</AlertTitle>
            {t('admin.product.archivedTip')}
          </Alert>
        )}
        {isLocked && (
          <Alert severity="warning" sx={{ mb: 1 }}>
            {t('admin.product.locked')}
          </Alert>
        )}
        <Stack
          className="page-header"
          direction="row"
          sx={{
            justifyContent: 'space-between',
            alignItems: 'center',
          }}>
          <Stack
            direction="row"
            onClick={() => goBackOrFallback('/admin/products')}
            sx={{
              alignItems: 'center',
              fontWeight: 'normal',
              cursor: 'pointer',
            }}>
            <ArrowBackOutlined fontSize="small" sx={{ mr: 0.5, color: 'text.secondary' }} />
            <Typography variant="h6" sx={{ color: 'text.secondary', fontWeight: 'normal' }}>
              {t('admin.products')}
            </Typography>
          </Stack>
          <ProductActions data={data} onChange={onChange} variant="normal" />
        </Stack>
        <Box
          sx={{
            mt: 4,
            mb: 3,
            display: 'flex',

            gap: {
              xs: 2,
              sm: 2,
              md: 5,
            },

            flexWrap: 'wrap',

            flexDirection: {
              xs: 'column',
              sm: 'column',
              md: 'row',
            },

            alignItems: {
              xs: 'flex-start',
              sm: 'flex-start',
              md: 'center',
            },
          }}>
          <Stack
            direction="row"
            sx={{
              justifyContent: 'space-between',
              alignItems: 'center',
            }}>
            <Stack
              direction="row"
              spacing={1}
              sx={{
                alignItems: 'center',
              }}>
              {data.images.length > 0 && (
                <Avatar src={data.images[0]} alt={data.name} variant="square" sx={{ width: '52px', height: '52px' }} />
              )}
              <Stack
                direction="column"
                sx={{
                  alignItems: 'flex-start',
                  justifyContent: 'space-around',
                }}>
                <Typography
                  variant="h2"
                  sx={{
                    color: 'text.primary',
                  }}>
                  {data.name}
                </Typography>
                <Typography
                  variant="subtitle1"
                  sx={{
                    color: 'text.lighter',
                  }}>
                  {formatProductPrice(data as any, defaultCurrency, locale)}
                </Typography>
              </Stack>
            </Stack>
          </Stack>
          <Stack
            className="section-body"
            sx={{
              justifyContent: 'flex-start',
              flexWrap: 'wrap',

              'hr.MuiDivider-root:last-child': {
                display: 'none',
              },

              flexDirection: {
                xs: 'column',
                sm: 'column',
                md: 'row',
              },

              alignItems: 'flex-start',

              gap: {
                xs: 1,
                sm: 1,
                md: 3,
              },
            }}>
            <InfoMetric label={t('common.id')} value={<Copyable text={props.id} style={{ marginLeft: 4 }} />} divider />
            <InfoMetric label={t('common.createdAt')} value={formatTime(data.created_at)} divider />
          </Stack>
        </Box>
        <Divider />
      </Box>
      <Stack
        sx={{
          flexDirection: {
            xs: 'column',
            lg: 'row',
          },
          gap: {
            xs: 2.5,
            md: 4,
          },
          '.payment-link-column-1': {
            minWidth: {
              xs: '100%',
              lg: '600px',
            },
          },
          '.payment-link-column-2': {
            width: {
              xs: '100%',
              md: '100%',
              lg: '320px',
            },
            maxWidth: {
              xs: '100%',
              md: '33%',
            },
          },
        }}>
        <Box
          className="payment-link-column-1"
          sx={{
            flex: 1,
            gap: 2.5,
            display: 'flex',
            flexDirection: 'column',
          }}>
          <Box className="section" sx={{ containerType: 'inline-size' }}>
            <SectionHeader title={t('admin.details')}>
              <Button
                variant="text"
                color="inherit"
                size="small"
                sx={{ color: 'text.link' }}
                onClick={() => setState((prev) => ({ editing: { ...prev.editing, product: true } }))}>
                {t('common.edit')}
              </Button>
            </SectionHeader>
            <InfoRowGroup
              sx={{
                display: 'grid',
                gridTemplateColumns: {
                  xs: 'repeat(1, 1fr)',
                  xl: 'repeat(2, 1fr)',
                },
                '@container (min-width: 1000px)': {
                  gridTemplateColumns: 'repeat(2, 1fr)',
                },
                '.info-row-wrapper': {
                  gap: 1,
                  flexDirection: {
                    xs: 'column',
                    xl: 'row',
                  },
                  alignItems: {
                    xs: 'flex-start',
                    xl: 'center',
                  },
                  '@container (min-width: 1000px)': {
                    flexDirection: 'row',
                    alignItems: 'center',
                  },
                },
              }}>
              <InfoRow label={t('admin.product.name.label')} value={data.name} />

              <InfoRow label={t('admin.product.description.label')} value={data.description} />
              <InfoRow label={t('admin.product.statement_descriptor.label')} value={data.statement_descriptor} />
              <InfoRow label={t('admin.product.unit_label.label')} value={data.unit_label} />
              <InfoRow label={t('admin.product.features.label')} value={data.features.map((x) => x.name).join(',')} />
              <InfoRow label={t('common.updatedAt')} value={formatTime(data.updated_at)} />
              <InfoRow
                label={t('admin.product.image.label')}
                value={
                  data.images.length ? (
                    <Avatar
                      src={data.images[0]}
                      alt={data.name}
                      variant="square"
                      sx={{ width: '160px', height: '160px' }}
                    />
                  ) : (
                    <Typography
                      variant="body2"
                      sx={{
                        color: 'text.lighter',
                      }}>
                      {t('empty.image')}
                    </Typography>
                  )
                }
              />
              {state.editing.product && (
                <EditProduct
                  product={data}
                  loading={state.loading.product}
                  onSave={onUpdateAll}
                  onCancel={() => setState((prev) => ({ editing: { ...prev.editing, product: false } }))}
                />
              )}
            </InfoRowGroup>
          </Box>
          <Divider />
          <Box className="section">
            <SectionHeader title={t('admin.product.pricing')}>
              <Button
                variant="text"
                color="inherit"
                size="small"
                sx={{ color: 'text.link' }}
                onClick={() => setState((prev) => ({ adding: { ...prev.adding, price: true } }))}>
                {t('admin.price.add')}
              </Button>
            </SectionHeader>
            <Box className="section-body">
              <PricesList product={data as any} onChange={runAsync} />
              {state.adding.price && (
                <AddPrice
                  loading={state.loading.price}
                  onSave={onAddPrice}
                  productType={data.type}
                  onCancel={() => setState((prev) => ({ adding: { ...prev.adding, price: false } }))}
                />
              )}
            </Box>
          </Box>
          <Divider />
          {data.type === 'service' && (
            <>
              <Box className="section">
                <SectionHeader title={t('admin.product.vendorConfig.title')}>
                  <Button
                    variant="text"
                    color="inherit"
                    size="small"
                    sx={{ color: 'text.link' }}
                    onClick={() => setState((prev) => ({ editing: { ...prev.editing, product: true } }))}>
                    {t('common.edit')}
                  </Button>
                </SectionHeader>
                <Box className="section-body">
                  {data.vendor_config && data.vendor_config.length > 0 ? (
                    <Stack spacing={2}>
                      {/* 总分成比例信息 */}
                      {(() => {
                        const totalPercentage = data.vendor_config
                          .filter((v: any) => v.commission_type === 'percentage')
                          .reduce((sum: number, v: any) => sum + (v.commission_rate || 0), 0);

                        return (
                          <Typography variant="body2" sx={{ color: 'text.secondary', mb: 1 }}>
                            {t('admin.product.vendorConfig.totalCommission', {
                              total: totalPercentage.toFixed(0),
                            })}
                          </Typography>
                        );
                      })()}
                      {data.vendor_config.map((vendor: any) => (
                        <Box
                          key={`vendor-${vendor.vendor_id}`}
                          sx={{
                            p: 2,
                            border: '1px solid',
                            borderColor: 'divider',
                            borderRadius: 1,
                            backgroundColor: 'background.paper',
                            maxWidth: '600px',
                          }}>
                          <Stack direction="row" sx={{ justifyContent: 'space-between', alignItems: 'center' }}>
                            <Box>
                              <Typography variant="body1" sx={{ color: 'text.primary', fontWeight: 500 }}>
                                {vendor.name || vendor.vendor_key || vendor.vendor_id}
                              </Typography>
                              {vendor.description && (
                                <Typography variant="body2" sx={{ color: 'text.secondary', mt: 0.5 }}>
                                  {vendor.description}
                                </Typography>
                              )}
                            </Box>
                            <Stack direction="row" spacing={3} sx={{ alignItems: 'center' }}>
                              <Typography variant="body2" sx={{ color: 'text.secondary' }}>
                                {vendor.commission_type === 'percentage'
                                  ? t('admin.vendor.commission')
                                  : t('admin.vendor.fixedAmount')}
                              </Typography>
                              <Typography variant="body1" sx={{ color: 'text.primary', fontWeight: 600 }}>
                                {vendor.commission_rate}
                                {vendor.commission_type === 'percentage' ? '%' : ''}
                              </Typography>
                            </Stack>
                          </Stack>
                        </Box>
                      ))}
                    </Stack>
                  ) : (
                    <Typography variant="body2" sx={{ color: 'text.secondary', textAlign: 'center', py: 2 }}>
                      {t('admin.product.vendorConfig.empty')}
                    </Typography>
                  )}
                </Box>
              </Box>
              <Divider />
            </>
          )}
          <Box className="section">
            <SectionHeader title={t('admin.events.title')} />
            <Box className="section-body">
              <EventList
                features={{ toolbar: false }}
                object_id={[data.id, ...data.prices.map((x) => x.id)].join(',')}
              />
            </Box>
          </Box>
        </Box>
        {isMobile && <Divider />}
        <Box className="payment-link-column-2" sx={{ gap: 2.5, display: 'flex', flexDirection: 'column' }}>
          <Box className="section">
            <SectionHeader
              title={
                <Stack
                  direction="row"
                  spacing={1}
                  sx={{
                    alignItems: 'center',
                  }}>
                  <Typography
                    variant="h3"
                    sx={{
                      fontSize: {
                        xs: '18px',
                        md: '1.09375rem',
                      },
                    }}>
                    {t('admin.product.cross_sell.title')}
                  </Typography>
                  <Tooltip title={t('admin.product.currencyNotAligned')}>
                    <InfoOutlined sx={{ color: 'text.lighter' }} fontSize="small" />
                  </Tooltip>
                </Stack>
              }
            />
            <Box className="section-body">
              <ProductCrossSell data={data} onChange={runAsync} />
            </Box>
          </Box>
          <Divider />
          <Box className="section">
            <SectionHeader title={t('common.metadata.label')}>
              <Button
                variant="text"
                color="inherit"
                size="small"
                sx={{ color: 'text.link' }}
                disabled={state.editing.metadata}
                onClick={handleEditMetadata}>
                {t('common.edit')}
              </Button>
            </SectionHeader>
            <Box className="section-body">
              <MetadataList data={data.metadata} handleEditMetadata={handleEditMetadata} />
              {state.editing.metadata && (
                <MetadataEditor
                  data={data}
                  loading={state.loading.metadata}
                  onSave={onUpdateMetadata}
                  onCancel={() => setState((prev) => ({ editing: { ...prev.editing, metadata: false } }))}
                />
              )}
            </Box>
          </Box>
        </Box>
      </Stack>
    </Root>
  );
}

const Root = styled(Stack)``;
