import React, { useState } from "react";
import {
  Box,
  Typography,
  useMediaQuery,
  useTheme,
  Avatar,
  IconButton,
  Link,
  Snackbar,
  Alert,
} from "@mui/material";
import { Close as CloseIcon } from "@mui/icons-material";
import {
  deepOrange,
  deepPurple,
  teal,
  indigo,
  pink,
  blue,
  green,
} from "@mui/material/colors";
import EditProfileModal from "../../components/EditProfileModel";
import { ERROR_MESSAGES, PROFILE_TEXT, TYPOGRAPHY_TEXT } from "../../const";
import { GET_CUSTOMER_ID } from "../../graphql/query";
import { UPDATE_PROFILE_USER } from "../../graphql/mutation";
import { useQuery, useMutation } from "@apollo/client";
import { ICountry, Country } from "country-state-city";

const themestyle = { colors: { primary: "#007BFF" } };

const Profile: React.FC = () => {
  const theme = useTheme();
  const isSmallScreen = useMediaQuery(theme.breakpoints.down("md"));
  const isMobile = useMediaQuery("(max-width:600px)");
  const storedUser = JSON.parse(localStorage.getItem("user") || "{}");
  const id = storedUser?.id || "";

  const { loading, error, data, refetch } = useQuery(GET_CUSTOMER_ID, {
    variables: { id },
  });

  const [updateProfile] = useMutation(UPDATE_PROFILE_USER);

  const customerData = data?.getCustomer || {};

  const displayName =
    customerData.username && customerData.username.toLowerCase() !== "unknown"
      ? customerData.username
      : PROFILE_TEXT.DEFAULT_NAME;
  const email = customerData.email || "";
  const phone = customerData.phoneNumber || "";
  const address = customerData.address || "";
  const postcode = customerData.pincode || "";
  const customerCountry = customerData.country || "";

  const getInitials = (name: string): string => {
    if (!name || name.toLowerCase() === PROFILE_TEXT.DEFAULT_NAME.toLowerCase())
      return "C";
    const words = name.trim().split(/\s+/);
    if (words.length === 1) return words[0][0]?.toUpperCase() || "U";
    return (words[0][0] + (words[1]?.[0] || "")).toUpperCase();
  };

  const getAvatarColor = (name: string): string => {
    const colors = [
      deepOrange[500],
      deepPurple[500],
      teal[500],
      indigo[500],
      pink[500],
      blue[500],
      green[500],
    ];
    const hash = name
      .split("")
      .reduce((acc, char) => acc + char.charCodeAt(0), 0);
    return colors[hash % colors.length];
  };

  const initials = getInitials(displayName);
  const avatarColor = getAvatarColor(displayName);

  const [open, setOpen] = useState(false);
  const [formData, setFormData] = useState({
    id: customerData.id || "",
    email: customerData.email || "",
    firstName: customerData.firstName || "",
    lastName: customerData.lastName || "",
    phone: customerData.phoneNumber || "",
    country: customerData.country || "",
    address: customerData.address || "",
    postcode: customerData.pincode || "",
    companyName: customerData.companyName || "",
  });
  const [country, setCountry] = useState<ICountry | null>(null);
  const [emailErrorMessage, setEmailErrorMessage] = useState("");
  const [firstNameErrorMessage, setFirstNameErrorMessage] = useState("");
  const [lastNameErrorMessage, setLastNameErrorMessage] = useState("");
  const [phoneErrorMessage, setPhoneErrorMessage] = useState("");
  const [companyNameErrorMessage, setCompanyNameErrorMessage] = useState("");
  const [addressErrorMessage, setAddressErrorMessage] = useState("");
  const [postcodeErrorMessage, setPostcodeErrorMessage] = useState("");
  const [countryErrorMessage, setCountryErrorMessage] = useState("");
  const [snackbarOpen, setSnackbarOpen] = useState(false);
  const [snackbarMessage, setSnackbarMessage] = useState("");
  const [snackbarSeverity, setSnackbarSeverity] = useState<"success" | "error">(
    "success"
  );

  const handleOpen = () => {
    setFormData({
      id: customerData.id || "",
      email: customerData.email || "",
      firstName: customerData.firstName || "",
      lastName: customerData.lastName || "",
      phone: customerData.phoneNumber || "",
      country: customerData.country || "",
      address: customerData.address || "",
      postcode: customerData.pincode || "",
      companyName: customerData.companyName || "",
    });
    const countryData = customerData.country
      ? Country.getAllCountries().find(
          (c: ICountry) => c.name === customerData.country
        ) || null
      : null;
    setCountry(countryData);
    setEmailErrorMessage("");
    setFirstNameErrorMessage("");
    setLastNameErrorMessage("");
    setPhoneErrorMessage("");
    setCompanyNameErrorMessage("");
    setAddressErrorMessage("");
    setPostcodeErrorMessage("");
    setCountryErrorMessage("");
    setOpen(true);
  };

  const handleClose = () => {
    setOpen(false);
  };

  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
  };

  const handleCountryChange = (selectedCountry: ICountry | null) => {
    setCountry(selectedCountry);
    setFormData((prev) => ({
      ...prev,
      country: selectedCountry ? selectedCountry.name : "",
    }));
    handleBlur(
      "country",
      selectedCountry,
      isValidCountry,
      setCountryErrorMessage
    );
  };

  const isValidEmail = (email: string) =>
    ERROR_MESSAGES.EMAILREG.test(email);
  const isValidName = (name: string) =>
   ERROR_MESSAGES.NAMEREG.test(name)
  const isValidPhone = (phone: string) =>
    ERROR_MESSAGES.PHONEREG.test(phone);
  const isValidCompany = (company: string) => company.trim().length >= 3;
  const isValidAddress = (address: string) => address.trim().length >= 5;
  const isValidPostcode = (postcode: string) =>
    ERROR_MESSAGES.POSTCODEREG.test(postcode);
  const isValidCountry = (country: ICountry | null) =>
    !!country && !!country.name;

  const handleBlur = (
    field: string,
    value: string | ICountry | null,
    validator: (val: any) => boolean,
    errorSetter: (msg: string) => void
  ) => {
    if (field === "country") {
      if (!isValidCountry(value as ICountry | null)) {
        errorSetter(ERROR_MESSAGES.COUNTRY);
      } else {
        errorSetter("");
      }
    } else if (!validator(value as string) && (value as string).length > 0) {
      const errorMap = {
        email: ERROR_MESSAGES.EMAIL_VAILD,
        firstName: ERROR_MESSAGES.FIRST_NAME,
        lastName: ERROR_MESSAGES.LAST_NAME,
        phone: ERROR_MESSAGES.VALID_PHONE_NUMBER,
        companyName: ERROR_MESSAGES.COMPANY_NAME,
        address: ERROR_MESSAGES.ADDRESS_MUST_BE,
        postcode: ERROR_MESSAGES.PINCODE,
      };
      errorSetter(errorMap[field as keyof typeof errorMap]);
    } else {
      errorSetter("");
    }
  };

  const hasErrors = () => {
    return (
      Boolean(emailErrorMessage) ||
      Boolean(firstNameErrorMessage) ||
      Boolean(lastNameErrorMessage) ||
      Boolean(phoneErrorMessage) ||
      Boolean(companyNameErrorMessage) ||
      Boolean(addressErrorMessage) ||
      Boolean(postcodeErrorMessage) ||
      Boolean(countryErrorMessage)
    );
  };

  const handleSave = async () => {
    const isFirstNameValid = isValidName(formData.firstName);
    const isLastNameValid = isValidName(formData.lastName);
    const isPhoneValid = isValidPhone(formData.phone);
    const isCompanyValid = isValidCompany(formData.companyName);
    const isAddressValid = isValidAddress(formData.address);
    const isPostcodeValid = isValidPostcode(formData.postcode);
    const isCountryValid = isValidCountry(country);

    setFirstNameErrorMessage(
      isFirstNameValid ? "" : ERROR_MESSAGES.FIRST_NAME
    );
    setLastNameErrorMessage(
      isLastNameValid ? "" : ERROR_MESSAGES.LAST_NAME
    );
    setPhoneErrorMessage(isPhoneValid ? "" : ERROR_MESSAGES.VALID_PHONE_NUMBER);
    setCompanyNameErrorMessage(
      isCompanyValid ? "" : ERROR_MESSAGES.COMPANY_NAME
    );
    setAddressErrorMessage(
      isAddressValid ? "" : ERROR_MESSAGES.ADDRESS_MUST_BE
    );
    setPostcodeErrorMessage(isPostcodeValid ? "" : ERROR_MESSAGES.PINCODE);
    setCountryErrorMessage(isCountryValid ? "" : ERROR_MESSAGES.COUNTRY);

    if (
      !isFirstNameValid ||
      !isLastNameValid ||
      !isPhoneValid ||
      !isCompanyValid ||
      !isAddressValid ||
      !isPostcodeValid ||
      !isCountryValid
    ) {
      setSnackbarSeverity("error");
      setSnackbarMessage(ERROR_MESSAGES.PLEASE_CORRECT);
      setSnackbarOpen(true);
      return;
    }

    try {
      const input = {
        id: formData.id,
        email: formData.email,
        firstName: formData.firstName,
        lastName: formData.lastName,
        phoneNumber: formData.phone,
        country: formData.country,
        address: formData.address,
        pincode: formData.postcode,
        companyName: formData.companyName || null,
      };

      if (!input.id) {
        setSnackbarMessage(ERROR_MESSAGES.ID_REQ);
        setSnackbarSeverity("error");
        setSnackbarOpen(true);
        return;
      }

      const { data, errors } = await updateProfile({ variables: { input } });

      if (errors) {
        throw new Error(errors[0].message);
      }

      if (data.updateProfile) {
        setSnackbarMessage(ERROR_MESSAGES.PROFILE);
        setSnackbarSeverity("success");
        setSnackbarOpen(true);
        refetch();
        setOpen(false);
      }
    } catch (error) {
      const errorMessage =
        error instanceof Error ? error.message : ERROR_MESSAGES.ERROR_OCCURED;
      setSnackbarMessage(`${ERROR_MESSAGES.ERROR_OCCURED} : ${errorMessage}`);
      setSnackbarSeverity("error");
      setSnackbarOpen(true);
    }
  };

  const handleSnackbarClose = () => {
    setSnackbarOpen(false);
  };

  if (loading) return <Typography>Loading...</Typography>;
  if (error) return <Typography>Error: {error.message}</Typography>;

  return (
    <Box sx={{ padding: 2, bgcolor: "#F9FAFC", minHeight: "85vh" }}>
      <Typography
        variant="h5"
        gutterBottom
        sx={{
          color: "#1A202C",
          fontWeight: 600,
          letterSpacing: "-0.3px",
          padding: "5px",
        }}
      >
        {PROFILE_TEXT.PAGE_TITLE}
      </Typography>
      <div
        style={{
          padding: "15px",
          width: "auto",
          maxWidth: "1200px",
          margin: "0 auto",
        }}
      >
        <div
          style={{
            display: "flex",
            flexDirection: isSmallScreen ? "column" : "row",
            alignItems: isSmallScreen ? "center" : "stretch",
            gap: "30px",
            marginBottom: "30px",
          }}
        >
          <div
            style={{
              border: "1px solid #E0E0E0",
              borderRadius: "10px",
              padding: "25px",
              width: isSmallScreen ? "95%" : "45%",
              backgroundColor: "#FFFFFF",
              boxShadow: "0 4px 6px rgba(0, 0, 0, 0.05)",
            }}
          >
            <Typography
              variant="h5"
              gutterBottom
              sx={{
                color: "#1A202C",
                fontWeight: 500,
                letterSpacing: "-0.3px",
                padding: "5px",
              }}
            >
              {PROFILE_TEXT.PROFILE_TITLE}
            </Typography>
            <div
              style={{
                display: "flex",
                flexDirection: isSmallScreen ? "column" : "row",
                gap: "25px",
                alignItems: isSmallScreen ? "center" : "flex-start",
              }}
            >
              <div>
                <IconButton
                  color="inherit"
                  aria-label={`User profile for ${displayName}`}
                >
                  <Avatar
                    sx={{
                      bgcolor: avatarColor,
                      color: "#fff",
                      width: 150,
                      height: 150,
                    }}
                  >
                    {initials}
                  </Avatar>
                </IconButton>
                <Typography
                  style={{
                    fontWeight: 500,
                    fontFamily: "Roboto, sans-serif",
                    fontSize: "18px",
                    color: "#2D3748",
                    marginTop: "15px",
                    textAlign: "center",
                    width: "100%",
                    display: "block",
                  }}
                >
                  {displayName}
                </Typography>
              </div>
              <div style={{ flex: "1", textAlign: isSmallScreen ? "center" : "left" }}>
                <Typography
                  style={{
                    fontWeight: 400,
                    fontFamily: "Roboto, sans-serif",
                    fontSize: "14px",
                    color: "#4A5568",
                    lineHeight: "1.6",
                  }}
                >
                  <strong>{TYPOGRAPHY_TEXT.ABOUT}</strong>
                  <br />
                  {TYPOGRAPHY_TEXT.PHONE}: {phone}
                  <br />
                  {TYPOGRAPHY_TEXT.EMAIL}: {email}
                  <br />
                  {TYPOGRAPHY_TEXT.ADDRESS}: {address}
                  <br />
                  {TYPOGRAPHY_TEXT.COUNTRY}: {customerCountry}
                  <br />
                  {TYPOGRAPHY_TEXT.POSTCODE}: {postcode}
                </Typography>
                <div style={{ marginTop: "15px" }}>
                  <Link
                    href="#"
                    onClick={handleOpen}
                    sx={{
                      color: themestyle.colors.primary,
                      textDecoration: "none",
                      fontSize: isSmallScreen ? "12px" : "14px",
                      "&:hover": { textDecoration: "underline" },
                    }}
                  >
                    {PROFILE_TEXT.EDIT_PROFILE}
                  </Link>
                  <br />
                  <Box
                    sx={{
                      display: "flex",
                      alignItems: "center",
                      marginTop: "10px",
                      justifyContent: isSmallScreen ? "center" : "flex-start",
                    }}
                  >
                    <Link
                      href="/profile/change-password"
                      sx={{
                        color: themestyle.colors.primary,
                        textDecoration: "none",
                        fontSize: isSmallScreen ? "12px" : "14px",
                        "&:hover": { textDecoration: "underline" },
                      }}
                    >
                      {PROFILE_TEXT.CHANGE_PASSWORD}
                    </Link>
                  </Box>
                </div>
              </div>
            </div>
          </div>

          {/* <div
            style={{
              border: "1px solid #E0E0E0",
              borderRadius: "10px",
              padding: "25px",
              width: isSmallScreen ? "95%" : "45%",
              backgroundColor: "#FFFFFF",
              boxShadow: "0 4px 6px rgba(0, 0, 0, 0.05)",
            }}
          >
            <Typography
              variant="h5"
              gutterBottom
              sx={{
                color: "#1A202C",
                fontWeight: 500,
                letterSpacing: "-0.3px",
                padding: "5px",
              }}
            >
              {PROFILE_TEXT.MEMBERSHIP_TITLE}
            </Typography>
            <div
              style={{
                border: "1px solid #E0E0E0",
                borderRadius: "8px",
                padding: "20px",
                backgroundColor: "#F7FAFC",
                color: "#718096",
                textAlign: "center",
                fontSize: "14px",
              }}
            >
              {PROFILE_TEXT.MEMBERSHIP_EMPTY}
            </div>
          </div> */}
        </div>
      </div>

      <EditProfileModal
        open={open}
        onClose={handleClose}
        onSave={handleSave}
        formData={formData}
        setFormData={setFormData}
        country={country}
        setCountry={setCountry}
        emailErrorMessage={emailErrorMessage}
        setEmailErrorMessage={setEmailErrorMessage}
        firstNameErrorMessage={firstNameErrorMessage}
        setFirstNameErrorMessage={setFirstNameErrorMessage}
        lastNameErrorMessage={lastNameErrorMessage}
        setLastNameErrorMessage={setLastNameErrorMessage}
        phoneErrorMessage={phoneErrorMessage}
        setPhoneErrorMessage={setPhoneErrorMessage}
        companyNameErrorMessage={companyNameErrorMessage}
        setCompanyNameErrorMessage={setCompanyNameErrorMessage}
        addressErrorMessage={addressErrorMessage}
        setAddressErrorMessage={setAddressErrorMessage}
        postcodeErrorMessage={postcodeErrorMessage}
        setPostcodeErrorMessage={setPostcodeErrorMessage}
        countryErrorMessage={countryErrorMessage}
        setCountryErrorMessage={setCountryErrorMessage}
        handleChange={handleChange}
        handleCountryChange={handleCountryChange}
        handleBlur={handleBlur}
        isValidEmail={isValidEmail}
        isValidName={isValidName}
        isValidPhone={isValidPhone}
        isValidCompany={isValidCompany}
        isValidAddress={isValidAddress}
        isValidPostcode={isValidPostcode}
        isValidCountry={isValidCountry}
        hasErrors={hasErrors}
      />

      <Snackbar
        open={snackbarOpen}
        autoHideDuration={2000}
        onClose={handleSnackbarClose}
        anchorOrigin={{ vertical: "top", horizontal: "center" }}
        sx={{
          "& .MuiSnackbarContent-root": {
            borderRadius: "8px",
            backgroundColor: "#f5f5f5",
          },
        }}
      >
        <Alert
          onClose={handleSnackbarClose}
          severity={snackbarSeverity}
          sx={{
            width: isSmallScreen ? "90%" : "100%",
            fontSize: isSmallScreen ? "14px" : "16px",
          }}
          action={
            <IconButton
              size="small"
              aria-label="close"
              color="inherit"
              onClick={handleSnackbarClose}
            >
              <CloseIcon fontSize="small" />
            </IconButton>
          }
        >
          {snackbarMessage}
        </Alert>
      </Snackbar>
    </Box>
  );
};

export default Profile;