import { useEffect, useState } from 'react';
import { Container, Select, Stack, Tabs } from '@mantine/core';
import {
  IconAdjustments,
  IconAlertCircle,
  IconFileText,
  IconFiles,
  IconSettings,
} from '@tabler/icons-react';
import { useTranslation } from 'react-i18next';
import { ErrorState, PageHeader, PageLoader } from '@ema-platform/ui';
import { extractErrorMessage, useGetLicenseTypesQuery, useLocalized } from '@ema-platform/api';
import { BehaviorTab } from '../components/BehaviorTab';
import { DocumentRequirementsTab } from '../components/DocumentRequirementsTab';
import { FormSchemaTab } from '../components/FormSchemaTab';

/**
 * Where an administrator configures what an applicant must fill in and
 * upload for a licence type — the form's sections/fields (with visibility
 * conditions) and its document upload slots (with conditional requirements).
 *
 * Not scoped to CoC/CoP specifically: every active licence type is offered,
 * because a form schema and its document requirements are properties of any
 * licence type, not just certificates. CoC/CoP are simply the first types an
 * administrator is expected to configure this way.
 */
export function CertificateRequirementsPage() {
  const { t } = useTranslation();
  const localized = useLocalized();

  const { data: licenseTypes, isLoading, isError, error, refetch } = useGetLicenseTypesQuery();
  const [typeId, setTypeId] = useState<string | null>(null);

  const options = (licenseTypes?.items ?? [])
    .slice()
    .sort((a, b) => a.sortOrder - b.sortOrder)
    .map((lt) => ({ value: lt.id, label: `${localized(lt.name)} (${lt.key})` }));

  useEffect(() => {
    if (!typeId && licenseTypes?.items?.length) setTypeId(licenseTypes.items[0].id);
  }, [licenseTypes, typeId]);

  const selectedType = licenseTypes?.items?.find((lt) => lt.id === typeId);

  return (
    <Container size="xl" py="md">
      <Stack gap="md">
        <PageHeader
          title={t('certReq.title', 'Certificate requirements')}
          subtitle={t(
            'certReq.subtitle',
            'Configure the form fields and document uploads applicants must complete for a licence type, including conditions on when a requirement applies.',
          )}
          noMargin
        />

        {isError ? (
          <ErrorState
            title={t('certReq.loadFailed', 'Could not load licence types')}
            description={extractErrorMessage(error)}
            onRetry={() => refetch()}
            icon={IconAlertCircle}
          />
        ) : isLoading ? (
          <PageLoader label={t('certReq.loading', 'Loading licence types…')} height={300} />
        ) : (
          <Stack gap="md">
            <Select
              label={t('certReq.licenseType', 'Licence type')}
              placeholder={t('certReq.selectLicenseType', 'Select a licence type')}
              data={options}
              value={typeId}
              onChange={setTypeId}
              searchable
              leftSection={<IconSettings size={15} />}
              maw={480}
            />

            {selectedType && (
              <Tabs defaultValue="schema" keepMounted={false}>
                <Tabs.List>
                  <Tabs.Tab value="schema" leftSection={<IconFileText size={15} />}>
                    {t('certReq.tabSchema', 'Form schema')}
                  </Tabs.Tab>
                  <Tabs.Tab value="documents" leftSection={<IconFiles size={15} />}>
                    {t('certReq.tabDocuments', 'Document requirements')}
                  </Tabs.Tab>
                  <Tabs.Tab value="behavior" leftSection={<IconAdjustments size={15} />}>
                    {t('certReq.tabBehavior', 'Behaviour')}
                  </Tabs.Tab>
                </Tabs.List>

                <Tabs.Panel value="schema" pt="md">
                  <FormSchemaTab licenseType={selectedType} />
                </Tabs.Panel>

                <Tabs.Panel value="documents" pt="md">
                  <DocumentRequirementsTab licenseType={selectedType} />
                </Tabs.Panel>

                <Tabs.Panel value="behavior" pt="md">
                  <BehaviorTab licenseType={selectedType} />
                </Tabs.Panel>
              </Tabs>
            )}
          </Stack>
        )}
      </Stack>
    </Container>
  );
}

export default CertificateRequirementsPage;
