import { AxiosResponse } from 'axios';
import { ReactElement, useContext, useEffect, useState } from 'react';
import { DocumentAPI, PropertiesAPI, SavedPropertiesAPI, UserAPI } from 'types';
import { axiosInstance } from '../../../../../axiosApi';
//==import Grid from '@mui/material/Unstable_Grid2';
import {
  Alert,
  Button,
  Grid,
  Card,
  CardActionArea,
  CardContent,
  Divider,
  Stack,
  Typography,
} from '@mui/material';
import { drawerWidth } from 'layouts/main-layout';
import { ProperyInfoCards } from '../Property/PropertyInfo';
import { useNavigate } from 'react-router-dom';

import HouseIcon from '@mui/icons-material/House';
import VisibilityIcon from '@mui/icons-material/Visibility';
import FavoriteIcon from '@mui/icons-material/Favorite';
import RequestQuoteIcon from '@mui/icons-material/RequestQuote';
import { EducationInfoCards } from '../Education/EducationInfo';
import { DataGrid, GridRenderCellParams } from '@mui/x-data-grid';
import { GridColDef } from '@mui/x-data-grid';
import PropertyDetailCard from '../Property/PropertyDetailCard';
import { DashboardProps } from 'pages/home/Dashboard';
import SavedPropertiesTable from './SavedPropertiesTable';

interface Row {
  id: number;
}

