import { Divider, Paper, Stack, Table, Text, Title } from "@mantine/core";
import {
  conditionHolds,
  type Attachment,
  type FormSectionConfig,
  type LicenseTypeRequirements,
} from "@ema-platform/api";
import { DocumentSlots } from "./DocumentSlots";

interface Props {
  /** Every form section (not just the "review" group) in wizard-step order. */
  sections: FormSectionConfig[];
  formData: Record<string, Record<string, unknown>>;
  localized: (value: { en?: string; am?: string } | undefined) => string;
  config: LicenseTypeRequirements;
  attachments: Attachment[];
  applicationId: string;
}

/**
 * Read-only "what was filed" view for a submitted application: every
 * answered section as a labelled table, then the uploaded documents.
 *
 * Shown instead of the wizard once there is nothing left to step through —
 * the stepper is for filling a form in, not for re-reading one that is
 * already someone else's decision to make.
 */
export function ApplicationSummary({
  sections,
  formData,
  localized,
  config,
  attachments,
  applicationId,
}: Props) {
  return (
    <Paper withBorder p="lg" radius="md">
      <Stack gap="lg">
        {sections.map((section) => (
          <div key={section.key}>
            <Text fw={600} fz="sm" tt="uppercase" c="gray.6" mb="sm">
              {localized(section.title)}
            </Text>
            <Table withTableBorder withColumnBorders>
              <Table.Tbody>
                {(section.fields ?? [])
                  .filter((f) => conditionHolds(f.showWhen, formData))
                  .map((field) => (
                    <Table.Tr key={field.key}>
                      <Table.Td w="45%">
                        <Text size="xs" c="dimmed">
                          {localized(field.label)}
                        </Text>
                      </Table.Td>
                      <Table.Td>
                        <Text size="sm">
                          {String(formData[section.key]?.[field.key] ?? "—")}
                        </Text>
                      </Table.Td>
                    </Table.Tr>
                  ))}
              </Table.Tbody>
            </Table>
          </div>
        ))}

        <div>
          <Divider mb="md" />
          <Title order={5} mb="sm">
            Documents
          </Title>
          <DocumentSlots
            requirements={config.documentRequirements}
            attachments={attachments}
            formData={formData}
            ownerType="APPLICATION"
            ownerId={applicationId}
            readOnly
            onUploaded={() => {
              // Read-only here — nothing to react to, but DocumentSlots
              // requires the callback.
            }}
          />
        </div>
      </Stack>
    </Paper>
  );
}
