import { useCallback } from 'react';
import { FormProvider } from 'react-hook-form';

import { IconArrowLeft } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import Button from '@material-hu/components/design-system/Buttons/Button';
import HuStepper from '@material-hu/components/design-system/Stepper';
import HuTabs from '@material-hu/components/design-system/Tabs';

import { type ReviewDetailFormQuestions } from 'src/pages/dashboard/performance/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import ReviewInputSection, {
  ReviewInputSectionType,
} from '../../components/ReviewInputSection';
import ReviewNextStepButton from '../../components/ReviewNextStepButton';
import TemplateDescription from '../../components/TemplateDescription';
import CalibrationAnswerPill from '../components/CalibrationAnswerPill';
import CalibrationComparisonDrawer from '../components/CalibrationComparisonDrawer';
import CalibrationHeaderCard from '../components/CalibrationHeaderCard';

import { useCalibrationComparison } from './hooks/useCalibrationComparison';
import { useCalibrationFormState } from './hooks/useCalibrationFormState';
import { useCalibrationFormSteps } from './hooks/useCalibrationFormSteps';
import { type CalibrationFormProps } from './types';
import { isQuestionAnswered, isStatusEditable } from './utils';

const CalibrationForm = ({ cycleId, detail, user }: CalibrationFormProps) => {
  const { t } = useLokaliseTranslation(['performance', 'competencies']);

  const { calibrationReview } = detail;
  const { form, status, formReviewId } = calibrationReview;
  const isReadOnly = !isStatusEditable(status);

  const { openComparison, hasComparison, drawerProps } =
    useCalibrationComparison({ detail });

  const { methods, onFormSubmit, isSubmitting, isValid, buckets } =
    useCalibrationFormState({ cycleId, formReviewId, form, t });

  const {
    availableSectionTypes,
    activeSectionType,
    currentStepIndex,
    isFirstStep,
    isLastStep,
    sectionTabsForHu,
    stepperSteps,
    currentStepQuestions,
    stepHasRequiredQuestion,
    goPrev,
    goNext,
    handleTabChange,
  } = useCalibrationFormSteps({ buckets, t });

  const getHeaderActions = useCallback(
    (question: ReviewDetailFormQuestions) => {
      const showPill = isReadOnly && isQuestionAnswered(question);
      const canCompare = hasComparison(question.id);
      if (!showPill && !canCompare) return undefined;
      return (
        <CalibrationAnswerPill
          showPill={showPill}
          onEyeClick={
            canCompare ? () => openComparison(question.id) : undefined
          }
        />
      );
    },
    [isReadOnly, hasComparison, openComparison],
  );

  if (!form) {
    return (
      <Stack sx={{ alignItems: 'center', py: 4 }}>
        <Typography color="text.secondary">
          {t('performance:calibration.detail.empty_form')}
        </Typography>
      </Stack>
    );
  }

  const canSubmit = isValid && !isSubmitting;

  return (
    <FormProvider {...methods}>
      <Stack
        component="form"
        onSubmit={onFormSubmit}
        sx={{ gap: 3, width: '100%', maxWidth: 880, mx: 'auto', pb: 10 }}
      >
        <CalibrationHeaderCard user={user} />

        {form.description && <TemplateDescription text={form.description} />}

        {availableSectionTypes.length > 0 && (
          <Stack sx={{ gap: 2, width: '100%' }}>
            {availableSectionTypes.length > 1 &&
              (isReadOnly ? (
                <HuTabs
                  value={activeSectionType}
                  tabs={sectionTabsForHu}
                  onTabChange={handleTabChange}
                />
              ) : (
                <HuStepper
                  steps={stepperSteps}
                  currentStep={currentStepIndex}
                />
              ))}

            {activeSectionType === ReviewInputSectionType.FORM &&
              buckets.formQuestions.length > 0 && (
                <ReviewInputSection
                  reviewItems={buckets.formQuestions}
                  type={ReviewInputSectionType.FORM}
                  answered={isReadOnly}
                  getHeaderActions={getHeaderActions}
                />
              )}
            {activeSectionType === ReviewInputSectionType.GOAL &&
              buckets.goalQuestions.length > 0 && (
                <ReviewInputSection
                  canViewGoalDetails={false}
                  reviewItems={buckets.goalQuestions}
                  type={ReviewInputSectionType.GOAL}
                  answered={isReadOnly}
                  getHeaderActions={getHeaderActions}
                />
              )}
            {activeSectionType === ReviewInputSectionType.COMPETENCY &&
              buckets.competencyQuestions.length > 0 && (
                <ReviewInputSection
                  reviewItems={buckets.competencyQuestions}
                  type={ReviewInputSectionType.COMPETENCY}
                  answered={isReadOnly}
                  getHeaderActions={getHeaderActions}
                />
              )}
          </Stack>
        )}

        {!isReadOnly && (
          <Stack sx={{ width: '100%', gap: 2, alignItems: 'flex-end' }}>
            {stepHasRequiredQuestion && (
              <Typography
                variant="body2"
                sx={{ alignSelf: 'stretch', textAlign: 'left' }}
              >
                <Typography component="span">{'* '}</Typography>
                {t('performance:form.required_answer')}
              </Typography>
            )}
            <Stack sx={{ flexDirection: 'row', gap: 2 }}>
              {!isFirstStep && (
                <Button
                  onClick={goPrev}
                  variant="tertiary"
                  size="large"
                  startIcon={<IconArrowLeft />}
                >
                  {t('general:back')}
                </Button>
              )}
              {isLastStep ? (
                <Button
                  type="submit"
                  disabled={!canSubmit}
                  variant="contained"
                  color="primary"
                  size="large"
                  loading={isSubmitting}
                >
                  {t('performance:calibration.detail.submit')}
                </Button>
              ) : (
                <ReviewNextStepButton
                  currentStepQuestions={currentStepQuestions}
                  onClick={goNext}
                  label={t('general:next')}
                />
              )}
            </Stack>
          </Stack>
        )}
      </Stack>
      <CalibrationComparisonDrawer {...drawerProps} />
    </FormProvider>
  );
};

export default CalibrationForm;
