import {
  Badge,
  Box,
  Button,
  Group,
  Paper,
  Stack,
  Text,
  ThemeIcon,
} from "@mantine/core";
import {
  AlertCircle,
  CheckCircle2,
  Clock,
  Download,
  Eye,
  FileText,
} from "lucide-react";
import { isViewable } from "@edr/ui-common";

import { PortalFileDropzone } from "@/components/contracts/PortalFileDropzone";
import { fetchViewableFile, downloadStoredFile } from "@/services/files.service";
import { BORDER, GREEN, INK } from "@/pages/contracts/contract-ui";

type ReviewStatus = "PENDING" | "APPROVED" | "QUERIED" | null;

export interface ClearanceDocumentUploadCardProps {
  label: string;
  required?: boolean;
  reviewStatus?: ReviewStatus;
  note?: string | null;
  uploadedFile?: { id: string; name: string } | null;
  stagedFile?: File | null;
  canUpload?: boolean;
  onStageFile?: (file: File | null) => void;
  onPreview?: (file: { name: string; url: string; mimeType?: string | null }) => void;
}

function StatusBadge({ status, hasFile }: { status?: ReviewStatus; hasFile: boolean }) {
  if (status === "APPROVED") {
    return (
      <Badge
        size="sm"
        variant="light"
        color="edr-green"
        leftSection={<CheckCircle2 size={12} />}
        radius="sm"
      >
        Approved
      </Badge>
    );
  }
  if (status === "QUERIED") {
    return (
      <Badge
        size="sm"
        variant="light"
        color="red"
        leftSection={<AlertCircle size={12} />}
        radius="sm"
      >
        Needs correction
      </Badge>
    );
  }
  if (hasFile) {
    return (
      <Badge
        size="sm"
        variant="light"
        color="blue"
        leftSection={<Clock size={12} />}
        radius="sm"
      >
        Under review
      </Badge>
    );
  }
  return (
    <Badge size="sm" variant="light" color="gray" radius="sm">
      Not uploaded
    </Badge>
  );
}

export function ClearanceDocumentUploadCard({
  label,
  required = false,
  reviewStatus = null,
  note,
  uploadedFile,
  stagedFile = null,
  canUpload = false,
  onStageFile,
  onPreview,
}: ClearanceDocumentUploadCardProps) {
  const queried = reviewStatus === "QUERIED";
  const approved = reviewStatus === "APPROVED";
  const showUpload = canUpload && !approved && onStageFile;
  const canPreviewUploaded =
    uploadedFile && isViewable({ name: uploadedFile.name, url: "" });

  return (
    <Paper
      withBorder
      radius="lg"
      p="md"
      style={{
        borderColor: queried ? "#F0B4B4" : uploadedFile ? `${GREEN}55` : BORDER,
        background: queried
          ? "linear-gradient(160deg, #FDF4F4 0%, #FFFFFF 70%)"
          : uploadedFile
            ? "linear-gradient(160deg, #F6FBF8 0%, #FFFFFF 70%)"
            : "#fff",
      }}
    >
      <Stack gap="sm">
        <Group justify="space-between" align="flex-start" wrap="nowrap">
          <Group gap={12} wrap="nowrap" style={{ minWidth: 0 }}>
            <ThemeIcon
              variant="light"
              color={queried ? "red" : uploadedFile ? "edr-green" : "gray"}
              radius="md"
              size={42}
            >
              <FileText size={20} />
            </ThemeIcon>
            <Box style={{ minWidth: 0 }}>
              <Text fz={14} fw={700} style={{ color: INK }} truncate>
                {label}
                {required ? (
                  <Text component="span" c="red" inherit>
                    {" "}
                    *
                  </Text>
                ) : null}
              </Text>
              {uploadedFile && !stagedFile ? (
                <Text fz={12} c="dimmed" truncate mt={2}>
                  {uploadedFile.name}
                </Text>
              ) : null}
            </Box>
          </Group>
          <StatusBadge status={reviewStatus} hasFile={Boolean(uploadedFile)} />
        </Group>

        {queried && note ? (
          <Box
            p="sm"
            style={{
              borderRadius: 10,
              background: "#FEF2F2",
              border: "1px solid #F0B4B4",
            }}
          >
            <Text fz={12} fw={600} c="red.8">
              Reviewer note
            </Text>
            <Text fz={12} c="red.7" mt={4}>
              {note}
            </Text>
          </Box>
        ) : null}

        {uploadedFile && !stagedFile ? (
          <Group gap={8}>
            {canPreviewUploaded && onPreview ? (
              <Button
                size="compact-sm"
                variant="light"
                color="edr-green"
                leftSection={<Eye size={14} />}
                onClick={() =>
                  void fetchViewableFile(uploadedFile.id, uploadedFile.name).then(
                    onPreview,
                  )
                }
              >
                View
              </Button>
            ) : null}
            <Button
              size="compact-sm"
              variant="default"
              component="button"
              type="button"
              onClick={() =>
                void downloadStoredFile(uploadedFile.id, uploadedFile.name)
              }
              leftSection={<Download size={14} />}
            >
              Download
            </Button>
          </Group>
        ) : null}

        {showUpload ? (
          <PortalFileDropzone
            label={uploadedFile || stagedFile ? "Replace file" : "Upload file"}
            description="PDF or image — drag and drop or browse."
            value={stagedFile}
            onChange={onStageFile}
            replaceMode={Boolean(uploadedFile)}
            onPreview={onPreview}
          />
        ) : null}
      </Stack>
    </Paper>
  );
}
