"use client";

import {
  type FormEvent,
  useState,
} from "react";

import ArrowBackOutlinedIcon from "@mui/icons-material/ArrowBackOutlined";
import BusinessOutlinedIcon from "@mui/icons-material/BusinessOutlined";
import SaveOutlinedIcon from "@mui/icons-material/SaveOutlined";

import Alert from "@mui/material/Alert";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import CircularProgress from "@mui/material/CircularProgress";
import Paper from "@mui/material/Paper";
import Snackbar from "@mui/material/Snackbar";
import TextField from "@mui/material/TextField";
import Typography from "@mui/material/Typography";

import { useRouter } from "next/navigation";

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

import { useMyOrganization } from "../hook/use-my-organization";

import {
  resolveMyOrganizationAssetUrl,
} from "../service/my-organization-service";

import type {
  MyOrganizationProfile,
  UpdateMyOrganizationPayload,
} from "../types/my-organization-types";

import {
  OrganizationLogoUploader,
} from "./organization-logo-uploader";

// ============================================================
// TYPES
// ============================================================

type EditOrganizationContentProps = {
  profile: MyOrganizationProfile;

  isSaving: boolean;

  isUploadingLogo: boolean;

  isUploadingSystemLogo: boolean;

  error: string | null;

  updateOrganization: (
    payload: UpdateMyOrganizationPayload,
  ) => Promise<MyOrganizationProfile | null>;

  uploadOrganizationLogo: (
    file: File,
  ) => Promise<MyOrganizationProfile | null>;

  uploadSystemLogo: (
    file: File,
  ) => Promise<MyOrganizationProfile | null>;
};

// ============================================================
// EDIT ORGANIZATION CONTENT
// ============================================================

