import React, { useEffect, useState } from "react";
import {
  Drawer,
  Stack,
  Group,
  Title,
  Text,
  Badge,
  MultiSelect,
  NumberInput,
  Select,
  Button,
  Textarea,
  Divider,
  ScrollArea,
  Avatar,
  Paper,
  Box,
  Modal,
  LoadingOverlay,
  Timeline,
  Tooltip,
  Card,
  Stepper,
} from "@mantine/core";
import { useDisclosure } from "@mantine/hooks";
import { notifications } from "@mantine/notifications";
import {
  IconArrowLeft,
  IconMessage,
  IconUser,
  IconCalendar,
  IconCheck,
  IconAlertCircle,
  IconSend,
  IconGitPullRequest,
  IconCornerDownRight,
  IconClock,
  IconEdit,
  IconFileCode,
  IconEye,
} from "@tabler/icons-react";
import moment from "moment";
import { getWorkflowTaskByEntity } from "@/lib/features/workflow/query";
import {
  upsertWorkflowTask,
  addWorkflowComment,
  createChangeRequest,
  resolveChangeRequest,
} from "@/lib/features/workflow/action";
import { getAdminUsers } from "@/lib/features/users/query";
import type { AdminUser } from "@/lib/features/users/types";
import type {
  WorkflowTask,
  WorkflowStatus,
  WorkflowEntityType,
  WorkflowComment,
  WorkflowChangeRequest,
} from "@/lib/features/workflow/types";
import {
  isEDMEntity,
  WORKFLOW_STATES,
  WORKFLOW_STATE_COLOR,
  WORKFLOW_STATE_LABEL,
} from "@/lib/features/workflow/types";
import { useUser } from "@/providers/UserProvider";

interface Props {
  opened: boolean;
  onClose: () => void;
  entityType: WorkflowEntityType;
  entityId: string;
  /**
   * Files a change request on this record can point at.
   *
   * Supplied by the caller because only it knows what "the files" are — the
   * templates in a folder, the one template on a detail page, the open tabs in
   * the workspace. Empty means requests can only be filed against the whole
   * record.
   */
  crTargets?: { value: string; label: string }[];
  /** Pre-selected target, e.g. the file the editor is showing. */
  defaultCrTarget?: string | null;
  /** Line to pre-fill, e.g. where the cursor was. */
  defaultCrLine?: number | null;
  onWorkflowUpdated?: (status: WorkflowStatus) => void;
}

/**
 * One line explaining what each state means, for the header under the badge.
 *
 * Labels and colours are NOT repeated here — they come from the shared maps in
 * features/workflow/types, which the list views also read. Three copies of
 * "what colour is TESTED" is how a badge ends up green in one view and teal in
 * the next.
 */
const STATUS_DESC: Record<string, string> = {
  CONFIGURATION_DRAFT: "Configuration is being set up by the administrator.",
  READY_FOR_CONTENT: "Configuration is done. Ready for copywriters to write content.",
  CONTENT_IN_PROGRESS: "Copywriters are actively working on the content.",
  READY_FOR_REVIEW: "Content is submitted and waiting for verification.",
  CHANGE_REQUESTED: "A reviewer asked for changes. See the requests below.",

  DEV_IN_PROGRESS: "Being built. Nobody else needs to look at it yet.",
  DEV_COMPLETED: "Build finished and handed over.",
  READY_FOR_TEST: "Waiting for a tester to pick it up.",
  TESTING: "Test sends going out — checking how it renders across mail clients.",
  TESTED: "Renders correctly everywhere it was checked.",
  IN_REVIEW: "Being reviewed against the brief before it can go out.",
  PUBLISHED: "Live. This is the only state that means it has gone out.",

  // Legacy states, kept so an old task still explains itself.
  DRAFT: "Being written.",
  VERIFIED: "Record is verified and locked.",
  APPROVED: "Signed off by the owner.",
  READY_TO_PUBLISH: "Cleared to send.",
};

