"use client";

import Avatar from "@mui/material/Avatar";
import Box from "@mui/material/Box";
import Chip from "@mui/material/Chip";
import CircularProgress from "@mui/material/CircularProgress";
import Dialog from "@mui/material/Dialog";
import Divider from "@mui/material/Divider";
import IconButton from "@mui/material/IconButton";
import Typography from "@mui/material/Typography";
import { alpha, useTheme } from "@mui/material/styles";

import CloseIcon from "@mui/icons-material/Close";
import BusinessIcon from "@mui/icons-material/Business";

import { AppButton } from "@/components/ui/button";
import type {
  Stakeholder,
  StakeholderDetail,
  StakeholderUser,
} from "@/features/stakeholder/stakeholder-data";

type ViewStakeholderDialogProps = {
  stakeholder: Stakeholder;
  stakeholderDetail: StakeholderDetail | null;
  isLoading: boolean;
  onClose: () => void;
};

const API_URL =
  process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001/api/v1";

function resolveImageSrc(value: string | null | undefined) {
  if (!value) {
    return undefined;
  }

  if (value.startsWith("/uploads/")) {
    const backendUrl = API_URL.replace(/\/api(?:\/v\d+)?\/?$/, "");

    return `${backendUrl}${value}`;
  }

  return value;
}

function formatDate(value: string | undefined) {
  if (!value) {
    return "-";
  }

  const date = new Date(value);

  if (Number.isNaN(date.getTime())) {
    return "-";
  }

  return date.toLocaleDateString(undefined, {
    year: "numeric",
    month: "short",
    day: "2-digit",
  });
}

function getUserName(user: StakeholderUser) {
  return user.name?.trim() || user.email || `User #${user.id}`;
}

function getUserInitial(user: StakeholderUser) {
  return getUserName(user).charAt(0).toUpperCase();
}

function InfoItem({ label, value }: { label: string; value: string }) {
  return (
    <Box>
      <Typography
        sx={{ color: "text.secondary", fontSize: 12, fontWeight: 700 }}
      >
        {label}
      </Typography>
      <Typography sx={{ mt: 0.5, fontSize: 14, fontWeight: 600 }}>
        {value}
      </Typography>
    </Box>
  );
}

function UserRow({ user }: { user: StakeholderUser }) {
  return (
    <Box
      sx={{
        display: "flex",
        alignItems: "center",
        gap: 1.25,
        py: 1.25,
      }}
    >
      <Avatar
        src={resolveImageSrc(user.avatar)}
        sx={{ width: 36, height: 36, fontSize: 13, fontWeight: 700 }}
      >
        {getUserInitial(user)}
      </Avatar>

      <Box sx={{ minWidth: 0, flex: 1 }}>
        <Typography noWrap sx={{ fontSize: 14, fontWeight: 700 }}>
          {getUserName(user)}
        </Typography>
        <Typography noWrap sx={{ color: "text.secondary", fontSize: 12 }}>
          {user.email ?? "-"}
        </Typography>
      </Box>

      <Typography
        noWrap
        sx={{ color: "text.secondary", fontSize: 12, fontWeight: 600 }}
      >
        {user.role?.replace(/_/g, " ") ?? "-"}
      </Typography>
    </Box>
  );
}

