import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Toast from '@arcblock/ux/lib/Toast';
import { api, formatError } from '@blocklet/payment-react';
import { AddOutlined } from '@mui/icons-material';
import {
  Button,
  CircularProgress,
  FormControl,
  FormControlLabel,
  InputLabel,
  MenuItem,
  Select,
  Stack,
  Switch,
  TextField,
} from '@mui/material';
import { useState } from 'react';
import { Controller, FormProvider, useForm } from 'react-hook-form';
import { dispatch } from 'use-bus';

import DrawerForm from '../../../../components/drawer-form';
import MetadataForm from '../../../../components/metadata/form';

interface Vendor {
  id: string;
  vendor_key: string;
  vendor_type: string;
  name: string;
  description: string;
  app_url: string;
  status: 'active' | 'inactive';
  metadata: Record<string, any>;
  created_at: string;
  updated_at: string;
}

interface VendorCreateProps {
  open?: boolean;
  onClose?: () => void;
  onSubmit?: () => void;
  vendorData?: Vendor;
}

interface VendorFormData {
  vendor_key: string;
  vendor_type: string;
  name: string;
  description: string;
  app_url: string;
  status: 'active' | 'inactive';
  metadata: Array<{ key: string; value: string }>;
  app_pid?: string;
  app_logo?: string;
}