/** Label, colour and description of one state, from the shared source. */
const statusMeta = (status: string) => ({
  label: WORKFLOW_STATE_LABEL[status] ?? status,
  color: WORKFLOW_STATE_COLOR[status] ?? "gray",
  desc: STATUS_DESC[status] ?? "",
});

/**
 * Forward path per entity type: the shared state list minus CHANGE_REQUESTED.
 *
 * CHANGE_REQUESTED is a sideways move a reviewer makes from anywhere, not a
 * stage you progress into, so it does not belong in the stepper — showing it
 * would read as though every record is meant to pass through it.
 */
const STAGES_BY_ENTITY = Object.fromEntries(
  Object.entries(WORKFLOW_STATES).map(([entity, states]) => [
    entity,
    states.filter((state) => state !== "CHANGE_REQUESTED"),
  ]),
) as Record<WorkflowEntityType, WorkflowStatus[]>;

const STAGE_ICONS: Record<string, React.ReactNode> = {
  CONFIGURATION_DRAFT: <IconFileCode size={16} />,
  DRAFT: <IconFileCode size={16} />,
  READY_FOR_CONTENT: <IconSend size={16} />,
  CONTENT_IN_PROGRESS: <IconEdit size={16} />,
  READY_FOR_REVIEW: <IconEye size={16} />,

  DEV_IN_PROGRESS: <IconFileCode size={16} />,
  DEV_COMPLETED: <IconGitPullRequest size={16} />,
  READY_FOR_TEST: <IconSend size={16} />,
  TESTING: <IconSend size={16} />,
  TESTED: <IconCheck size={16} />,
  IN_REVIEW: <IconEye size={16} />,
  PUBLISHED: <IconCheck size={16} />,

  VERIFIED: <IconCheck size={16} />,
  APPROVED: <IconCheck size={16} />,
  READY_TO_PUBLISH: <IconCheck size={16} />,
};