const PropertyOwnerDashboard = ({ account }: DashboardProps): ReactElement => {
  const [properties, setProperties] = useState<PropertiesAPI[]>([]);
  const [numBids, setNumBids] = useState<Number>(0);
  const [numOffers, setNumOffers] = useState<Number>(0);
  const [savedProperties, setSavedProperties] = useState<PropertiesAPI[]>([]);
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
  const [documents, setDocuments] = useState<DocumentAPI[]>([]);

  const navigate = useNavigate();
  useEffect(() => {
    const fetchProperties = async () => {
      try {
        const { data }: AxiosResponse<PropertiesAPI[]> = await axiosInstance.get('/properties/');
        if (data.length > 0) {
          setProperties(data);
        }
      } catch (error) {
        console.log(error);
      }
    };
    const fetchOffers = async () => {
      try {
        const { data }: AxiosResponse<PropertiesAPI[]> = await axiosInstance.get('/offers/');
        if (data.length > 0) {
          setNumOffers(data.length);
        }
      } catch (error) {
        console.log(error);
      }
    };

    const fetchBids = async () => {
      try {
        const { data }: AxiosResponse<PropertiesAPI[]> = await axiosInstance.get('/bids/');
        if (data.length > 0) {
          setNumBids(data.length);
        }
      } catch (error) {
        console.log(error);
      }
    };
    const fetchSavedProperties = async () => {
      try {
        let expandedSavedProperties: PropertiesAPI[] = [];
        const { data }: AxiosResponse<SavedPropertiesAPI[]> =
          await axiosInstance.get('/saved-properties/');
        const requests = data.map((item) =>
          axiosInstance.get(`/properties/${item.property}/?search=1`),
        );
        const responses = await Promise.all(requests);

        expandedSavedProperties = responses.map((response) => response.data);
        console.log(expandedSavedProperties);
        setSavedProperties(expandedSavedProperties);
      } catch (error) {
        console.log(error);
      }
    };
    const fetchDocuments = async () => {
      try {
        const { data }: AxiosResponse<DocumentAPI[]> = await axiosInstance.get('/document/');
        console.log('documents', data);
        setDocuments(data);
      } catch (error) {
        console.log(error);
      }
    };
    fetchProperties();
    fetchOffers();
    fetchBids();
    fetchSavedProperties();
    fetchDocuments();
  }, []);
  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);
    }
  };

  const documentColumns: GridColDef[] = [
    {
      field: 'id',
      headerName: 'ID',
    },
    {
      field: 'title',
      headerName: 'Title',
      flex: 1,
    },
    {
      field: 'action',
      headerName: 'Action',
      flex: 0,
      renderCell: (params: GridRenderCellParams<Row, number>) => {
        return (
          <Button variant="contained" component="label">
            View
          </Button>
        );
      },
    },
  ];

  const DocumentRows = [
    {
      id: 1,
      title: 'Offer',
    },
    {
      id: 2,
      title: 'Disclousre Form',
    },
  ];

  const numViews = properties.reduce((accum, currProperty) => {
    return accum + currProperty.views;
  }, 0);
  const numSaves = properties.reduce((accum, currProperty) => {
    return accum + currProperty.saves;
  }, 0);
  const savedPropertiesCardLength: number = savedProperties.length === 0 ? 6 : 12;
  const documentsCardLength: number = documents.length === 0 ? 6 : 12;

  return (
    <Grid
      container
      component="main"
      columns={12}
      spacing={3.75}
      flexGrow={1}
      pt={4.375}
      pr={1.875}
      pb={0}
      sx={{
        width: { md: `calc(100% - ${drawerWidth}px)` },
        pl: { xs: 3.75, lg: 0 },
      }}
    >
      {/* quick states */}
      {!account.profile_created && (
        <Grid xs={12} key="profile-setup">
          <Alert severity="warning" sx={{ mb: 2 }}>
            Please set up your <a href="/profile">profile</a>
          </Alert>
        </Grid>
      )}
      <Grid xs={12} sm={6} md={4} lg={3} key="active-listing-card">
        <Card sx={{ display: 'flex' }} onClick={() => navigate('/profile')}>
          <CardContent sx={{ flexGrow: 1 }}>
            <Stack direction="column" alignItems="center">
              <HouseIcon />
              <Typography variant="button">{properties.length}</Typography>
              <Typography variant="caption">Active Listings</Typography>
            </Stack>
          </CardContent>
        </Card>
      </Grid>
      <Grid xs={12} sm={6} md={4} lg={3} key="num-views-card">
        <Card sx={{ display: 'flex' }}>
          <CardContent sx={{ flexGrow: 1 }}>
            <Stack direction="column" alignItems="center">
              <VisibilityIcon />
              <Typography>{numViews}</Typography>
              <Typography variant="caption">Total Views</Typography>
            </Stack>
          </CardContent>
        </Card>
      </Grid>
      <Grid xs={12} sm={6} md={4} lg={3} key="total-saves-card">
        <Card sx={{ display: 'flex' }}>
          <CardContent sx={{ flexGrow: 1 }}>
            <Stack direction="column" alignItems="center">
              <FavoriteIcon />
              <Typography>{numSaves}</Typography>
              <Typography variant="caption">Total Saves</Typography>
            </Stack>
          </CardContent>
        </Card>
      </Grid>
      <Grid xs={12} sm={6} md={4} lg={3} key="num-offers-card">
        <Card sx={{ display: 'flex' }} onClick={() => navigate('/offers')}>
          <CardContent sx={{ flexGrow: 1 }}>
            <Stack direction="column" alignItems="center">
              <RequestQuoteIcon />
              <Typography variant="h6">{numOffers}</Typography>
              <Typography variant="caption">Total Offers</Typography>
            </Stack>
          </CardContent>
        </Card>
      </Grid>
      <Grid xs={12} sm={6} md={4} lg={3} key="num-bids-card">
        <Card sx={{ display: 'flex' }} onClick={() => navigate('/bids')}>
          <CardContent sx={{ flexGrow: 1 }}>
            <Stack direction="column" alignItems="center">
              <RequestQuoteIcon />
              <Typography variant="h6">{numBids}</Typography>
              <Typography variant="caption">Total Bids</Typography>
            </Stack>
          </CardContent>
        </Card>
      </Grid>

      {account.tier === 'basic' && (
        <Grid xs={12} md={4}>
          <Card>
            <Stack direction="column">
              <Typography variant="h4">Upgrade your account</Typography>
              <Typography variant="caption">
                Unlock premium features to get more features and sell faster
              </Typography>
            </Stack>

            <CardActionArea>
              <Button variant="contained" component="label" onClick={() => navigate('/upgrade/')}>
                Upgrade
              </Button>
              <Button>Learn More</Button>
            </CardActionArea>
          </Card>
        </Grid>
      )}

      {/* Properties */}
      {message && (
        <Alert severity={message.type} sx={{ mb: 2 }}>
          {message.text}
        </Alert>
      )}
      {properties.length > 0 && (
        <Grid xs={12}>
          <Divider sx={{ my: 2 }} />
        </Grid>
      )}
      {properties.map((item) => (
        <Grid xs={12} key={item.id}>
          <PropertyDetailCard
            property={item}
            isPublicPage={false}
            onSave={handleSaveProperty}
            isOwnerView={true}
            onDelete={handleDeleteProperty}
          />
          {/* <ProperyInfoCards property={item} /> */}
        </Grid>
      ))}
      <Grid xs={12}>
        <Divider sx={{ my: 2 }} />
      </Grid>

      <Grid xs={12} md={documentsCardLength}>
        <Card sx={{ display: 'flex' }}>
          <Stack direction="column">
            <Typography variant="h4">Documents Requiring Attention</Typography>
          </Stack>
          {documents.length === 0 ? (
            <Typography variant="caption">
              There are no documents that require your attention at this point
            </Typography>
          ) : (
            <CardContent sx={{ flexGrow: 1 }}>
              <DataGrid getRowHeight={() => 70} rows={DocumentRows} columns={documentColumns} />
            </CardContent>
          )}
        </Card>
      </Grid>

      <Grid xs={12} md={savedPropertiesCardLength}>
        <Card>
          <Stack direction="column">
            <Stack direction="column">
              <Typography variant="h4">Saved Properties</Typography>
              <Typography variant="caption">Keep track of the properties you have saved</Typography>
            </Stack>

            <CardContent>
              <SavedPropertiesTable savedProperties={savedProperties} />
            </CardContent>
          </Stack>
        </Card>
      </Grid>
      <Grid xs={12} md={12}>
        {account.tier === 'premium' ? (
          <Card>
            <Stack direction="column">
              <Stack direction="column">
                <Typography variant="h4">Video Progress</Typography>
                <Typography variant="caption">
                  Complete our FSBO training to maximize your sale potential
                </Typography>
              </Stack>

              <CardContent>
                <EducationInfoCards />
              </CardContent>
            </Stack>
          </Card>
        ) : (
          <Card>
            <Stack direction="column">
              <Typography variant="h4">Video Progress</Typography>
              <Typography variant="caption">
                Upgrade to get access to FSBO educational videos
              </Typography>
            </Stack>

            <CardActionArea>
              <Button variant="contained" component="label" onClick={() => navigate('/upgrade/')}>
                Upgrade
              </Button>
              <Button>Learn More</Button>
            </CardActionArea>
          </Card>
        )}
      </Grid>
    </Grid>
  );
};

export default PropertyOwnerDashboard;
