import { ReactElement, useContext, useEffect, useState } from 'react';
import { UserAPI, VendorAPI } from 'types';
import ChangePasswordCard from './ChangePasswordCard';
import {
  Container,
  Typography,
  Box,
  Divider,
  Alert,
  Avatar,
  Rating,
  Grid,
  Paper,
} from '@mui/material';
import VendorProfileCard from './VendorProfileCard';
import ServicesCard from './ServiceCard';
import { axiosInstance } from '../../../../../axiosApi';
import DashboardLoading from '../Dashboard/DashboardLoading';
import DashboardErrorPage from '../Dashboard/DashboardErrorPage';
import { ProfileProps } from 'pages/Profile/Profile';
import { useNavigate } from 'react-router-dom';

const VendorProfile = ({ account }: ProfileProps): ReactElement => {
  const [vendor, setVendor] = useState<VendorAPI | null>(null);
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
  const [loadingData, setLoadingData] = useState<boolean>(true);
  const navigate = useNavigate();

  useEffect(() => {
    const fetchVendor = async () => {
      try {
        const { data }: AxiosResponse<VendorAPI[]> = await axiosInstance.get('/vendors/');
        if (data.length > 0) {
          setVendor(data[0]);
        }
      } catch (error) {
        console.log(error);
      } finally {
        setLoadingData(false);
      }
    };
    fetchVendor();
  }, []);
  if (loadingData) {
    return <DashboardLoading />;
  }

  if (vendor === null) {
    return <DashboardErrorPage />;
  } else {
    const handleUpgradeSubscription = () => {
      navigate('/upgrade/');
      // setVendor((prev) => ({
      //   ...prev,
      //   user: { ...prev.user, tier: 'premium' },
      // }));
      // setMessage({ type: 'success', text: 'Subscription upgraded to Premium!' });
      // setTimeout(() => setMessage(null), 3000);
    };

    const handleSaveVendorProfile = (updatedVendor: VendorAPI) => {
      try {
        let newUpdatedVendor;
        // if the email is the same, remove it
        if (updatedVendor.user.email === account.email) {
          const { user, ...reducedVendor } = updatedVendor;
          const { email, ...reducedUser } = user;
          newUpdatedVendor = {
            user: {
              profile_created: true,
              ...reducedUser,
            },
            ...reducedVendor,
          };
        } else {
          newUpdatedVendor = updatedVendor;
        }
        newUpdatedVendor.user.profile_created = true;

        const { data, error } = axiosInstance.patch(`/vendors/${account.id}/`, {
          ...newUpdatedVendor,
        });
        setVendor(updatedVendor);
        setMessage({ type: 'success', text: 'Vendor profile updated successfully!' });
        setTimeout(() => setMessage(null), 3000);
      } catch (error) {
        console.log(error);
        setMessage({ type: 'error', text: 'Error saving the profile. Try again.' });
        setTimeout(() => setMessage(null), 3000);
      }
    };

    const handleSaveServices = (updatedServices: string[]) => {
      try {
        const { data, error } = axiosInstance.patch(`/vendors/${account.id}/`, {
          services: updatedServices,
        });
        setVendor((prev) => ({
          ...prev,
          services: updatedServices,
        }));
        setMessage({ type: 'success', text: 'Services updated successfully!' });
        setTimeout(() => setMessage(null), 3000);
      } catch (error) {
        setMessage({ type: 'error', text: 'Error saving services. Try again.' });
        setTimeout(() => setMessage(null), 3000);
      }
    };

    const handleSaveServiceAreas = (updatedServiceAreas: string[]) => {
      try {
        const { data, error } = axiosInstance.patch(`/vendors/${account.id}/`, {
          service_areas: updatedServiceAreas,
        });

        setVendor((prev) => ({
          ...prev,
          service_areas: updatedServiceAreas,
        }));
        setMessage({ type: 'success', text: 'Service areas updated successfully!' });
        setTimeout(() => setMessage(null), 3000);
      } catch (error) {
        setMessage({ type: 'error', text: 'Error saving service area. Try again.' });
        setTimeout(() => setMessage(null), 3000);
      }
    };

    return (
      <Container maxWidth="lg" sx={{ mt: 4, mb: 4 }}>
        <Typography variant="h4" component="h1" gutterBottom color="background.paper">
          Vendor Profile Dashboard
        </Typography>
        {message && (
          <Alert severity={message.type} sx={{ mb: 2 }}>
            {message.text}
          </Alert>
        )}

        <Paper sx={{ p: 3, mb: 3, display: 'flex', alignItems: 'center', gap: 3 }}>
          {vendor.profile_picture && (
            <Avatar
              src={vendor.profile_picture}
              alt={vendor.business_name}
              sx={{ width: 80, height: 80 }}
            />
          )}
          <Box>
            <Typography variant="h5">{vendor.business_name}</Typography>
            <Typography variant="body1" color="textSecondary">
              {vendor.business_type}
            </Typography>
            {vendor.average_rating !== undefined && vendor.num_reviews !== undefined && (
              <Box sx={{ display: 'flex', alignItems: 'center' }}>
                <Rating value={vendor.average_rating} precision={0.1} readOnly />
                <Typography variant="body2" color="textSecondary" sx={{ ml: 1 }}>
                  ({vendor.num_reviews} reviews)
                </Typography>
              </Box>
            )}
          </Box>
        </Paper>

        <VendorProfileCard
          vendor={vendor}
          onUpgrade={handleUpgradeSubscription}
          onSave={handleSaveVendorProfile}
        />

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

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

        <ServicesCard
          services={vendor.services}
          onSave={handleSaveServices}
          serviceAreas={vendor.service_areas}
          onSaveServiceAreas={handleSaveServiceAreas}
        />

        {/* You can add more sections here, e.g., for portfolio, reviews, etc. */}
      </Container>
    );
  }
};

export default VendorProfile;