function EditOrganizationContent({
  profile,
  isSaving,
  isUploadingLogo,
  isUploadingSystemLogo,
  error,
  updateOrganization,
  uploadOrganizationLogo,
  uploadSystemLogo,
}: EditOrganizationContentProps) {
  const router = useRouter();

  const { language } =
    useAppLanguage();

  const isKhmer =
    language === "kh";

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

  // ==========================================================
  // FORM STATE
  //
  // Initialize directly from API profile.
  // No useEffect + setState.
  // ==========================================================

  const [
    name,
    setName,
  ] = useState(
    () =>
      profile.organization.name ??
      "",
  );

  const [
    description,
    setDescription,
  ] = useState(
    () =>
      profile.organization.description ??
      "",
  );

  const [
    coChair,
    setCoChair,
  ] = useState(
    () =>
      profile.organization.coChair ??
      "",
  );

  const [
    fieldError,
    setFieldError,
  ] =
    useState<string | null>(
      null,
    );

  const [
    successMessage,
    setSuccessMessage,
  ] =
    useState<string | null>(
      null,
    );

  // ==========================================================
  // LOGO URLS
  // ==========================================================

  const organizationLogoUrl =
    resolveMyOrganizationAssetUrl(
      profile.organization.logo,
    );

  const systemLogoUrl =
    resolveMyOrganizationAssetUrl(
      profile.systemLogo,
    );

  // ==========================================================
  // LABELS
  // ==========================================================

  const labels =
    isKhmer
      ? {
          title:
            "កែប្រែព័ត៌មានស្ថាប័ន",

          organizationInformation:
            "ព័ត៌មានស្ថាប័ន",

          organizationName:
            "ឈ្មោះស្ថាប័ន",

          organizationType:
            "ប្រភេទស្ថាប័ន",

          coChair:
            "សហប្រធាន",

          description:
            "ការពិពណ៌នា",

          logoBranding:
            "រូបសញ្ញា និងអត្តសញ្ញាណ",

          organizationLogo:
            "រូបសញ្ញាស្ថាប័ន",

          organizationLogoDescription:
            "រូបសញ្ញានេះតំណាងឱ្យស្ថាប័នរបស់អ្នក។",

          systemLogo:
            "រូបសញ្ញាប្រព័ន្ធ G-PSF",

          systemLogoDescription:
            "រូបសញ្ញានេះបង្ហាញនៅផ្នែកខាងឆ្វេងលើរបស់ប្រព័ន្ធ។",

          save:
            "រក្សាទុកការកែប្រែ",

          saving:
            "កំពុងរក្សាទុក...",

          cancel:
            "បោះបង់",

          nameRequired:
            "សូមបញ្ចូលឈ្មោះស្ថាប័ន។",

          updateSuccess:
            "ព័ត៌មានស្ថាប័នត្រូវបានកែប្រែដោយជោគជ័យ។",

          organizationLogoSuccess:
            "រូបសញ្ញាស្ថាប័នត្រូវបានកែប្រែដោយជោគជ័យ។",

          systemLogoSuccess:
            "រូបសញ្ញាប្រព័ន្ធត្រូវបានកែប្រែដោយជោគជ័យ។",

          organizationLogoError:
            "មិនអាចកែប្រែរូបសញ្ញាស្ថាប័នបានទេ។",

          systemLogoError:
            "មិនអាចកែប្រែរូបសញ្ញាប្រព័ន្ធបានទេ។",
        }
      : {
          title:
            "Edit Organization",

          organizationInformation:
            "Organization Information",

          organizationName:
            "Organization Name",

          organizationType:
            "Organization Type",

          coChair:
            "Co-Chair",

          description:
            "Description",

          logoBranding:
            "Logo & Branding",

          organizationLogo:
            "Organization Logo",

          organizationLogoDescription:
            "This logo represents your organization.",

          systemLogo:
            "System Logo (G-PSF)",

          systemLogoDescription:
            "This logo appears in the system sidebar/header.",

          save:
            "Save Changes",

          saving:
            "Saving...",

          cancel:
            "Cancel",

          nameRequired:
            "Organization name is required.",

          updateSuccess:
            "Organization updated successfully.",

          organizationLogoSuccess:
            "Organization logo updated successfully.",

          systemLogoSuccess:
            "System logo updated successfully.",

          organizationLogoError:
            "Unable to upload organization logo.",

          systemLogoError:
            "Unable to upload system logo.",
        };

  // ==========================================================
  // ORGANIZATION TYPE
  // ==========================================================

  const organizationType =
    profile.organization
      .stakeholderType
      ?.name
      ?.trim() ||
    "—";

  // ==========================================================
  // SUBMIT
  // ==========================================================

  async function handleSubmit(
    event: FormEvent<HTMLFormElement>,
  ) {
    event.preventDefault();

    setFieldError(
      null,
    );

    const normalizedName =
      name.trim();

    if (!normalizedName) {
      setFieldError(
        labels.nameRequired,
      );

      return;
    }

    const result =
      await updateOrganization({
        name:
          normalizedName,

        description:
          description.trim(),

        coChair:
          coChair.trim(),
      });

    if (!result) {
      return;
    }

    setSuccessMessage(
      labels.updateSuccess,
    );
  }

  // ==========================================================
  // CANCEL
  // ==========================================================

  function handleCancel() {
    router.push(
      "/my-organization",
    );
  }

  // ==========================================================
  // CLOSE SUCCESS ALERT
  // ==========================================================

  function closeSuccessMessage() {
    setSuccessMessage(
      null,
    );
  }

  return (
    <>
      <Box
        component="form"
        onSubmit={(event) => {
          void handleSubmit(
            event,
          );
        }}
        sx={{
          width:
            "100%",

          px: {
            xs: 2,
            sm: 3,
            lg: 3.5,
          },

          py: {
            xs: 2.5,
            sm: 3,
          },

          fontFamily,

          "& .MuiTypography-root": {
            fontFamily,
          },

          "& .MuiInputBase-root": {
            fontFamily,
          },

          "& .MuiInputLabel-root": {
            fontFamily,
          },

          "& .MuiButton-root": {
            fontFamily,
            textTransform:
              "none",
          },
        }}
      >
        {/* ====================================================
            PAGE TITLE
        ==================================================== */}

        <Typography
          component="h1"
          sx={{
            mb:
              2,

            color:
              "text.primary",

            fontSize:
              isKhmer
                ? {
                    xs: 25,
                    sm: 29,
                  }
                : {
                    xs: 28,
                    sm: 31,
                  },

            fontWeight:
              isKhmer
                ? 600
                : 700,

            lineHeight:
              isKhmer
                ? 1.6
                : 1.2,

            letterSpacing:
              isKhmer
                ? 0
                : "-0.02em",
          }}
        >
          {labels.title}
        </Typography>

        {/* ====================================================
            API ERROR
        ==================================================== */}

        {error && (
          <Alert
            severity="error"
            sx={{
              mb:
                2,

              fontFamily,
            }}
          >
            {error}
          </Alert>
        )}

        {/* ====================================================
            FIELD ERROR
        ==================================================== */}

        {fieldError && (
          <Alert
            severity="warning"
            sx={{
              mb:
                2,

              fontFamily,
            }}
          >
            {fieldError}
          </Alert>
        )}

        {/* ====================================================
            ORGANIZATION INFORMATION
        ==================================================== */}

        <Paper
          elevation={0}
          sx={{
            overflow:
              "hidden",

            bgcolor:
              "background.paper",

            backgroundImage:
              "none",

            border:
              "1px solid",

            borderColor:
              "divider",

            borderRadius:
              2,
          }}
        >
          {/* Header */}

          <Box
            sx={{
              minHeight:
                isKhmer
                  ? 68
                  : 62,

              px: {
                xs: 2,
                sm: 2.5,
              },

              display:
                "flex",

              alignItems:
                "center",

              gap:
                1.1,

              borderBottom:
                "1px solid",

              borderColor:
                "divider",
            }}
          >
            <BusinessOutlinedIcon
              sx={{
                fontSize:
                  22,

                color:
                  "primary.main",
              }}
            />

            <Typography
              component="h2"
              sx={{
                color:
                  "text.primary",

                fontSize:
                  isKhmer
                    ? 16
                    : 15,

                fontWeight:
                  700,

                lineHeight:
                  isKhmer
                    ? 1.7
                    : 1.4,
              }}
            >
              {
                labels.organizationInformation
              }
            </Typography>
          </Box>

          {/* Fields */}

          <Box
            sx={{
              p: {
                xs: 2,
                sm: 2.5,
              },

              display:
                "grid",

              gridTemplateColumns: {
                xs:
                  "1fr",

                md:
                  "repeat(2, minmax(0, 1fr))",
              },

              gap:
                2,
            }}
          >
            {/* Organization Name */}

            <TextField
              fullWidth
              required
              size="small"
              label={
                labels.organizationName
              }
              value={
                name
              }
              onChange={(event) => {
                setName(
                  event.target.value,
                );

                if (fieldError) {
                  setFieldError(
                    null,
                  );
                }
              }}
              sx={{
                "& .MuiOutlinedInput-root":
                  {
                    minHeight:
                      52,

                    borderRadius:
                      1.25,
                  },
              }}
            />

            {/* Organization Type */}

            <TextField
              fullWidth
              disabled
              size="small"
              label={
                labels.organizationType
              }
              value={
                organizationType
              }
              sx={{
                "& .MuiOutlinedInput-root":
                  {
                    minHeight:
                      52,

                    borderRadius:
                      1.25,
                  },
              }}
            />

            {/* Co-Chair */}

            <TextField
              fullWidth
              size="small"
              label={
                labels.coChair
              }
              value={
                coChair
              }
              onChange={(event) => {
                setCoChair(
                  event.target.value,
                );
              }}
              sx={{
                gridColumn: {
                  xs:
                    "auto",

                  md:
                    "1 / -1",
                },

                "& .MuiOutlinedInput-root":
                  {
                    minHeight:
                      52,

                    borderRadius:
                      1.25,
                  },
              }}
            />

            {/* Description */}

            <TextField
              fullWidth
              multiline
              minRows={
                4
              }
              label={
                labels.description
              }
              value={
                description
              }
              onChange={(event) => {
                setDescription(
                  event.target.value,
                );
              }}
              sx={{
                gridColumn: {
                  xs:
                    "auto",

                  md:
                    "1 / -1",
                },

                "& .MuiOutlinedInput-root":
                  {
                    borderRadius:
                      1.25,
                  },
              }}
            />
          </Box>
        </Paper>

        {/* ====================================================
            LOGO & BRANDING
        ==================================================== */}

        <Paper
          elevation={0}
          sx={{
            mt:
              2,

            overflow:
              "hidden",

            bgcolor:
              "background.paper",

            backgroundImage:
              "none",

            border:
              "1px solid",

            borderColor:
              "divider",

            borderRadius:
              2,
          }}
        >
          {/* Header */}

          <Box
            sx={{
              minHeight:
                isKhmer
                  ? 68
                  : 62,

              px: {
                xs: 2,
                sm: 2.5,
              },

              display:
                "flex",

              alignItems:
                "center",

              gap:
                1.1,

              borderBottom:
                "1px solid",

              borderColor:
                "divider",
            }}
          >
            <Typography
              component="h2"
              sx={{
                color:
                  "text.primary",

                fontSize:
                  isKhmer
                    ? 16
                    : 15,

                fontWeight:
                  700,

                lineHeight:
                  isKhmer
                    ? 1.7
                    : 1.4,
              }}
            >
              {
                labels.logoBranding
              }
            </Typography>
          </Box>

          {/* Logo Content */}

          <Box
            sx={{
              p: {
                xs: 2,
                sm: 2.5,
              },

              display:
                "grid",

              gap:
                2,
            }}
          >
            {/* ================================================
                ORGANIZATION LOGO
            ================================================ */}

            <OrganizationLogoUploader
              title={
                labels.organizationLogo
              }
              description={
                labels.organizationLogoDescription
              }
              logoUrl={
                organizationLogoUrl
              }
              imageAlt="Organization logo"
              isUploading={
                isUploadingLogo
              }
              onUpload={async (file) => {
                const result =
                  await uploadOrganizationLogo(
                    file,
                  );

                if (!result) {
                  throw new Error(
                    labels.organizationLogoError,
                  );
                }

                setSuccessMessage(
                  labels.organizationLogoSuccess,
                );
              }}
            />

            {/* ================================================
                SYSTEM LOGO
            ================================================ */}

            <OrganizationLogoUploader
              title={
                labels.systemLogo
              }
              description={
                labels.systemLogoDescription
              }
              logoUrl={
                systemLogoUrl
              }
              imageAlt="G-PSF system logo"
              isUploading={
                isUploadingSystemLogo
              }
              onUpload={async (file) => {
                const result =
                  await uploadSystemLogo(
                    file,
                  );

                if (!result) {
                  throw new Error(
                    labels.systemLogoError,
                  );
                }

                setSuccessMessage(
                  labels.systemLogoSuccess,
                );
              }}
            />
          </Box>
        </Paper>

        {/* ====================================================
            ACTION BUTTONS
        ==================================================== */}

        <Box
          sx={{
            mt:
              2,

            display:
              "flex",

            flexDirection: {
              xs:
                "column-reverse",

              sm:
                "row",
            },

            justifyContent:
              "flex-end",

            gap:
              1.25,
          }}
        >
          {/* Cancel */}

          <Button
            type="button"
            variant="outlined"
            startIcon={
              <ArrowBackOutlinedIcon />
            }
            disabled={
              isSaving
            }
            onClick={
              handleCancel
            }
            sx={{
              width: {
                xs:
                  "100%",

                sm:
                  "auto",
              },

              minWidth:
                140,

              height:
                isKhmer
                  ? 48
                  : 44,

              borderRadius:
                1.25,

              fontWeight:
                600,
            }}
          >
            {labels.cancel}
          </Button>

          {/* Save */}

          <Button
            type="submit"
            variant="contained"
            disabled={
              isSaving
            }
            startIcon={
              isSaving ? (
                <CircularProgress
                  size={18}
                  color="inherit"
                />
              ) : (
                <SaveOutlinedIcon />
              )
            }
            sx={{
              width: {
                xs:
                  "100%",

                sm:
                  "auto",
              },

              minWidth:
                170,

              height:
                isKhmer
                  ? 48
                  : 44,

              borderRadius:
                1.25,

              fontWeight:
                600,

              color:
                "common.white",

              boxShadow:
                "none",

              "&:hover": {
                boxShadow:
                  "none",
              },
            }}
          >
            {isSaving
              ? labels.saving
              : labels.save}
          </Button>
        </Box>
      </Box>

      {/* ======================================================
          SUCCESS ALERT
      ====================================================== */}

      <Snackbar
        open={
          Boolean(
            successMessage,
          )
        }
        autoHideDuration={
          3000
        }
        anchorOrigin={{
          vertical:
            "bottom",

          horizontal:
            "right",
        }}
        onClose={
          closeSuccessMessage
        }
        sx={{
          mb: {
            xs: 1,
            sm: 2,
          },

          mr: {
            xs: 1,
            sm: 2,
          },
        }}
      >
        <Alert
          severity="success"
          variant="filled"
          onClose={
            closeSuccessMessage
          }
          sx={{
            width:
              "100%",

            minWidth: {
              xs: 280,
              sm: 340,
            },

            maxWidth:
              430,

            borderRadius:
              1.5,

            boxShadow:
              6,

            fontFamily,
          }}
        >
          {successMessage}
        </Alert>
      </Snackbar>
    </>
  );
}

