"use client";

import Autocomplete from "@mui/material/Autocomplete";
import Avatar from "@mui/material/Avatar";
import Box from "@mui/material/Box";
import Checkbox from "@mui/material/Checkbox";
import Grid from "@mui/material/Grid";
import TextField from "@mui/material/TextField";
import Typography from "@mui/material/Typography";
import { alpha, useTheme } from "@mui/material/styles";

import { useAppLanguage } from "@/components/providers/app-language-provider";

import { CefpAddIssueField } from "./cefp-add-issue-field";

import type {
  CefpAddIssueFormValue,
  CefpAddIssueOption,
} from "./cefp-add-issue-types";

type AgencyFieldKey =
  | "secondAgencyId"
  | "thirdAgencyId"
  | "fourthAgencyId"
  | "fifthAgencyId";

type Props = {
  value: CefpAddIssueFormValue;
  governmentAgencies: CefpAddIssueOption[];

  onChange: <K extends keyof CefpAddIssueFormValue>(
    key: K,
    value: CefpAddIssueFormValue[K],
  ) => void;
};

type RelatedAgencyField = {
  key: AgencyFieldKey;
  label: string;
};

function EmptyCheckboxIcon() {
  return (
    <Box
      sx={{
        width: 18,
        height: 18,
        flexShrink: 0,

        border: "1.7px solid",
        borderColor: "primary.main",
        borderRadius: "3px",

        bgcolor: "transparent",
      }}
    />
  );
}

function CheckedCheckboxIcon() {
  return (
    <Box
      component="svg"
      viewBox="0 0 18 18"
      aria-hidden="true"
      sx={{
        width: 18,
        height: 18,
        display: "block",
        flexShrink: 0,
        color: "primary.main",
      }}
    >
      <rect
        x="0.75"
        y="0.75"
        width="16.5"
        height="16.5"
        rx="3"
        fill="currentColor"
      />

      <path
        d="M4.8 9.1 7.6 11.8 13.3 6.2"
        fill="none"
        stroke="#FFFFFF"
        strokeLinecap="round"
        strokeLinejoin="round"
        strokeWidth="1.8"
      />
    </Box>
  );
}

function getInitials(name: string) {
  const parts = name
    .trim()
    .split(/\s+/)
    .filter(Boolean);

  if (parts.length === 0) {
    return "?";
  }

  if (parts.length === 1) {
    return parts[0].slice(0, 2).toUpperCase();
  }

  return `${parts[0][0]}${parts[1][0]}`.toUpperCase();
}

function AgencyLogo({
  agency,
  fontFamily,
  size = 28,
}: {
  agency: CefpAddIssueOption;
  fontFamily: string;
  size?: number;
}) {
  return (
    <Avatar
      src={agency.logo || undefined}
      alt={agency.name}
      slotProps={{
        img: {
          loading: "lazy",
          referrerPolicy: "no-referrer",
        },
      }}
      sx={{
        width: size,
        height: size,
        flexShrink: 0,

        bgcolor: "action.hover",
        color: "primary.main",

        border: "1px solid",
        borderColor: "divider",

        fontFamily,
        fontSize: size <= 24 ? 8 : 9,
        fontWeight: 700,
      }}
    >
      {getInitials(agency.name)}
    </Avatar>
  );
}

function SelectedAgencyContent({
  agency,
  fontFamily,
}: {
  agency: CefpAddIssueOption;
  fontFamily: string;
}) {
  return (
    <Box
      sx={{
        minWidth: 0,
        width: "100%",

        display: "flex",
        alignItems: "center",
        gap: 1.25,
      }}
    >
      <AgencyLogo
        agency={agency}
        fontFamily={fontFamily}
        size={26}
      />

      <Typography
        component="span"
        title={agency.name}
        sx={{
          minWidth: 0,
          flex: 1,

          overflow: "hidden",

          color: "text.primary",
          fontFamily,
          fontSize: 13,
          fontWeight: 400,

          textOverflow: "ellipsis",
          whiteSpace: "nowrap",
        }}
      >
        {agency.name}
      </Typography>
    </Box>
  );
}