export const WorkflowSidebar: React.FC<Props> = ({
  opened,
  onClose,
  entityType,
  entityId,
  crTargets = [],
  defaultCrTarget = null,
  defaultCrLine = null,
  onWorkflowUpdated,
}) => {
  const { user: currentUser } = useUser();
  const [task, setTask] = useState<WorkflowTask | null>(null);
  const [users, setUsers] = useState<AdminUser[]>([]);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);

  // Comment state
  const [commentText, setCommentText] = useState("");

  // Change request modal state
  const [crOpened, { open: openCr, close: closeCr }] = useDisclosure(false);
  const [crDescription, setCrDescription] = useState("");
  const [crTarget, setCrTarget] = useState<string | null>(defaultCrTarget);
  const [crLine, setCrLine] = useState<string | number>(defaultCrLine ?? "");
  const [crAssignee, setCrAssignee] = useState<string | null>(null);

  // The caller can change which file is open while the drawer stays mounted, so
  // the prefill has to follow it rather than only apply on first mount.
  useEffect(() => {
    setCrTarget(defaultCrTarget);
    setCrLine(defaultCrLine ?? "");
  }, [defaultCrTarget, defaultCrLine]);

  const loadData = async () => {
    setLoading(true);
    try {
      const [taskRes, usersRes] = await Promise.all([
        getWorkflowTaskByEntity(entityType, entityId),
        getAdminUsers(1, 150),
      ]);

      if (taskRes.success && taskRes.data) {
        setTask(taskRes.data);
      }
      if ("success" in usersRes && usersRes.success && usersRes.data) {
        setUsers(usersRes.data.users || []);
      }
    } catch (err) {
      notifications.show({
        color: "red",
        message: "Failed to load workflow information",
      });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (opened && entityId) {
      loadData();
    }
  }, [opened, entityId]);

  const handleAssigneeChange = async (userIds: string[]) => {
    if (!task) return;
    setSubmitting(true);
    try {
      const res = await upsertWorkflowTask({
        entity_type: entityType,
        entity_id: entityId,
        assignee_ids: userIds,
        status: task.status,
      });

      if (res.success && res.data) {
        notifications.show({
          color: "green",
          message: userIds.length > 0 ? "Task assigned successfully" : "Task unassigned",
        });
        // Reload details to capture the log and changes
        await loadData();
      } else {
        notifications.show({
          color: "red",
          message: res.message || "Failed to update assignees",
        });
      }
    } catch {
      notifications.show({
        color: "red",
        message: "Failed to update assignees",
      });
    } finally {
      setSubmitting(false);
    }
  };

  const handleStatusChange = async (newStatus: WorkflowStatus) => {
    if (!task) return;
    setSubmitting(true);
    try {
      const res = await upsertWorkflowTask({
        entity_type: entityType,
        entity_id: entityId,
        status: newStatus,
        assignee_id: task.assignee_id,
      });

      if (res.success && res.data) {
        notifications.show({
          color: "green",
          message: `Workflow status updated to: ${statusMeta(newStatus).label}`,
        });
        onWorkflowUpdated?.(newStatus);
        await loadData();
      } else {
        notifications.show({
          color: "red",
          message: res.message || "Failed to update status",
        });
      }
    } catch {
      notifications.show({
        color: "red",
        message: "Failed to update status",
      });
    } finally {
      setSubmitting(false);
    }
  };

  const handleAddComment = async () => {
    if (!task?.id || !commentText.trim()) return;
    setSubmitting(true);
    try {
      const res = await addWorkflowComment(task.id, commentText.trim());
      if (res.success) {
        setCommentText("");
        notifications.show({ color: "green", message: "Comment added" });
        await loadData();
      } else {
        notifications.show({
          color: "red",
          message: res.message || "Failed to add comment",
        });
      }
    } catch {
      notifications.show({ color: "red", message: "Failed to add comment" });
    } finally {
      setSubmitting(false);
    }
  };

  const handleCreateChangeRequest = async () => {
    if (!task?.id || !crDescription.trim()) return;
    setSubmitting(true);
    try {
      const parsedLine = Number(crLine);
      const res = await createChangeRequest(task.id, crDescription.trim(), {
        targetRef: crTarget,
        targetLabel: crTargets.find((t) => t.value === crTarget)?.label ?? null,
        lineNumber: Number.isInteger(parsedLine) && parsedLine > 0 ? parsedLine : null,
        assigneeId: crAssignee,
      });
      if (res.success) {
        setCrDescription("");
        setCrLine("");
        setCrAssignee(null);
        closeCr();
        notifications.show({
          color: "orange",
          message: "Change request submitted successfully",
        });
        onWorkflowUpdated?.("CHANGE_REQUESTED");
        await loadData();
      } else {
        notifications.show({
          color: "red",
          message: res.message || "Failed to submit change request",
        });
      }
    } catch {
      notifications.show({
        color: "red",
        message: "Failed to submit change request",
      });
    } finally {
      setSubmitting(false);
    }
  };

  const handleResolveChangeRequest = async (crId: string) => {
    setSubmitting(true);
    try {
      const res = await resolveChangeRequest(crId);
      if (res.success) {
        notifications.show({
          color: "green",
          message: "Change request resolved. Ready to resume.",
        });
        onWorkflowUpdated?.("CONTENT_IN_PROGRESS");
        await loadData();
      } else {
        notifications.show({
          color: "red",
          message: res.message || "Failed to resolve change request",
        });
      }
    } catch {
      notifications.show({
        color: "red",
        message: "Failed to resolve change request",
      });
    } finally {
      setSubmitting(false);
    }
  };

  const selectData = users.map((u) => ({
    value: u.id,
    label: `${u.first_name} ${u.last_name || ""} (${u.email})`,
  }));

  const stages = STAGES_BY_ENTITY[entityType] ?? STAGES_BY_ENTITY.MEMBER_OFFER;
  const currentStatus = task?.status || stages[0]!;
  const statusInfo = statusMeta(currentStatus);

  /**
   * CHANGE_REQUESTED is not a stage, so the stepper has nowhere to point. Show
   * the review stage instead — that is where the item actually sits, waiting to
   * go back through it.
   */
  const reviewStage = stages.includes("READY_FOR_REVIEW")
    ? "READY_FOR_REVIEW"
    : "IN_REVIEW";
  const activeIndex = stages.indexOf(
    currentStatus === "CHANGE_REQUESTED" ? reviewStage : currentStatus,
  );
  // The last stage is "done", so the stepper is complete rather than on it.
  const stepperActiveIndex =
    currentStatus === stages[stages.length - 1] ? stages.length : activeIndex;

  const isEdm = isEDMEntity(entityType);
  const changeRequested = currentStatus === "CHANGE_REQUESTED";

  /**
   * Neighbours in the stage list, which is what the forward and back buttons
   * offer.
   *
   * CHANGE_REQUESTED is off the path, so its neighbours are named rather than
   * derived: forward means back into review (what you do once the requests are
   * resolved), not past it — activeIndex points AT the review stage, so
   * index + 1 would skip the review that was just asked for.
   */
  const prevStage = changeRequested
    ? stages[0] ?? null
    : activeIndex > 0
      ? stages[activeIndex - 1]
      : null;
  const nextStage = changeRequested
    ? reviewStage
    : activeIndex >= 0 && activeIndex < stages.length - 1
      ? stages[activeIndex + 1]
      : null;

  // Combine comments and change requests into a chronological history stream
  interface HistoryItem {
    id: string;
    type: "comment" | "change_request";
    date: string;
    author: string;
    content: string;
    raw: any;
  }

  const historyItems: HistoryItem[] = [];

  if (task?.comments) {
    task.comments.forEach((c) => {
      historyItems.push({
        id: c.id,
        type: "comment",
        date: c.created_at,
        author: `${c.author_first_name || "Unknown"} ${c.author_last_name || ""
          }`.trim(),
        content: c.comment_text,
        raw: c,
      });
    });
  }

  if (task?.change_requests) {
    task.change_requests.forEach((cr) => {
      historyItems.push({
        id: cr.id,
        type: "change_request",
        date: cr.created_at,
        author: `${cr.requester_first_name || "Unknown"} ${cr.requester_last_name || ""
          }`.trim(),
        content: `Requested Changes: ${cr.description}`,
        raw: cr,
      });
    });
  }

  // Sort history items chronologically (newest at bottom)
  historyItems.sort(
    (a, b) => new Date(a.date).getTime() - new Date(b.date).getTime(),
  );

  return (
    <Drawer
      opened={opened}
      onClose={onClose}
      position="right"
      size="lg"
      title={
        <Title order={4}>
          Workflow & Assignments
        </Title>
      }
      styles={{
        header: { borderBottom: "1px solid #e9ecef", paddingBottom: "15px" },
        body: { padding: 0, height: "calc(100vh - 70px)" },
      }}
    >
      <Box style={{ position: "relative", height: "100%" }}>
        <LoadingOverlay visible={loading} overlayProps={{ blur: 1 }} />

        {!loading && (
          <FlexDirectionWrapper>
            {/* Top Summary Block */}
            <Paper
              p="md"
              radius={0}
              style={{
                backgroundColor: "#f8f9fa",
                borderBottom: "1px solid #e9ecef"
              }}
            >
              <Stack gap="xs">
                <Group justify="space-between">
                  <Text size="sm" fw={600} c="dimmed">
                    STATUS
                  </Text>
                  <Badge color={statusInfo.color} size="lg" radius="md">
                    {statusInfo.label}
                  </Badge>
                </Group>
                <Text size="xs" c="dimmed">
                  {statusInfo.desc}
                </Text>

                {/* Visual Workflow Steps Path */}
                <Stepper
                  active={stepperActiveIndex}
                  color="dark"
                  size="sm"
                  styles={{
                    steps: {
                      paddingInline: "14px",
                    },
                    stepWrapper: {
                      border: "1px dashed #dee2e6",
                      padding: "2px",
                      borderRadius: "100%",
                    },
                    stepBody: {
                      marginLeft: 0,
                      textAlign: "center",
                    },
                    stepLabel: {
                      fontSize: "11px",
                      fontWeight: 600,
                      textAlign: "center",
                    },
                    stepDescription: {
                      fontSize: "10px",
                      textAlign: "center",
                      whiteSpace: "nowrap",
                    },
                    stepIcon: {
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                    }
                  }}
                >
                  {stages.map((stage, i) => {
                    // CHANGE_REQUESTED hijacks the review step rather than
                    // adding one, so the path length never changes under you.
                    const isBlockedReview =
                      stage === reviewStage && currentStatus === "CHANGE_REQUESTED";
                    const icon = isBlockedReview ? (
                      <IconAlertCircle size={16} />
                    ) : (
                      STAGE_ICONS[stage] ?? <IconFileCode size={16} />
                    );
                    return (
                      <Stepper.Step
                        key={stage}
                        label={`Step ${i + 1}`}
                        description={statusMeta(stage).label}
                        icon={icon}
                        completedIcon={icon}
                        color={isBlockedReview ? "red" : undefined}
                        style={{
                          display: "flex",
                          flexDirection: "column",
                          alignItems: "center",
                          justifyContent: "center",
                          textAlign: "center",
                          gap: "10px",
                        }}
                      />
                    );
                  })}
                </Stepper>
              </Stack>
            </Paper>

            <Paper p="md" radius={0} style={{ borderBottom: "1px solid #e9ecef" }}>
              <Stack gap="xs">
                <MultiSelect
                  label="Assigned To"
                  placeholder="Unassigned"
                  data={selectData}
                  value={task?.assignee_ids || []}
                  onChange={handleAssigneeChange}
                  disabled={submitting}
                  clearable
                  leftSection={<IconUser size={16} />}
                />

                {/* Overlapping Avatar Group for Assignees */}
                {task?.assignees && task.assignees.length > 0 && (
                  <Group gap="xs" mt="xs" align="center">
                    <Text size="xs" fw={600} c="dimmed">
                      Active Assignees:
                    </Text>
                    <Avatar.Group>
                      {task.assignees.map((assignee: any) => {
                        const name = `${assignee.first_name} ${assignee.last_name || ""}`.trim();
                        const initials = assignee.first_name.substring(0, 2).toUpperCase();
                        return (
                          <Tooltip key={assignee.id} label={`${name} (${assignee.email})`} withArrow>
                            <Avatar
                              radius="xl"
                              size="sm"
                              color="blue"
                              variant="light"
                              styles={{ placeholder: { fontSize: "10px", fontWeight: 700 } }}
                            >
                              {initials}
                            </Avatar>
                          </Tooltip>
                        );
                      })}
                    </Avatar.Group>
                  </Group>
                )}
              </Stack>
            </Paper>

            {/* Workflow Quick Action Buttons */}
            <Box px="md" py="sm" style={{ borderBottom: "1px solid #e9ecef" }}>
              <Card withBorder padding="sm" radius="md" style={{ backgroundColor: "#f8f9fa", borderStyle: "dashed" }}>
                <Stack gap="xs">
                  <Text size="xs" fw={600} c="dimmed">
                    WORKFLOW TRANSITIONS
                  </Text>

                  {isEdm ? (
                    <>
                      {/*
                        Derived from the stage list rather than written out per
                        state: the EDM path is seven states long, and a
                        hand-written chain that long drifts out of step with
                        STAGES_BY_ENTITY the first time a state is inserted.
                      */}
                      {changeRequested ? (
                        <Paper p="xs" radius="xs" style={{ backgroundColor: "#fff5f5", borderLeft: "3px solid #ffc9c9" }}>
                          <Group gap={8} wrap="nowrap" align="flex-start">
                            <IconAlertCircle size={16} color="#c92a2a" style={{ flexShrink: 0, marginTop: 2 }} />
                            <Text size="xs" c="red.8" fw={500}>
                              Changes requested. Resolve the requests below, then
                              send it back for review.
                            </Text>
                          </Group>
                        </Paper>
                      ) : null}

                      <Group gap="xs" grow>
                        {prevStage && (
                          <Button
                            size="sm"
                            variant="default"
                            onClick={() => handleStatusChange(prevStage)}
                            disabled={submitting}
                            leftSection={<IconArrowLeft size={16} />}
                          >
                            Back to {statusMeta(prevStage).label}
                          </Button>
                        )}
                        {nextStage && (
                          <Button
                            size="sm"
                            color={statusMeta(nextStage).color}
                            onClick={() => handleStatusChange(nextStage)}
                            disabled={submitting}
                            leftSection={<IconSend size={16} />}
                          >
                            Move to {statusMeta(nextStage).label}
                          </Button>
                        )}
                      </Group>

                      {!changeRequested && (
                        <Button
                          size="sm"
                          color="red"
                          variant="light"
                          onClick={openCr}
                          disabled={submitting}
                          leftSection={<IconAlertCircle size={16} />}
                        >
                          Request Changes
                        </Button>
                      )}

                      {!nextStage && !changeRequested && (
                        <Group gap={6}>
                          <IconCheck size={16} color="#2b8a3e" />
                          <Text size="xs" fw={600} c="green.8">
                            Cleared to send.
                          </Text>
                        </Group>
                      )}
                    </>
                  ) : (
                    <>
                      {currentStatus === "CONFIGURATION_DRAFT" && (
                        <Button
                          size="sm"
                          color="cyan"
                          onClick={() => handleStatusChange("READY_FOR_CONTENT")}
                          disabled={submitting}
                          leftSection={<IconSend size={16} />}
                          variant="filled"
                        >
                          Mark Ready for Content
                        </Button>
                      )}

                      {currentStatus === "READY_FOR_CONTENT" && (
                        <Group gap="xs" grow>
                          <Button
                            size="sm"
                            variant="default"
                            onClick={() => handleStatusChange("CONFIGURATION_DRAFT")}
                            disabled={submitting}
                            leftSection={<IconFileCode size={16} />}
                          >
                            Back to Draft
                          </Button>
                          <Button
                            size="sm"
                            color="yellow"
                            onClick={() => handleStatusChange("CONTENT_IN_PROGRESS")}
                            disabled={submitting}
                            leftSection={<IconEdit size={16} />}
                          >
                            Start Writing
                          </Button>
                        </Group>
                      )}

                      {currentStatus === "CONTENT_IN_PROGRESS" && (
                        <Button
                          size="sm"
                          color="blue"
                          onClick={() => handleStatusChange("READY_FOR_REVIEW")}
                          disabled={submitting}
                          leftSection={<IconSend size={16} />}
                        >
                          Submit for Review
                        </Button>
                      )}

                      {currentStatus === "READY_FOR_REVIEW" && (
                        <Group gap="xs" grow>
                          <Button
                            size="sm"
                            color="red"
                            variant="light"
                            onClick={openCr}
                            disabled={submitting}
                            leftSection={<IconAlertCircle size={16} />}
                          >
                            Request Changes
                          </Button>
                          <Button
                            size="sm"
                            color="green"
                            onClick={() => handleStatusChange("VERIFIED")}
                            disabled={submitting}
                            leftSection={<IconCheck size={16} />}
                          >
                            Verify & Approve
                          </Button>
                        </Group>
                      )}

                      {currentStatus === "CHANGE_REQUESTED" && (
                        <Paper p="xs" radius="xs" style={{ backgroundColor: "#fff5f5", borderLeft: "3px solid #ffc9c9" }}>
                          <Group gap={8} wrap="nowrap" align="flex-start">
                            <IconAlertCircle size={16} color="#c92a2a" style={{ flexShrink: 0, marginTop: 2 }} />
                            <Text size="xs" c="red.8" fw={500}>
                              Changes requested. Content writers must review and resolve the requests below.
                            </Text>
                          </Group>
                        </Paper>
                      )}

                      {currentStatus === "VERIFIED" && (
                        <Group justify="space-between" align="center">
                          <Group gap={6}>
                            <IconCheck size={16} color="#2b8a3e" />
                            <Text size="xs" fw={600} c="green.8">
                              Approved & Verified
                            </Text>
                          </Group>
                          <Button
                            size="xs"
                            variant="subtle"
                            color="gray"
                            onClick={() => handleStatusChange("READY_FOR_REVIEW")}
                            disabled={submitting}
                          >
                            Re-open Review
                          </Button>
                        </Group>
                      )}
                    </>
                  )}
                </Stack>
              </Card>
            </Box>

            {/* Conversation & Collaboration Section */}
            <Box style={{ flex: 1, minHeight: 0 }} p="md">
              <Stack style={{ height: "100%" }} gap="md">
                <Text size="xs" fw={600} c="dimmed">
                  COLLABORATION TIMELINE
                </Text>

                <ScrollArea style={{ flex: 1 }} scrollbarSize={6}>
                  {historyItems.length === 0 ? (
                    <Text size="sm" c="dimmed" ta="center" py="xl">
                      No comments or actions yet. Start the conversation!
                    </Text>
                  ) : (
                    <Stack gap="sm" style={{ paddingRight: "6px" }}>
                      {historyItems.map((item) => {
                        const isCR = item.type === "change_request";
                        const isPendingCR = isCR && item.raw.status === "PENDING";
                        const initials = item.author.substring(0, 2).toUpperCase();

                        return (
                          <Group key={item.id} align="flex-start" gap="xs" wrap="nowrap">
                            <Avatar
                              radius="xl"
                              size="sm"
                              color={isCR ? "red" : "blue"}
                              variant="light"
                              styles={{ placeholder: { fontSize: "10px", fontWeight: 700 } }}
                            >
                              {initials}
                            </Avatar>
                            <Box style={{ flex: 1 }}>
                              <Paper
                                p="sm"
                                radius="md"
                                style={{
                                  backgroundColor: isCR ? "#fff5f5" : "#f8f9fa",
                                  border: isCR ? "1px solid #ffe3e3" : "1px solid #e9ecef",
                                  position: 'relative',
                                  boxShadow: '0 1px 3px rgba(0,0,0,0.02)',
                                }}
                              >
                                <Group justify="space-between" align="center" mb={4}>
                                  <Group gap={6}>
                                    <Text size="xs" fw={600}>
                                      {item.author}
                                    </Text>
                                    <Badge size="xs" color={isCR ? "red" : "blue"} variant="light" radius="xs">
                                      {isCR ? "Change Request" : "Comment"}
                                    </Badge>
                                    {/* Where it points. Without this a request
                                        on a folder of eight templates is a
                                        guessing game. */}
                                    {isCR && item.raw.target_label && (
                                      <Badge
                                        size="xs"
                                        color="gray"
                                        variant="outline"
                                        radius="xs"
                                        style={{ fontFamily: "monospace", textTransform: "none" }}
                                      >
                                        {item.raw.target_label}
                                        {item.raw.line_number ? `:${item.raw.line_number}` : ""}
                                      </Badge>
                                    )}
                                  </Group>
                                  <Text size="xs" c="dimmed">
                                    {moment(item.date).fromNow()}
                                  </Text>
                                </Group>
                                <Text size="sm" style={{ whiteSpace: "pre-line" }}>
                                  {isCR ? item.content.replace("Requested Changes: ", "") : item.content}
                                </Text>

                                {isCR && (
                                  <Box mt="xs" style={{ borderTop: "1px solid #ffe3e3", paddingTop: "8px", marginTop: "8px" }}>
                                    <Group justify="space-between" align="center">
                                      <Badge
                                        color={isPendingCR ? "red" : "green"}
                                        size="xs"
                                        variant="filled"
                                      >
                                        {item.raw.status}
                                      </Badge>
                                      {isPendingCR && (
                                        <Button
                                          size="compact-xs"
                                          color="green"
                                          leftSection={<IconCheck size={12} />}
                                          onClick={() =>
                                            handleResolveChangeRequest(item.id)
                                          }
                                          disabled={submitting}
                                          variant="light"
                                        >
                                          Resolve Changes
                                        </Button>
                                      )}
                                      {isPendingCR && item.raw.assignee_first_name && (
                                        <Text size="xs" c="dimmed">
                                          for {item.raw.assignee_first_name}{" "}
                                          {item.raw.assignee_last_name || ""}
                                        </Text>
                                      )}
                                      {!isPendingCR && item.raw.resolved_at && (
                                        <Text size="xs" c="dimmed" style={{ fontStyle: 'italic' }}>
                                          Resolved by {item.raw.resolver_first_name || "User"}{" "}
                                          {moment(item.raw.resolved_at).fromNow()}
                                        </Text>
                                      )}
                                    </Group>
                                  </Box>
                                )}
                              </Paper>
                            </Box>
                          </Group>
                        );
                      })}
                    </Stack>
                  )}
                </ScrollArea>

                {/* Comment Form input at the bottom */}
                {task?.id && (
                  <Group align="flex-end" gap="xs" mt="auto">
                    <Textarea
                      placeholder="Write a comment..."
                      value={commentText}
                      onChange={(e) => setCommentText(e.target.value)}
                      disabled={submitting}
                      style={{ flex: 1 }}
                      minRows={1}
                      maxRows={4}
                      autosize
                    />
                    <Button
                      color="dark"
                      onClick={handleAddComment}
                      disabled={!commentText.trim() || submitting}
                    >
                      <IconSend size={16} />
                    </Button>
                  </Group>
                )}
              </Stack>
            </Box>
          </FlexDirectionWrapper>
        )}
      </Box>

      {/* Request Changes Modal */}
      <Modal
        opened={crOpened}
        onClose={closeCr}
        title="Request Content Changes"
        centered
      >
        <Stack>
          <Text size="sm">
            Say what needs to change. Whoever you point it at is notified
            immediately.
          </Text>

          {crTargets.length > 0 && (
            <Group grow align="flex-start">
              <Select
                label="File"
                placeholder="Whole record"
                data={crTargets}
                value={crTarget}
                onChange={setCrTarget}
                searchable
                clearable
              />
              <NumberInput
                label="Line"
                placeholder="optional"
                min={1}
                value={crLine}
                onChange={setCrLine}
                // A line number is meaningless without a file, and the server
                // rejects that combination, so the input follows the file.
                disabled={!crTarget}
              />
            </Group>
          )}

          <Select
            label="Who should fix it"
            placeholder="Everyone assigned to this record"
            data={selectData}
            value={crAssignee}
            onChange={setCrAssignee}
            searchable
            clearable
            leftSection={<IconUser size={16} />}
          />

          <Textarea
            label="Adjustments Requested"
            placeholder="Describe the copy or asset changes required..."
            required
            value={crDescription}
            onChange={(e) => setCrDescription(e.target.value)}
            minRows={3}
          />
          <Group justify="flex-end">
            <Button variant="subtle" onClick={closeCr} disabled={submitting}>
              Cancel
            </Button>
            <Button
              color="red"
              onClick={handleCreateChangeRequest}
              disabled={!crDescription.trim() || submitting}
            >
              Submit Request
            </Button>
          </Group>
        </Stack>
      </Modal>
    </Drawer>
  );
};

// Simple helper styles to simulate a layout flex direction
const FlexDirectionWrapper: React.FC<{ children: React.ReactNode }> = ({
  children,
}) => (
  <div
    style={{
      display: "flex",
      flexDirection: "column",
      height: "100%",
    }}
  >
    {children}
  </div>
);