export default function VendorCreate({
  open = true,
  onClose = () => {},
  onSubmit: onSubmitCallback = () => {},
  vendorData = undefined,
}: VendorCreateProps) {
  const { t } = useLocaleContext();
  const [loading, setLoading] = useState(false);

  const isEditMode = !!vendorData;

  const defaultValues = vendorData
    ? {
        ...vendorData,
        metadata: vendorData.metadata
          ? Object.entries(vendorData.metadata).map(([key, value]) => ({
              key,
              value: typeof value === 'object' ? JSON.stringify(value) : String(value),
            }))
          : [],
      }
    : {
        vendor_key: '',
        vendor_type: 'launcher',
        name: '',
        description: '',
        app_url: '',
        status: 'inactive' as const,
        metadata: [{ key: 'blockletMetaUrl', value: '' }],
      };

  const methods = useForm<VendorFormData>({
    mode: 'onChange',
    defaultValues,
  });

  const {
    control,
    handleSubmit,
    reset,
    formState: { errors, isValid },
    watch,
  } = methods;

  const watchedValues = watch();

  const validateUrl = (url: string) => {
    if (!url) return t('admin.vendor.appUrlRequired');
    try {
      // eslint-disable-next-line no-new
      new URL(url);
      return true;
    } catch {
      return t('admin.vendor.appUrlInvalid');
    }
  };

  const onSubmit = async (data: VendorFormData) => {
    try {
      setLoading(true);

      // 轻量级校验：检查URL格式
      try {
        // eslint-disable-next-line no-new
        new URL(data.app_url);
      } catch {
        Toast.error(t('admin.vendor.appUrlInvalid'));
        setLoading(false);
        return;
      }

      // 准备提交数据，将 metadata 数组转换为对象
      const { metadata: metadataArray, ...restData } = data;
      const metadataObj = metadataArray.reduce((acc: Record<string, any>, item) => {
        if (item.key && item.value) {
          try {
            // 尝试解析 JSON，如果失败则作为字符串处理
            acc[item.key] = JSON.parse(item.value);
          } catch {
            acc[item.key] = item.value;
          }
        }
        return acc;
      }, {});

      const submitData = {
        ...restData,
        metadata: metadataObj,
      };

      if (isEditMode && vendorData) {
        // 编辑模式：更新供应商
        await api.put(`/api/vendors/${vendorData.id}`, submitData);
        Toast.success(t('admin.vendor.updateSuccess'));
        dispatch('vendor.updated');
      } else {
        // 创建模式：新建供应商
        await api.post('/api/vendors', submitData);
        Toast.success(t('admin.vendor.saved'));
        dispatch('vendor.created');
      }

      reset();
      dispatch('drawer.submitted');
      if (onSubmitCallback) {
        onSubmitCallback();
      }
      if (onClose) {
        onClose();
      }
    } catch (error) {
      console.error('Failed to create vendor:', error);
      Toast.error(formatError(error));
    } finally {
      setLoading(false);
    }
  };

  const handleClose = () => {
    reset();
    if (onClose) {
      onClose();
    }
  };

  return (
    <FormProvider {...methods}>
      <DrawerForm
        icon={isEditMode ? null : <AddOutlined />}
        text={isEditMode ? t('admin.vendor.edit') : t('admin.vendor.create')}
        open={open}
        onClose={handleClose}
        width={800}
        addons={
          <Button variant="contained" size="small" onClick={handleSubmit(onSubmit)} disabled={loading || !isValid}>
            {loading && <CircularProgress size="small" sx={{ mr: 1 }} />}
            {isEditMode ? t('admin.save') : t('admin.vendor.save')}
          </Button>
        }>
        <Stack spacing={3}>
          <Controller
            name="vendor_type"
            control={control}
            rules={{
              required: t('admin.vendor.vendorTypeRequired'),
            }}
            render={({ field }) => (
              <FormControl fullWidth required error={!!errors.vendor_type}>
                <InputLabel>{t('admin.vendor.vendorType')}</InputLabel>
                <Select {...field} label={t('admin.vendor.vendorType')}>
                  <MenuItem value="launcher">{t('admin.vendor.launcher')}</MenuItem>
                  <MenuItem value="didnames">{t('admin.vendor.didnames')}</MenuItem>
                </Select>
              </FormControl>
            )}
          />
          <Controller
            name="vendor_key"
            control={control}
            rules={{
              required: t('admin.vendor.vendorKeyRequired'),
              pattern: {
                value: /^[a-z0-9_]+$/,
                message: t('admin.vendor.vendorKeyInvalid'),
              },
            }}
            render={({ field }) => (
              <TextField
                {...field}
                label={t('admin.vendor.vendorKey')}
                required
                fullWidth
                disabled={isEditMode}
                error={!!errors.vendor_key}
                helperText={errors.vendor_key?.message || t('admin.vendor.vendorKeyHelp')}
              />
            )}
          />
          <Controller
            name="name"
            control={control}
            rules={{ required: t('admin.vendor.nameRequired') }}
            render={({ field }) => (
              <TextField
                {...field}
                label={t('admin.vendor.name')}
                required
                fullWidth
                error={!!errors.name}
                helperText={errors.name?.message || t('admin.vendor.displayNameHelp')}
              />
            )}
          />

          <Controller
            name="description"
            control={control}
            render={({ field }) => (
              <TextField {...field} label={t('admin.vendor.description')} multiline rows={3} fullWidth />
            )}
          />

          <Controller
            name="app_url"
            control={control}
            rules={{
              required: t('admin.vendor.appUrlRequired'),
              validate: validateUrl,
            }}
            render={({ field }) => (
              <TextField
                {...field}
                label={t('admin.vendor.appUrl')}
                required
                fullWidth
                error={!!errors.app_url}
                helperText={errors.app_url?.message || t('admin.vendor.appUrlHelp')}
              />
            )}
          />

          <MetadataForm title={t('common.metadata.label')} />

          <Controller
            name="status"
            control={control}
            render={({ field }) => (
              <FormControlLabel
                sx={{ maxWidth: 'max-content' }}
                control={
                  <Switch
                    checked={field.value === 'active'}
                    onChange={(e) => field.onChange(e.target.checked ? 'active' : 'inactive')}
                  />
                }
                label={watchedValues.status === 'active' ? t('admin.vendor.enabled') : t('admin.vendor.disabled')}
              />
            )}
          />
        </Stack>
      </DrawerForm>
    </FormProvider>
  );
}
