// src/components/VendorApp/VendorDetail.tsx
import React, { useContext, useEffect } from 'react';
import { Box, Typography, Paper, Avatar, Rating, Grid, Button, Stack } from '@mui/material';

import PhoneIcon from '@mui/icons-material/Phone';
import EmailIcon from '@mui/icons-material/Email';
import LocationOnIcon from '@mui/icons-material/LocationOn';
import { ConverationAPI, VendorItem } from 'types';
import VendorMap from './VendorMap';
import { useNavigate } from 'react-router-dom';
import { AccountContext } from 'contexts/AccountContext';
import { axiosInstance } from '../../../../../axiosApi';
import { AxiosResponse } from 'axios';
import MapComponent from 'components/base/MapComponent';

interface VendorDetailProps {
  vendor: VendorItem;
  showMessageBtn: boolean;
}

const VendorDetail: React.FC<VendorDetailProps> = ({ vendor, showMessageBtn }) => {
  const navigate = useNavigate();
  const { account, accountLoading } = useContext(AccountContext);
  const createMessage = async () => {
    // First see if there is one already
    const { data }: AxiosResponse<ConverationAPI[]> = await axiosInstance.get(
      `/conversations/?vendor=${vendor.id}`,
    );
    if (data.length === 0) {
      const { data }: AxiosResponse<ConverationAPI[]> = await axiosInstance.post(
        `/conversations/`,
        {
          property_owner: account?.id,
          vendor: vendor.id,
        },
      );
      navigate(`/conversations/?selectedConversation=${data[0].id}`);
    } else {
      navigate(`/conversations/?selectedConversation=${data[0].id}`);
    }
  };
  if (!vendor) {
    return (
      <Paper
        elevation={2}
        sx={{
          p: 3,
          height: '100%',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
        }}
      >
        <Typography variant="h6" color="text.secondary">
          No vendor selected
        </Typography>
      </Paper>
    );
  }

  useEffect(() => {
    // increment the vendor view count
    const incrementVendorCount = async () => {
      if (showMessageBtn) {
        try {
          await axiosInstance.post(`/vendors/${vendor.id}/increment_view_count/?search=1`);
        } catch (error) {}
      }
    };
    incrementVendorCount();
  }, []);

  return (
    <Paper elevation={3} sx={{ p: 2 }}>
      <Grid container sx={{ minHeight: '100%' }}>
        <Grid size={{ xs: 12, md: 6 }} sx={{ display: 'flex', flexDirection: 'column' }}>
          <Box display="flex" alignItems="center" mb={2}>
            <Avatar
              src={vendor.vendorImageUrl}
              alt={vendor.name}
              sx={{ width: 80, height: 80, mr: 2 }}
            />
            <Box>
              <Typography variant="h5" gutterBottom>
                {vendor.name}
              </Typography>
              <Box display="flex" alignItems="center">
                <Rating value={vendor.rating} readOnly precision={0.5} />
                <Typography variant="body2" sx={{ ml: 1 }}>
                  ({vendor.rating.toFixed(1)} / 5)
                </Typography>
              </Box>
            </Box>
          </Box>

          <Typography variant="body1" color="text.secondary" sx={{ mb: 2 }}>
            {vendor.description}
          </Typography>

          <Typography variant="h6" sx={{ mt: 3, mb: 1 }}>
            Contact Information
          </Typography>
          <Typography variant="body2" display="flex" alignItems="center" mb={0.5}>
            <PhoneIcon fontSize="small" sx={{ mr: 1 }} /> {vendor.phone}
          </Typography>
          <Typography variant="body2" display="flex" alignItems="center" mb={0.5}>
            <EmailIcon fontSize="small" sx={{ mr: 1 }} /> {vendor.email}
          </Typography>
          <Typography variant="body2" display="flex" alignItems="center">
            <LocationOnIcon fontSize="small" sx={{ mr: 1 }} /> {vendor.address}
          </Typography>

          <Typography variant="h6" sx={{ mt: 3, mb: 1 }}>
            Services Offered
          </Typography>
          <Box>
            {vendor.servicesOffered.map((service, index) => (
              <Typography key={index} variant="body2" sx={{ mb: 0.5 }}>
                - {service}
              </Typography>
            ))}
          </Box>
          <Typography variant="h6" sx={{ mt: 3, mb: 1 }}>
            Service Areas
          </Typography>
          <Box>
            {vendor.serviceAreas.map((service, index) => (
              <Typography key={index} variant="body2" sx={{ mb: 0.5 }}>
                - {service}
              </Typography>
            ))}
          </Box>
          {showMessageBtn && (
            <Button onClick={createMessage} disabled={accountLoading}>
              Message
            </Button>
          )}
        </Grid>
        <Grid size={{ xs: 12, md: 6 }} sx={{ display: 'flex', flexDirection: 'column' }}>
          <Box
            sx={{
              width: '100%',
              height: '100%', // Make sure the box takes available height
              minHeight: '400px', // Ensure a minimum height for the map
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
              borderRadius: '4px', // Optional: rounded corners
              overflow: 'hidden', // Ensures map doesn't overflow border radius
            }}
          >
            {vendor.latitude && vendor.longitude ? (
              <MapComponent lat={vendor.latitude} lng={vendor.longitude} address={vendor.address} />
            ) : (
              <Typography variant="body2" color="text.secondary">
                Location data not available for this vendor.
              </Typography>
            )}
          </Box>
        </Grid>
      </Grid>
    </Paper>
  );
};

export default VendorDetail;
