import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { FormInput, FormLabel, api } from '@blocklet/payment-react';
import { AddOutlined, DeleteOutlineOutlined } from '@mui/icons-material';
import { Alert, Box, Button, Divider, IconButton, MenuItem, Select, Stack, Typography } from '@mui/material';
import { useEffect, useRef, useState } from 'react';
import { Controller, useFieldArray, useFormContext, useWatch } from 'react-hook-form';

interface Vendor {
  id: string;
  name: string;
  description: string;
  vendor_key: string;
  vendor_type: string;
}

export default function VendorConfig() {
  const { t } = useLocaleContext();
  const { control, setValue, setError: setFormError, clearErrors } = useFormContext();
  const [vendors, setVendors] = useState<Vendor[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const lastItemRef = useRef<HTMLDivElement | null>(null);

  const vendorConfigs = useFieldArray({ control, name: 'vendor_config' });

  useEffect(() => {
    const fetchVendors = async () => {
      try {
        setLoading(true);
        setError(null);
        const response = await api.get('/api/vendors');
        setVendors(response.data?.data || []);
      } catch (err: any) {
        setError(err.message || 'Failed to fetch vendors');
        console.error('Failed to fetch vendors:', err);
      } finally {
        setLoading(false);
      }
    };

    fetchVendors();
  }, []);

  const selectedVendorIds = vendorConfigs.fields.map((item: any) => item.vendor_id);
  const noneSelectedVendors = vendors.filter((v) => !selectedVendorIds.includes(v.id));

  const watchedVendorConfig = useWatch({ control, name: 'vendor_config' });

  const [totalCommission, setTotalCommission] = useState(0);

  useEffect(() => {
    const vendorConfigArray = watchedVendorConfig || [];

    const percentageFields = vendorConfigArray.filter((field: any) => field?.commission_type === 'percentage');

    const total = percentageFields.reduce((sum: number, field: any) => {
      const rate = Number(field?.commission_rate || 0);
      return sum + rate;
    }, 0);

    setTotalCommission(total);

    const isValid = total <= 100;

    if (vendorConfigArray.length > 0) {
      if (isValid) {
        clearErrors('vendor_config_total');
      } else {
        setFormError('vendor_config_total', {
          type: 'manual',
          message: t('admin.product.vendorConfig.totalCommissionExceeded', {
            total: total.toFixed(0),
          }),
        });
      }
    } else {
      clearErrors('vendor_config_total');
    }
  }, [watchedVendorConfig, clearErrors, setFormError, t]);

  const validateTotalCommission = () => {
    return totalCommission <= 100;
  };

  return (
    <Box sx={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column' }} className="vendor-config">
      {error && (
        <Alert severity="error" onClose={() => setError(null)} sx={{ mt: 1 }}>
          {error}
        </Alert>
      )}
      <Stack
        sx={{
          maxHeight: 400,
          minHeight: 'auto',
          overflow: 'auto',
          flex: 1,
        }}>
        {vendorConfigs.fields.map((vendorField: any, index: number) => (
          <Stack
            key={vendorField.id}
            ref={index === vendorConfigs.fields.length - 1 ? lastItemRef : null}
            sx={{ mb: 2, alignItems: 'flex-end', '&:last-child': { mb: 0 } }}
            spacing={2}
            direction="row">
            <Stack direction="row" spacing={2} sx={{ flex: 1 }}>
              <Controller
                name={`vendor_config.${index}.vendor_id`}
                control={control}
                render={({ field }) => {
                  return (
                    <Box sx={{ minWidth: 320 }}>
                      <FormLabel>{t('admin.product.vendorConfig.productCode')}</FormLabel>
                      <Select
                        {...field}
                        fullWidth
                        onChange={(e) => {
                          const vendorId = e.target.value as string;
                          field.onChange(vendorId);

                          // Set default values when selecting a vendor
                          setValue(`vendor_config.${index}.commission_rate`, 20);
                          setValue(`vendor_config.${index}.commission_type`, 'percentage');
                        }}
                        renderValue={(value: string) => {
                          const vendor = vendors.find((v) => v.id === value);
                          if (!vendor) return null;
                          return <Box sx={{ display: 'flex', flexDirection: 'column' }}>{vendor.name}</Box>;
                        }}>
                        {noneSelectedVendors.length ? (
                          noneSelectedVendors.map((vendor) => (
                            <MenuItem key={vendor.id} value={vendor.id} sx={{ gap: 1 }}>
                              <Typography variant="h5">{vendor.name}</Typography>
                              <Typography
                                variant="body2"
                                sx={{
                                  color: 'text.secondary',
                                }}>
                                {vendor.vendor_key}
                              </Typography>
                            </MenuItem>
                          ))
                        ) : (
                          <MenuItem disabled value="">
                            {t('admin.product.vendorConfig.noVendor')}
                          </MenuItem>
                        )}
                      </Select>
                    </Box>
                  );
                }}
              />

              <Controller
                name={`vendor_config.${index}.commission_type`}
                control={control}
                render={({ field }) => (
                  <Box sx={{ minWidth: 140, display: 'none' }}>
                    <FormLabel>{t('admin.product.vendorConfig.commissionType')}</FormLabel>
                    <Select {...field} fullWidth>
                      <MenuItem value="percentage">{t('admin.vendor.percentage')}</MenuItem>
                      <MenuItem value="fixed">{t('admin.vendor.fixedAmount')}</MenuItem>
                    </Select>
                  </Box>
                )}
              />

              <Controller
                name={`vendor_config.${index}.commission_rate`}
                control={control}
                rules={{
                  required: t('admin.product.vendorConfig.commissionRateRequired'),
                  min: { value: 0, message: t('admin.product.vendorConfig.commissionRateMin') },
                  max: { value: 100, message: t('admin.product.vendorConfig.commissionRateMax') },
                }}
                render={({ field }) => (
                  <FormInput
                    {...(field as any)}
                    size="small"
                    placeholder={t('admin.product.vendorConfig.commissionRate')}
                    label={t('admin.product.vendorConfig.commissionRate')}
                    type="number"
                    inputProps={{
                      min: 0,
                      max: 100,
                      step: 10,
                    }}
                    onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
                      field.onChange(e);
                    }}
                  />
                )}
              />
            </Stack>
            <IconButton
              onClick={() => vendorConfigs.remove(index)}
              sx={{
                border: '1px solid',
                borderColor: 'divider',
                borderRadius: 1,
                padding: '8px',
              }}>
              <DeleteOutlineOutlined color="error" sx={{ opacity: 0.75 }} />
            </IconButton>
          </Stack>
        ))}
      </Stack>
      {(watchedVendorConfig || []).length > 0 && (
        <Alert severity={validateTotalCommission() ? 'info' : 'error'} sx={{ mt: 1, mb: 2 }}>
          {validateTotalCommission()
            ? t('admin.product.vendorConfig.totalCommission', {
                total: totalCommission.toFixed(0),
              })
            : t('admin.product.vendorConfig.totalCommissionExceeded', {
                total: totalCommission.toFixed(0),
              })}
        </Alert>
      )}
      <Divider />
      <Stack
        direction="row"
        sx={{
          mt: vendorConfigs.fields.length ? 2 : 1,
          justifyContent: 'space-between',
        }}>
        <Button
          size="small"
          variant="outlined"
          color="primary"
          sx={{ color: 'text.primary' }}
          onClick={() =>
            vendorConfigs.append({
              vendor_id: '',
              commission_rate: 0,
              commission_type: 'percentage',
            })
          }
          disabled={loading || selectedVendorIds.length === vendors.length || noneSelectedVendors.length === 0}>
          <AddOutlined fontSize="small" /> {t('admin.product.vendorConfig.add')}
        </Button>
      </Stack>
    </Box>
  );
}