export function CefpAddIssueAgenciesSection({
  value,
  governmentAgencies,
  onChange,
}: Props) {
  const theme = useTheme();
  const { language } = useAppLanguage();

  const isKhmer = language === "kh";

  const text = isKhmer
    ? {
        title: "ស្ថាប័នពាក់ព័ន្ធ",
        secondAgency: "ស្ថាប័នទីពីរ",
        thirdAgency: "ស្ថាប័នទីបី",
        fourthAgency: "ស្ថាប័នទីបួន",
        fifthAgency: "ស្ថាប័នទីប្រាំ",
        selectAgency: "ជ្រើសរើសស្ថាប័ន",
        noAgency: "មិនមានស្ថាប័ន",
      }
    : {
        title: "Related Agencies",
        secondAgency: "Second Agency",
        thirdAgency: "Third Agency",
        fourthAgency: "Fourth Agency",
        fifthAgency: "Fifth Agency",
        selectAgency: "Select Agency",
        noAgency: "No agencies available",
      };

  const fontFamily = isKhmer
    ? '"Battambang", "Kantumruy Pro", sans-serif'
    : '"Inter", "Segoe UI", Arial, sans-serif';

  const fields: RelatedAgencyField[] = [
    {
      key: "secondAgencyId",
      label: text.secondAgency,
    },
    {
      key: "thirdAgencyId",
      label: text.thirdAgency,
    },
    {
      key: "fourthAgencyId",
      label: text.fourthAgency,
    },
    {
      key: "fifthAgencyId",
      label: text.fifthAgency,
    },
  ];

  const selectedAgencyIds = [
    value.governmentAgencyId,
    value.secondAgencyId,
    value.thirdAgencyId,
    value.fourthAgencyId,
    value.fifthAgencyId,
  ].filter(Boolean);

  return (
    <Box sx={{ width: "100%" }}>
      <Typography
        component="h3"
        sx={{
          mb: 2,

          color: "text.primary",

          fontFamily,
          fontSize: 14,
          fontWeight: 600,
          lineHeight: 1.5,
        }}
      >
        {text.title}
      </Typography>

      <Grid
        container
        columnSpacing={2.5}
        rowSpacing={3}
      >
        {fields.map((field) => {
          const currentValue = value[field.key];

          const selectedAgency =
            governmentAgencies.find(
              (agency) =>
                String(agency.id) === currentValue,
            ) ?? null;

          const availableAgencies =
            governmentAgencies.filter((agency) => {
              const agencyId = String(agency.id);

              return (
                agencyId === currentValue ||
                !selectedAgencyIds.includes(agencyId)
              );
            });

          const popupPlacement:
            | "bottom-start"
            | "top-start" =
            field.key === "fourthAgencyId" ||
            field.key === "fifthAgencyId"
              ? "top-start"
              : "bottom-start";

          return (
            <Grid
              key={field.key}
              size={{
                xs: 12,
                md: 6,
              }}
            >
              <CefpAddIssueField label={field.label}>
                <Autocomplete<CefpAddIssueOption>
                  options={availableAgencies}
                  value={selectedAgency}
                  openOnFocus
                  autoHighlight
                  clearOnEscape
                  disablePortal={false}
                  getOptionLabel={(option) =>
                    option.name
                  }
                  isOptionEqualToValue={(
                    option,
                    selectedOption,
                  ) =>
                    option.id === selectedOption.id
                  }
                  noOptionsText={text.noAgency}
                  onChange={(_, selectedOption) => {
                    onChange(
                      field.key,
                      selectedOption
                        ? String(selectedOption.id)
                        : "",
                    );
                  }}
                  slotProps={{
                    popper: {
                      placement: popupPlacement,

                      modifiers: [
                        {
                          name: "flip",
                          enabled: false,
                        },
                        {
                          name: "offset",
                          enabled: true,
                          options: {
                            offset: [0, 6],
                          },
                        },
                        {
                          name: "preventOverflow",
                          enabled: true,
                          options: {
                            boundary: "viewport",
                            rootBoundary: "viewport",
                            mainAxis: true,
                            altAxis: true,
                            tether: true,
                            padding: 10,
                          },
                        },
                      ],

                      sx: {
                        zIndex: 1800,

                        "& .MuiAutocomplete-paper": {
                          m: 0,
                          overflow: "hidden",

                          border: "1px solid",
                          borderColor: "divider",
                          borderRadius: 1.5,

                          bgcolor: "background.paper",
                          backgroundImage: "none",

                          boxShadow:
                            theme.palette.mode === "dark"
                              ? "0 12px 32px rgba(0, 0, 0, 0.58)"
                              : "0 12px 32px rgba(16, 24, 40, 0.2)",
                        },
                      },
                    },

                    paper: {
                      elevation: 0,
                    },

                    listbox: {
                      sx: {
                        p: 0,
                        maxHeight: 220,

                        overflowY: "auto",
                        overflowX: "hidden",

                        "&::-webkit-scrollbar": {
                          width: 7,
                        },

                        "&::-webkit-scrollbar-track": {
                          bgcolor: "action.hover",
                        },

                        "&::-webkit-scrollbar-thumb": {
                          bgcolor: alpha(
                            theme.palette.text.secondary,
                            0.38,
                          ),
                          borderRadius: 999,
                        },
                      },
                    },
                  }}
                  renderOption={(
                    optionProps,
                    agency,
                    state,
                  ) => {
                    const {
                      key,
                      ...restOptionProps
                    } = optionProps;

                    return (
                      <Box
                        component="li"
                        key={key}
                        {...restOptionProps}
                        sx={{
                          minHeight: "56px !important",

                          px: "16px !important",
                          py: "8px !important",

                          display: "flex !important",
                          alignItems:
                            "center !important",
                          gap: "10px !important",

                          borderBottom: "1px solid",
                          borderColor: "divider",

                          bgcolor: "background.paper",
                          color: "text.primary",

                          "&:last-of-type": {
                            borderBottom: 0,
                          },

                          "&:hover": {
                            bgcolor: "action.hover",
                          },

                          '&[aria-selected="true"]': {
                            bgcolor: "action.selected",
                          },

                          '&[aria-selected="true"]:hover':
                            {
                              bgcolor:
                                "action.selected",
                            },
                        }}
                      >
                        <Checkbox
                          checked={state.selected}
                          icon={
                            <EmptyCheckboxIcon />
                          }
                          checkedIcon={
                            <CheckedCheckboxIcon />
                          }
                          disableRipple
                          tabIndex={-1}
                          sx={{
                            p: 0,
                            flexShrink: 0,
                            color: "primary.main",
                          }}
                        />

                        <AgencyLogo
                          agency={agency}
                          fontFamily={fontFamily}
                        />

                        <Typography
                          title={agency.name}
                          sx={{
                            minWidth: 0,
                            flex: 1,

                            overflow: "hidden",

                            color: "text.primary",

                            fontFamily,
                            fontSize: 13,
                            fontWeight: 400,
                            lineHeight: 1.4,

                            textOverflow: "ellipsis",
                            whiteSpace: "nowrap",
                          }}
                        >
                          {agency.name}
                        </Typography>
                      </Box>
                    );
                  }}
                  renderInput={(params) => (
                    <Box
                      sx={{
                        position: "relative",
                        width: "100%",
                      }}
                    >
                      <TextField
                        {...params}
                        fullWidth
                        placeholder={
                          selectedAgency
                            ? ""
                            : text.selectAgency
                        }
                        sx={{
                          "& .MuiOutlinedInput-root": {
                            height: 50,
                            minHeight: 50,

                            px: 2,
                            py: 0,

                            borderRadius: 1.5,

                            bgcolor:
                              "background.paper",
                            color: "text.primary",

                            "& fieldset": {
                              borderColor: "divider",
                            },

                            "&:hover fieldset": {
                              borderColor:
                                "text.secondary",
                            },

                            "&.Mui-focused fieldset": {
                              borderColor:
                                "primary.main",
                              borderWidth: 1,
                            },
                          },

                          "& .MuiAutocomplete-inputRoot": {
                            flexWrap: "nowrap",
                            pr: "40px !important",
                          },

                          "& .MuiAutocomplete-input": {
                            minWidth: "0 !important",
                            width: "100% !important",

                            px: "0 !important",
                            py: "0 !important",

                            color: "text.primary",
                            WebkitTextFillColor:
                              "currentColor",

                            fontFamily,
                            fontSize: 13,

                            opacity: selectedAgency
                              ? 0
                              : 1,
                          },

                          "& .MuiAutocomplete-endAdornment":
                            {
                              right: 10,
                            },

                          "& .MuiAutocomplete-clearIndicator":
                            {
                              display: "none",
                            },

                          "& .MuiAutocomplete-popupIndicator":
                            {
                              color: "text.secondary",
                            },

                          "& input::placeholder": {
                            color: alpha(
                              theme.palette.text
                                .secondary,
                              0.72,
                            ),
                            opacity: 1,
                          },
                        }}
                      />

                      {selectedAgency ? (
                        <Box
                          sx={{
                            position: "absolute",

                            left: 16,
                            right: 46,
                            top: "50%",

                            zIndex: 1,

                            transform:
                              "translateY(-50%)",

                            pointerEvents: "none",
                          }}
                        >
                          <SelectedAgencyContent
                            agency={selectedAgency}
                            fontFamily={fontFamily}
                          />
                        </Box>
                      ) : null}
                    </Box>
                  )}
                />
              </CefpAddIssueField>
            </Grid>
          );
        })}
      </Grid>
    </Box>
  );
}