// ============================================================
// MAIN COMPONENT
// ============================================================

export function EditOrganizationForm() {
  const {
    profile,

    isLoading,
    isSaving,

    isUploadingLogo,
    isUploadingSystemLogo,

    error,

    updateOrganization,

    uploadOrganizationLogo,
    uploadSystemLogo,
  } =
    useMyOrganization();

  // ==========================================================
  // LOADING
  // ==========================================================

  if (isLoading) {
    return (
      <Box
        sx={{
          minHeight:
            500,

          display:
            "grid",

          placeItems:
            "center",
        }}
      >
        <CircularProgress />
      </Box>
    );
  }

  // ==========================================================
  // ERROR / NO PROFILE
  // ==========================================================

  if (!profile) {
    return (
      <Box
        sx={{
          p: {
            xs: 2,
            md: 3,
          },
        }}
      >
        <Alert
          severity="error"
        >
          {error ??
            "Unable to load organization."}
        </Alert>
      </Box>
    );
  }

  // ==========================================================
  // FORM
  //
  // key forces the form content to remount when updatedAt changes.
  // Therefore no useEffect is needed for form synchronization.
  // ==========================================================

  return (
    <EditOrganizationContent
      key={`${profile.id}-${profile.organization.updatedAt ?? ""}`}
      profile={
        profile
      }
      isSaving={
        isSaving
      }
      isUploadingLogo={
        isUploadingLogo
      }
      isUploadingSystemLogo={
        isUploadingSystemLogo
      }
      error={
        error
      }
      updateOrganization={
        updateOrganization
      }
      uploadOrganizationLogo={
        uploadOrganizationLogo
      }
      uploadSystemLogo={
        uploadSystemLogo
      }
    />
  );
}