import React from 'react';
import { useFormContext, Controller, type UseFormReturn } from 'react-hook-form';
import { Box, Typography, TextField, Grid, Button } from '@mui/material';
import { useTranslation } from 'react-i18next';
import { EmbeddingModelItem } from '../configuration';
import { PageRankItem } from '../configuration/common-items';

interface CreateGeneralFormProps {
  form?: UseFormReturn;
  onSubmit?: (data: any) => void;
  isSubmitting?: boolean;
  onCancel?: () => void;
  submitButtonText?: string;
  cancelButtonText?: string;
}

function CreateGeneralForm({
  form: propForm,
  onSubmit,
  isSubmitting,
  onCancel,
  submitButtonText,
  cancelButtonText,
}: CreateGeneralFormProps = {}) {
  const { t } = useTranslation();

  const defaultSubmitButtonText = submitButtonText || t('common.save');
  const defaultCancelButtonText = cancelButtonText || t('common.cancel');

  // 优先使用props传递的form，否则使用FormProvider的context
  let contextForm: UseFormReturn | null = null;
  try {
    contextForm = useFormContext();
  } catch (error) {
    contextForm = null;
  }

  const form = propForm || contextForm;

  if (!form) {
    console.error('CreateGeneralForm: No form context found. Component must be used within a FormProvider or receive a form prop.');
    return (
      <Box sx={{ p: 2, textAlign: 'center' }}>
        <Typography color="error">
          {t('form.configurationError')}
        </Typography>
      </Box>
    );
  }

  const { control } = form;

  return (
    <Box sx={{ p: 3 }}>
      <Typography variant="h6" gutterBottom>
        {t('knowledge.basicInfo')}
      </Typography>

      <Grid container spacing={3}>
        {/* 表单字段（去除 avatar / permission / TagsItem） */}
        <Grid size={{ xs: 12 }}>
          <Grid container spacing={2}>
            <Grid size={{ xs: 12 }}>
              <Controller
                name="name"
                control={control}
                rules={{ required: t('knowledge.nameRequired') }}
                render={({ field, fieldState: { error } }) => (
                  <TextField
                    {...field}
                    label={t('knowledge.knowledgeBaseName')}
                    fullWidth
                    required
                    error={!!error}
                    helperText={error?.message}
                  />
                )}
              />
            </Grid>

            <Grid size={{ xs: 12 }}>
              <Controller
                name="description"
                control={control}
                render={({ field }) => (
                  <TextField
                    {...field}
                    label={t('common.description')}
                    fullWidth
                    multiline
                    rows={3}
                    placeholder={t('knowledge.descriptionPlaceholder')}
                  />
                )}
              />
            </Grid>
          </Grid>

          <Grid size={{ xs: 12 }} sx={{ mt: 2 }}>
            <EmbeddingModelItem />
            <PageRankItem />
          </Grid>
        </Grid>
      </Grid>

      {/* 表单操作按钮 - 仅在有onSubmit回调时显示 */}
      {onSubmit && (
        <Box sx={{ mt: 4, display: 'flex', justifyContent: 'flex-end', gap: 2 }}>
          {onCancel && (
            <Button
              variant="outlined"
              onClick={onCancel}
              disabled={isSubmitting}
            >
              {defaultCancelButtonText}
            </Button>
          )}
          <Button
            variant="contained"
            onClick={form ? form.handleSubmit(onSubmit) : undefined}
            disabled={isSubmitting || !form}
          >
            {isSubmitting ? t('common.submitting') : defaultSubmitButtonText}
          </Button>
        </Box>
      )}
    </Box>
  );
}

export default CreateGeneralForm;