export function ViewStakeholderDialog({
  stakeholder,
  stakeholderDetail,
  isLoading,
  onClose,
}: ViewStakeholderDialogProps) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";
  const detail = stakeholderDetail ?? {
    ...stakeholder,
    users: [],
  };

  const borderColor = isDark ? alpha("#ffffff", 0.12) : "#e5e7eb";

  return (
    <Dialog
      open
      onClose={onClose}
      maxWidth={false}
      scroll="paper"
      sx={{
        "& .MuiBackdrop-root": {
          backgroundColor: isDark
            ? alpha("#000000", 0.72)
            : "rgba(0, 0, 0, 0.48)",
        },
        "& .MuiDialog-container": {
          justifyContent: "flex-end",
          alignItems: "flex-start",
        },
      }}
      slotProps={{
        paper: {
          sx: {
            mt: 0,
            mr: 0,
            width: { xs: "100vw", md: 680, xl: 760 },
            maxWidth: "calc(100vw - 16px)",
            maxHeight: "calc(100vh - 16px)",
            borderRadius: "10px",
            overflow: "hidden",
            bgcolor: theme.palette.background.paper,
            color: theme.palette.text.primary,
          },
        },
      }}
    >
      <Box
        sx={{
          px: 2.5,
          py: 2,
          borderBottom: `1px solid ${borderColor}`,
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          gap: 2,
        }}
      >
        <Typography sx={{ fontSize: 20, fontWeight: 800 }}>
          View Stakeholder
        </Typography>

        <IconButton onClick={onClose} size="small">
          <CloseIcon sx={{ fontSize: 20 }} />
        </IconButton>
      </Box>

      <Box
        sx={{
          px: 2.5,
          py: 2.5,
          maxHeight: "calc(100vh - 136px)",
          overflowY: "auto",
        }}
      >
        {isLoading && !stakeholderDetail ? (
          <Box
            sx={{
              minHeight: 260,
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
            }}
          >
            <CircularProgress size={28} />
          </Box>
        ) : (
          <Box sx={{ display: "flex", flexDirection: "column", gap: 2.5 }}>
            <Box
              sx={{
                display: "flex",
                alignItems: "center",
                gap: 1.5,
              }}
            >
              <Avatar
                src={resolveImageSrc(detail.logo)}
                sx={{
                  width: 58,
                  height: 58,
                  bgcolor: isDark ? alpha("#ffffff", 0.08) : "#f5f7fa",
                  color: isDark ? alpha("#ffffff", 0.72) : "#1a64a8",
                }}
              >
                {detail.logo ? null : <BusinessIcon sx={{ fontSize: 28 }} />}
              </Avatar>

              <Box sx={{ minWidth: 0, flex: 1 }}>
                <Typography noWrap sx={{ fontSize: 22, fontWeight: 800 }}>
                  {detail.name}
                </Typography>

                <Box sx={{ mt: 1, display: "flex", gap: 1, flexWrap: "wrap" }}>
                  <Chip
                    label={detail.stakeholderType?.name ?? "-"}
                    size="small"
                    sx={{ fontWeight: 700 }}
                  />
                  <Chip
                    label={detail.active ? "Active" : "Inactive"}
                    size="small"
                    color={detail.active ? "success" : "error"}
                    variant="outlined"
                    sx={{ fontWeight: 700 }}
                  />
                </Box>
              </Box>
            </Box>

            <Box
              sx={{
                display: "grid",
                gridTemplateColumns: { xs: "1fr", sm: "1fr 1fr" },
                gap: 2,
              }}
            >
              <InfoItem label="Created" value={formatDate(detail.createdAt)} />
              <InfoItem
                label="Last Update"
                value={formatDate(detail.updatedAt)}
              />
            </Box>

            <Box>
              <Typography sx={{ mb: 0.75, fontSize: 13, fontWeight: 800 }}>
                Description
              </Typography>
              <Box
                sx={{
                  minHeight: 90,
                  p: 1.5,
                  border: `1px solid ${borderColor}`,
                  borderRadius: "8px",
                  bgcolor: isDark ? alpha("#ffffff", 0.04) : "#fafafa",
                }}
              >
                <Typography sx={{ color: "text.secondary", fontSize: 14 }}>
                  {detail.description || "-"}
                </Typography>
              </Box>
            </Box>

            <Box>
              <Box
                sx={{
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "space-between",
                  gap: 2,
                  mb: 0.75,
                }}
              >
                <Typography sx={{ fontSize: 13, fontWeight: 800 }}>
                  Users
                </Typography>

                <Chip
                  label={`${detail.users.length} user${
                    detail.users.length === 1 ? "" : "s"
                  }`}
                  size="small"
                  variant="outlined"
                />
              </Box>

              <Box
                sx={{
                  border: `1px solid ${borderColor}`,
                  borderRadius: "8px",
                  overflow: "hidden",
                }}
              >
                {detail.users.length > 0 ? (
                  detail.users.map((user, index) => (
                    <Box key={user.id}>
                      <UserRow user={user} />
                      {index < detail.users.length - 1 ? <Divider /> : null}
                    </Box>
                  ))
                ) : (
                  <Typography
                    sx={{ p: 1.5, color: "text.secondary", fontSize: 14 }}
                  >
                    No users added to this stakeholder.
                  </Typography>
                )}
              </Box>
            </Box>
          </Box>
        )}
      </Box>

      <Box
        sx={{
          px: 2.5,
          py: 1.7,
          borderTop: `1px solid ${borderColor}`,
          display: "flex",
          justifyContent: "flex-end",
        }}
      >
        <AppButton
          onClick={onClose}
          sx={{
            width: 120,
          }}
        >
          Close
        </AppButton>
      </Box>
    </Dialog>
  );
}
