import React from "react";
import {
  Box,
  Typography,
  Modal,
  Button,
  Stack,
  TextField,
  IconButton,
  useMediaQuery,
} from "@mui/material";
import { Close as CloseIcon } from "@mui/icons-material";
import IntelliwealthTextField from "./intelliwealthTextField";
import themestyle from "../theme";
import { EDIT_PROFILE_TEXT, TYPOGRAPHY_TEXT } from "../const";
import { CountrySelect } from "react-country-state-city";
import { ICountry } from "country-state-city";
import "react-country-state-city/dist/react-country-state-city.css";

interface EditProfileModalProps {
  open: boolean;
  onClose: () => void;
  onSave: () => void;
  formData: {
    id: string;
    email: string;
    firstName: string;
    lastName: string;
    phone: string;
    country: string;
    address: string;
    postcode: string;
    companyName: string;
  };
  setFormData: React.Dispatch<
    React.SetStateAction<{
      id: string;
      email: string;
      firstName: string;
      lastName: string;
      phone: string;
      country: string;
      address: string;
      postcode: string;
      companyName: string;
    }>
  >;
  country: ICountry | null;
  setCountry: React.Dispatch<React.SetStateAction<ICountry | null>>;
  emailErrorMessage: string;
  setEmailErrorMessage: React.Dispatch<React.SetStateAction<string>>;
  firstNameErrorMessage: string;
  setFirstNameErrorMessage: React.Dispatch<React.SetStateAction<string>>;
  lastNameErrorMessage: string;
  setLastNameErrorMessage: React.Dispatch<React.SetStateAction<string>>;
  phoneErrorMessage: string;
  setPhoneErrorMessage: React.Dispatch<React.SetStateAction<string>>;
  companyNameErrorMessage: string;
  setCompanyNameErrorMessage: React.Dispatch<React.SetStateAction<string>>;
  addressErrorMessage: string;
  setAddressErrorMessage: React.Dispatch<React.SetStateAction<string>>;
  postcodeErrorMessage: string;
  setPostcodeErrorMessage: React.Dispatch<React.SetStateAction<string>>;
  countryErrorMessage: string;
  setCountryErrorMessage: React.Dispatch<React.SetStateAction<string>>;
  handleChange: (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => void;
  handleCountryChange: (selectedCountry: ICountry | null) => void;
  handleBlur: (
    field: string,
    value: string | ICountry | null,
    validator: (val: any) => boolean,
    errorSetter: (msg: string) => void
  ) => void;
  isValidEmail: (email: string) => boolean;
  isValidName: (name: string) => boolean;
  isValidPhone: (phone: string) => boolean;
  isValidCompany: (company: string) => boolean;
  isValidAddress: (address: string) => boolean;
  isValidPostcode: (postcode: string) => boolean;
  isValidCountry: (country: ICountry | null) => boolean;
  hasErrors: () => boolean;
}

const EditProfileModal: React.FC<EditProfileModalProps> = ({
  open,
  onClose,
  onSave,
  formData,
  setFormData,
  country,
  setCountry,
  emailErrorMessage,
  setEmailErrorMessage,
  firstNameErrorMessage,
  setFirstNameErrorMessage,
  lastNameErrorMessage,
  setLastNameErrorMessage,
  phoneErrorMessage,
  setPhoneErrorMessage,
  companyNameErrorMessage,
  setCompanyNameErrorMessage,
  addressErrorMessage,
  setAddressErrorMessage,
  postcodeErrorMessage,
  setPostcodeErrorMessage,
  countryErrorMessage,
  setCountryErrorMessage,
  handleChange,
  handleCountryChange,
  handleBlur,
  isValidEmail,
  isValidName,
  isValidPhone,
  isValidCompany,
  isValidAddress,
  isValidPostcode,
  isValidCountry,
  hasErrors,
}) => {
  const isMobile = useMediaQuery("(max-width:600px)");

  const handleCountrySelectChange = (selectedCountry: any) => {
    const countryObj: ICountry | null = selectedCountry
      ? {
          name: selectedCountry.name,
          phonecode: selectedCountry.phonecode,
          isoCode: selectedCountry.isoCode,
          flag: selectedCountry.flag,
          currency: selectedCountry.currency,
          latitude: selectedCountry.latitude,
          longitude: selectedCountry.longitude,
        }
      : null;
    handleCountryChange(countryObj);
  };

  return (
    <Modal
      open={open}
      onClose={onClose}
      aria-labelledby="edit-profile-modal"
      aria-describedby="edit-profile-form"
      sx={{
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        zIndex: 1500,
      }}
    >
      <Box
        sx={{
          width: { xs: "80%", sm: "80%", md: "500px" },
          maxHeight: "80vh", 
          bgcolor: "background.paper",
          borderRadius: "8px",
          boxShadow: 24,
          p: isMobile ? 3 : 4, 
          position: "relative",
          overflowY: "auto",
        }}
      >
        <IconButton
          aria-label="close"
          onClick={onClose}
          sx={{ position: "absolute", top: 8, right: 8, color: "#757575" }}
        >
          <CloseIcon />
        </IconButton>
        <Typography
          id="edit-profile-modal"
          variant={isMobile ? "h6" : "h5"}
          sx={{ mb: 3, color: "#1A202C", fontWeight: 500 }}
        >
          {EDIT_PROFILE_TEXT.MODAL_TITLE}
        </Typography>
        <Stack direction="column" spacing={2} sx={{ width: "100%" }}>
          <Stack direction="column" spacing={1}>
            <Typography
              variant="body2"
              sx={{
                color: "#222222",
                fontFamily: themestyle.fontFamily.lato,
                fontWeight: 500,
                textAlign: "left",
              }}
            >
              {TYPOGRAPHY_TEXT.EMAIL}
            </Typography>
            <IntelliwealthTextField
              fullWidth
              margin="normal"
              name="email"
              value={formData.email}
              InputProps={{ readOnly: true }}
              sx={{
                "& .MuiOutlinedInput-root": { borderRadius: "8px", height: "45px" },
                "& .MuiInputLabel-root": { fontSize: "14px" },
                "& .MuiInputBase-input": { fontSize: "14px" },
              }}
            />
          </Stack>
          <Stack
            direction={isMobile ? "column" : "row"}
            spacing={isMobile ? 2 : 2}
            sx={{ mb: isMobile ? 2 : 0 }}
          >
            <Stack direction="column" spacing={1} sx={{ flex: 1 }}>
              <Typography
                variant="body2"
                sx={{
                  color: "#222222",
                  fontFamily: themestyle.fontFamily.lato,
                  fontWeight: 500,
                  textAlign: "left",
                }}
              >
                {TYPOGRAPHY_TEXT.FIRST_NAME}
              </Typography>
              <IntelliwealthTextField
                fullWidth
                name="firstName"
                placeholder="Enter your first name"
                value={formData.firstName}
                onChange={handleChange}
                onBlur={() =>
                  handleBlur(
                    "firstName",
                    formData.firstName,
                    isValidName,
                    setFirstNameErrorMessage
                  )
                }
                error={Boolean(firstNameErrorMessage)}
                helperText={firstNameErrorMessage}
                sx={{
                  "& .MuiOutlinedInput-root": {
                    borderRadius: "8px",
                    height: "45px",
                  },
                  "& .MuiInputLabel-root": { fontSize: "14px" },
                  "& .MuiInputBase-input": { fontSize: "14px" },
                }}
              />
            </Stack>
            <Stack direction="column" spacing={1} sx={{ flex: 1 }}>
              <Typography
                variant="body2"
                sx={{
                  color: "#222222",
                  fontFamily: themestyle.fontFamily.lato,
                  fontWeight: 500,
                  textAlign: "left",
                }}
              >
                {TYPOGRAPHY_TEXT.LAST_NAME}
              </Typography>
              <IntelliwealthTextField
                fullWidth
                name="lastName"
                placeholder="Enter your last name"
                value={formData.lastName}
                onChange={handleChange}
                onBlur={() =>
                  handleBlur(
                    "lastName",
                    formData.lastName,
                    isValidName,
                    setLastNameErrorMessage
                  )
                }
                error={Boolean(lastNameErrorMessage)}
                helperText={lastNameErrorMessage}
                sx={{
                  "& .MuiOutlinedInput-root": {
                    borderRadius: "8px",
                    height: "45px",
                  },
                  "& .MuiInputLabel-root": { fontSize: "14px" },
                  "& .MuiInputBase-input": { fontSize: "14px" },
                }}
              />
            </Stack>
          </Stack>
          <Stack
            direction={isMobile ? "column" : "row"}
            spacing={isMobile ? 2 : 2}
            sx={{ mb: isMobile ? 2 : 0 }}
          >
            <Stack direction="column" spacing={1} sx={{ flex: 1 }}>
              <Typography
                variant="body2"
                sx={{
                  color: "#222222",
                  fontFamily: themestyle.fontFamily.lato,
                  fontWeight: 500,
                  textAlign: "left",
                }}
              >
                {TYPOGRAPHY_TEXT.COMPANY_NAME}
              </Typography>
              <IntelliwealthTextField
                fullWidth
                name="companyName"
                placeholder="Enter your company name"
                value={formData.companyName}
                onChange={handleChange}
                onBlur={() =>
                  handleBlur(
                    "companyName",
                    formData.companyName,
                    isValidCompany,
                    setCompanyNameErrorMessage
                  )
                }
                error={Boolean(companyNameErrorMessage)}
                helperText={companyNameErrorMessage}
                sx={{
                  "& .MuiOutlinedInput-root": {
                    borderRadius: "8px",
                    height: "45px",
                  },
                  "& .MuiInputLabel-root": { fontSize: "14px" },
                  "& .MuiInputBase-input": { fontSize: "14px" },
                }}
              />
            </Stack>
            <Stack direction="column" spacing={1} sx={{ flex: 1 }}>
              <Typography
                variant="body2"
                sx={{
                  color: "#222222",
                  fontFamily: themestyle.fontFamily.lato,
                  fontWeight: 500,
                  textAlign: "left",
                }}
              >
                {TYPOGRAPHY_TEXT.PHONE}
              </Typography>
              <IntelliwealthTextField
                fullWidth
                name="phone"
                value={formData.phone}
                placeholder="Enter your phone number"
                onChange={handleChange}
                onBlur={() =>
                  handleBlur(
                    "phone",
                    formData.phone,
                    isValidPhone,
                    setPhoneErrorMessage
                  )
                }
                error={Boolean(phoneErrorMessage)}
                helperText={phoneErrorMessage}
                sx={{
                  "& .MuiOutlinedInput-root": {
                    borderRadius: "8px",
                    height: "45px",
                  },
                  "& .MuiInputLabel-root": { fontSize: "14px" },
                  "& .MuiInputBase-input": { fontSize: "14px" },
                }}
              />
            </Stack>
          </Stack>
          <Stack direction="column" spacing={1} sx={{ mb: 2 }}>
            <Typography
              variant="body2"
              sx={{
                color: "#222222",
                fontFamily: themestyle.fontFamily.lato,
                fontWeight: 500,
                textAlign: "left",
              }}
            >
              {TYPOGRAPHY_TEXT.ADDRESS}
            </Typography>
            <TextField
              fullWidth
              name="address"
              placeholder="Enter your address"
              value={formData.address}
              onChange={handleChange}
              onBlur={() =>
                handleBlur(
                  "address",
                  formData.address,
                  isValidAddress,
                  setAddressErrorMessage
                )
              }
              error={Boolean(addressErrorMessage)}
              helperText={addressErrorMessage}
              variant="outlined"
              multiline
              rows={3}
              sx={{
                "& .MuiOutlinedInput-root": { borderRadius: "8px" },
                "& .MuiInputLabel-root": { fontSize: "14px" },
                "& .MuiInputBase-input": { fontSize: "14px" },
              }}
            />
          </Stack>
          <Stack
            direction={isMobile ? "column" : "row"}
            spacing={isMobile ? 2 : 2}
            sx={{ mb: isMobile ? 2 : 0 }}
          >
            <Stack direction="column" spacing={1} sx={{ flex: 1 }}>
              <Typography
                variant="body2"
                sx={{
                  color: "#222222",
                  fontFamily: themestyle.fontFamily.lato,
                  fontWeight: 500,
                  textAlign: "left",
                }}
              >
                {TYPOGRAPHY_TEXT.COUNTRY}
              </Typography>
              <CountrySelect
                value={country?.name || ""}
                onChange={handleCountrySelectChange}
                placeHolder="Select Country"
                showFlag={true}
                inputClassName={
                  countryErrorMessage ? "rsc-input-error" : "rsc-input"
                }
                style={{
                  borderRadius: "8px",
                  height: "45px",
                  fontSize: "14px",
                  width: "100%",
                  padding: "8px",
                }}
              />
              {countryErrorMessage && (
                <Typography
                  variant="caption"
                  color="error"
                  sx={{ display: "block", mt: 0.5, ml: 1.5 }}
                >
                  {countryErrorMessage}
                </Typography>
              )}
            </Stack>
            <Stack direction="column" spacing={1} sx={{ flex: 1 }}>
              <Typography
                variant="body2"
                sx={{
                  color: "#222222",
                  fontFamily: themestyle.fontFamily.lato,
                  fontWeight: 500,
                  textAlign: "left",
                }}
              >
                {TYPOGRAPHY_TEXT.POSTCODE}
              </Typography>
              <IntelliwealthTextField
                fullWidth
                name="postcode"
                value={formData.postcode}
                onChange={handleChange}
                onBlur={() =>
                  handleBlur(
                    "postcode",
                    formData.postcode,
                    isValidPostcode,
                    setPostcodeErrorMessage
                  )
                }
                error={Boolean(postcodeErrorMessage)}
                helperText={postcodeErrorMessage}
                sx={{
                  "& .MuiOutlinedInput-root": {
                    borderRadius: "8px",
                    height: "45px",
                  },
                  "& .MuiInputLabel-root": { fontSize: "14px" },
                  "& .MuiInputBase-input": { fontSize: "14px" },
                }}
              />
            </Stack>
          </Stack>
          <Box
            sx={{
              mt: 3,
              display: "flex",
              justifyContent: isMobile ? "center" : "flex-end",
              gap: 2,
              width: "100%",
              flexWrap: "wrap",  
            }}
          >
            <Button
              onClick={onClose}
              variant="contained"
              color="secondary"
              sx={{
                fontSize: isMobile ? "12px" : "14px",
                textTransform: "none",
                bgcolor: "#E0E0E0",
                color: "#000000",
                borderRadius: "8px",
                "&:hover": { bgcolor: "#BDBDBD" },
                minWidth: "100px",
                padding: isMobile ? "8px 16px" : "10px 20px",
              }}
            >
              {EDIT_PROFILE_TEXT.CANCEL}
            </Button>
            <Button
              onClick={onSave}
              variant="contained"
              color="primary"
              disabled={hasErrors()}
              sx={{
                fontSize: isMobile ? "12px" : "14px",
                textTransform: "none",
                bgcolor: themestyle.colors.primary,
                borderRadius: "8px",
                minWidth: "100px",
                padding: isMobile ? "8px 16px" : "10px 20px",
              }}
            >
              {EDIT_PROFILE_TEXT.SAVE}
            </Button>
          </Box>
        </Stack>
      </Box>
    </Modal>
  );
};

export default EditProfileModal;