import { Alert, Box, Button, Container, Divider, Grid, Paper, Typography } from '@mui/material';
import ChangePasswordCard from './ChangePasswordCard';

import { ReactElement, useContext, useEffect, useState } from 'react';
import { PropertiesAPI, PropertyOwnerAPI, PropertyRequestAPI, UserAPI, OpenHouseAPI } from 'types';
import ProfileCard from './ProfileCard';
import { AxiosResponse } from 'axios';
import PropertyCard from './PropertyCard.';
import AddPropertyDialog from './AddPropertyDialog';
import { axiosInstance } from '../../../../../axiosApi';
import PropertyDetailCard from '../Property/PropertyDetailCard';
import { AccountContext } from 'contexts/AccountContext';
import DashboardErrorPage from '../Dashboard/DashboardErrorPage';
import DashboardLoading from '../Dashboard/DashboardLoading';
import { ProfileProps } from 'pages/Profile/Profile';
import { useNavigate } from 'react-router-dom';
import AddOpenHouseDialog from './AddOpenHouseDialog';
import OpenHouseDialogContent from './OpenHouseDialogContext';

const PropertyOwnerProfile = ({ account }: ProfileProps): ReactElement => {
  const [loadingData, setLoadingData] = useState<boolean>(true);
  const navigate = useNavigate();
  const [user, setUser] = useState<PropertyOwnerAPI | null>(null);

  const [openHouses, setOpenHouses] = useState<OpenHouseAPI[]>([]);
  const [openAddOpenHouseDialog, setOpenAddOpenHouseDialog] = useState(false);
  const [openHouseErrors, setOpenHouseErrors] = useState<{ [key: string]: string }>({});

  useEffect(() => {
    const fetchPropertyOwner = async () => {
      try {
        setLoadingData(true);
        const { data }: AxiosResponse<PropertyOwnerAPI[]> =
          await axiosInstance.get(`/property-owners/`);
        if (data.length > 0) {
          setUser(data[0]);
        }
      } catch (error) {
        console.log(error);
      } finally {
        setLoadingData(false);
      }
    };
    fetchPropertyOwner();
  }, []);

  const [properties, setProperties] = useState<PropertiesAPI[]>([]); //initialPropertiesData);

  const [openAddPropertyDialog, setOpenAddPropertyDialog] = useState(false);
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  useEffect(() => {
    const fetchProperties = async () => {
      try {
        setLoadingData(true);
        const { data }: AxiosResponse<PropertiesAPI[]> = await axiosInstance.get('/properties/');
        if (data.length > 0) {
          setProperties(data);
          console.log('setting the user to: ', data[0].owner);
          setUser(data[0].owner);
        }

        const { data: openHousesData }: AxiosResponse<OpenHouseAPI[]> = await axiosInstance.get(
          '/properties/open-houses/',
        );
        setOpenHouses(openHousesData);
      } catch (error) {
        console.log(error);
      } finally {
        setLoadingData(false);
      }
    };
    fetchProperties();
  }, []);

  const handleUpgradeSubscription = async () => {
    navigate('/upgrade/');
    // const { data }: AxiosResponse<UserAPI> = await axiosInstance.post(`/user/`, {
    //   ...user.user,
    //   tier: 'premium',
    // });
    // if (data !== null && user) {
    //   const updateUser: PropertyOwnerAPI = {
    //     ...user,
    //     user: data,
    //   };
    //   setUser(updateUser);
    // }

    // setMessage({ type: 'success', text: 'Subscription upgraded to Premium!' });
    // setTimeout(() => setMessage(null), 3000);
  };

  const handleSaveProfile = async (editedUser: UserAPI) => {
    editedUser.profile_created = true;
    const { data }: AxiosResponse<UserAPI> = await axiosInstance.post(`/user/`, {
      ...editedUser,
    });
    if (data !== null && user) {
      const updateUser: PropertyOwnerAPI = {
        ...user,
        user: data,
      };
      setUser(updateUser);
    }

    setMessage({ type: 'success', text: 'Profile updated successfully!' });
    setTimeout(() => setMessage(null), 3000);
  };

  const handleOpenAddPropertyDialog = () => {
    setOpenAddPropertyDialog(true);
  };

  const handleCloseAddPropertyDialog = () => {
    setOpenAddPropertyDialog(false);
  };

  const handleOpenAddOpenHouseDialog = () => {
    setOpenAddOpenHouseDialog(true);
  };

  const handleCloseAddOpenHouseDialog = () => {
    setOpenAddOpenHouseDialog(false);
    setOpenHouseErrors({});
  };

  const handleAddOpenHouse = async (
    newOpenHouseData: Omit<OpenHouseAPI, 'id'> & { listed_date: string },
  ) => {
    try {
      const { data }: AxiosResponse<OpenHouseAPI> = await axiosInstance.post(
        '/properties/open-houses/',
        newOpenHouseData,
      );
      setOpenHouses((prev) => [...prev, data]);
      setMessage({ type: 'success', text: 'Open house added successfully!' });
      setTimeout(() => setMessage(null), 3000);
      setOpenAddOpenHouseDialog(false);
    } catch (error) {
      console.log(error);
      setOpenHouseErrors(error.response.data);
      setMessage({ type: 'error', text: 'Error adding open house.' });
      setTimeout(() => setMessage(null), 3000);
    }
  };

  const handleAddProperty = (
    newPropertyData: Omit<PropertiesAPI, 'id' | 'owner' | 'created_at' | 'last_updated'>,
  ) => {
    if (user) {
      const newProperty: PropertyRequestAPI = {
        ...newPropertyData,
        owner: user.user.id,
        // created_at: new Date().toISOString().split('T')[0],
        // last_updated: new Date().toISOString().split('T')[0],
      };

      newProperty.created_at = new Date().toISOString().split('T')[0];
      newProperty.last_updated = new Date().toISOString().split('T')[0];

      newProperty.open_houses = [];

      console.log(newProperty);
      const { data, error } = axiosInstance.post('/properties/', {
        ...newProperty,
      });
      const updateNewProperty: PropertiesAPI = {
        ...newProperty,
        owner: user,
      };
      setProperties((prev) => [...prev, updateNewProperty]);
      setMessage({ type: 'success', text: 'Property added successfully!' });
      setTimeout(() => setMessage(null), 3000);
    }
  };

  const handleSaveProperty = async (updatedProperty: PropertiesAPI) => {
    try {
      const { data } = await axiosInstance.patch<PropertiesAPI>(
        `/properties/${updatedProperty.id}/`,
        {
          ...updatedProperty,
          owner: account.id,
        },
      );
      const updatedProperties = properties.map((item) => {
        if (item.id === data.id) {
          return { ...item, ...data };
        }
        return item;
      });
      setProperties(updatedProperties);
      setMessage({ type: 'success', text: 'Property has been updated' });
      setTimeout(() => setMessage(null), 3000);
    } catch (error) {
      setMessage({ type: 'error', text: 'Error while saving the property. Please try again' });
      setTimeout(() => setMessage(null), 3000);
    }
  };

  const handleDeleteProperty = async (propertyId: number) => {
    try {
      await axiosInstance.delete(`/properties/${propertyId}/`);
      setProperties((prev) => prev.filter((item) => item.id !== propertyId));
      setMessage({ type: 'success', text: 'Property has been removed' });
      setTimeout(() => setMessage(null), 3000);
    } catch (error) {
      setMessage({ type: 'error', text: 'Error while removing the property. Please try again' });
      setTimeout(() => setMessage(null), 3000);
    }
  };

  console.log(user);
  if (loadingData) {
    return <DashboardLoading />;
  }

  if (user === null) {
    return <DashboardErrorPage />;
  } else {
    return (
      <Container maxWidth="lg" sx={{ mt: 4, mb: 4 }}>
        <Typography variant="h4" component="h1" gutterBottom sx={{ color: 'background.paper' }}>
          User Profile Dashboard
        </Typography>
        {message && (
          <Alert severity={message.type} sx={{ mb: 2 }}>
            {message.text}
          </Alert>
        )}
        <ProfileCard
          user={user.user}
          onUpgrade={handleUpgradeSubscription}
          onSave={handleSaveProfile}
          setMessage={setMessage}
        />

        {/*<Box sx={{ mt: 4 }}>
          <ChangePasswordCard />
        </Box>*/}

        <Divider sx={{ my: 4 }} />

        <Box display="flex" justifyContent="space-between" alignItems="center" sx={{ mb: 2 }}>
          <Typography variant="h5" component="h2" sx={{ color: 'background.paper' }}>
            My Properties
          </Typography>
          <Button variant="contained" color="primary" onClick={handleOpenAddPropertyDialog}>
            Add Property
          </Button>
        </Box>
        {message && (
          <Alert severity={message.type} sx={{ mb: 2 }}>
            {message.text}
          </Alert>
        )}
        {properties.length === 0 ? (
          <Paper sx={{ p: 3, textAlign: 'center' }}>
            <Typography variant="body1" color="textSecondary">
              You currently have no properties listed.
            </Typography>
          </Paper>
        ) : (
          <Grid container spacing={3}>
            {properties.map((property) => (
              <Grid size={{ xs: 12 }} key={property.id}>
                {/* <PropertyCard property={property} /> */}
                <PropertyDetailCard
                  property={property}
                  isPublicPage={false}
                  onSave={handleSaveProperty}
                  isOwnerView={true}
                  onDelete={handleDeleteProperty}
                />
              </Grid>
            ))}
          </Grid>
        )}

        <AddPropertyDialog
          open={openAddPropertyDialog}
          onClose={handleCloseAddPropertyDialog}
          onAddProperty={handleAddProperty}
        />

        <Divider sx={{ my: 4 }} />

        {properties.length > 0 ? (
          <>
            <Box display="flex" justifyContent="space-between" alignItems="center" sx={{ mb: 2 }}>
              <Typography variant="h5" component="h2" sx={{ color: 'background.paper' }}>
                My Open Houses
              </Typography>
              <Button variant="contained" color="primary" onClick={handleOpenAddOpenHouseDialog}>
                Add Open House
              </Button>
            </Box>
            {openHouses.length === 0 ? (
              <Paper sx={{ p: 3, textAlign: 'center' }}>
                <Typography variant="body1" color="textSecondary">
                  You have no open houses scheduled.
                </Typography>
              </Paper>
            ) : (
              <Grid container spacing={3}>
                {openHouses.map((openHouse) => (
                  <Grid size={{ xs: 12, sm: 6, md: 4, lg: 3, xl: 2 }} key={openHouse.id}>
                    {/* You will create a component to display the open house details */}
                    <OpenHouseDialogContent openHouse={openHouse} />
                  </Grid>
                ))}
              </Grid>
            )}
          </>
        ) : (
          <Alert severity="info" sx={{ mb: 2 }}>
            Please add a property before you can schedule an open house.
          </Alert>
        )}

        <AddOpenHouseDialog
          open={openAddOpenHouseDialog}
          onClose={handleCloseAddOpenHouseDialog}
          onAddOpenHouse={handleAddOpenHouse}
          properties={properties} // Pass the properties to the dialog
          errors={openHouseErrors}
        />
      </Container>
    );
  }
};

export default PropertyOwnerProfile;
