import { Box, Button, Group, Stack, Text, TextInput } from "@mantine/core";
import { Plus, Trash2 } from "lucide-react";

import { PortalFileDropzone } from "@/components/contracts/PortalFileDropzone";
import { INK } from "@/pages/contracts/contract-ui";

export type AdHocDoc = { name: string; file: File | null };

export function ClearanceAdHocUploadSection({
  rows,
  onAdd,
  onRemove,
  onNameChange,
  onFileChange,
  onPreview,
}: {
  rows: AdHocDoc[];
  onAdd: () => void;
  onRemove: (index: number) => void;
  onNameChange: (index: number, name: string) => void;
  onFileChange: (index: number, file: File | null) => void;
  onPreview?: (file: { name: string; url: string; mimeType?: string | null }) => void;
}) {
  return (
    <Box mt="lg">
      <Group justify="space-between" align="center" mb="sm">
        <Box>
          <Text fz={13} fw={700} style={{ color: INK }}>
            Additional documents
          </Text>
          <Text fz={12} c="dimmed">
            Optional supporting files not listed above.
          </Text>
        </Box>
        <Button
          size="compact-sm"
          variant="light"
          color="edr-green"
          leftSection={<Plus size={14} />}
          onClick={onAdd}
        >
          Add document
        </Button>
      </Group>
      <Stack gap="md">
        {rows.map((row, i) => (
          <Box
            key={i}
            p="md"
            style={{
              borderRadius: 14,
              border: "1px solid #E6ECF2",
              background: "#FAFCFE",
            }}
          >
            <Stack gap="sm">
              <Group justify="space-between" wrap="nowrap">
                <TextInput
                  label="Document name"
                  placeholder="e.g. Special permit"
                  value={row.name}
                  onChange={(e) => onNameChange(i, e.currentTarget.value)}
                  style={{ flex: 1 }}
                  radius="md"
                />
                <Button
                  variant="subtle"
                  color="red"
                  mt={24}
                  leftSection={<Trash2 size={14} />}
                  onClick={() => onRemove(i)}
                >
                  Remove
                </Button>
              </Group>
              <PortalFileDropzone
                label="File"
                value={row.file}
                onChange={(file) => onFileChange(i, file)}
                onPreview={onPreview}
              />
            </Stack>
          </Box>
        ))}
      </Stack>
    </Box>
  );
}
