// src/pages/VendorDashboardPage.tsx

import React, { ReactElement, useEffect, useState } from 'react';
import {
  Container,
  Typography,
  Box,
  Grid,
  Card,
  CardContent,
  Divider,
  Chip,
  Alert,
} from '@mui/material';
import { useNavigate } from 'react-router-dom';
import VisibilityIcon from '@mui/icons-material/Visibility';
import GavelIcon from '@mui/icons-material/Gavel';
import ChatBubbleIcon from '@mui/icons-material/ChatBubble';
import NotificationsIcon from '@mui/icons-material/Notifications';
import PaidIcon from '@mui/icons-material/Paid';
import { DashboardProps } from 'pages/home/Dashboard';
import { BidAPI, ConverationAPI, VendorAPI, VendorItem } from 'types';
import { AxiosResponse } from 'axios';
import { axiosInstance } from '../../../../../axiosApi';
import DashboardLoading from './DashboardLoading';
import DashboardErrorPage from './DashboardErrorPage';
import VendorDetail from '../Vendor/VendorDetail';

// Mock Data for the Vendor Dashboard
interface VendorDashboardData {
  views: {
    total: number;
    last_30_days: number;
  };
  bids: {
    total: number;
    responded_to: number;
    new_bids: number;
    selected_for: number;
  };
  conversations: {
    unread: number;
  };
}

const mockVendorData: VendorDashboardData = {
  views: {
    total: 5432,
    last_30_days: 215,
  },
  bids: {
    total: 45,
    responded_to: 38,
    new_bids: 7,
    selected_for: 12,
  },
  conversations: {
    unread: 3,
  },
};

const VendorDashboard = ({ account }: DashboardProps): ReactElement => {
  const [vendor, setVendor] = useState<VendorAPI | null>(null);
  const [loadingData, setLoadingData] = useState<boolean>(true);
  // bid data
  const [numBids, setNumBids] = useState<Number>(0);
  const [numBidResponses, setNumBidResponses] = useState<Number>(0);
  const [numBidsSelected, setNumBidsSelected] = useState<Number>(0);
  const [newBids, setNewBids] = useState<Number>(0);
  const [numConverstaions, setNumConversations] = useState<Number>(0);

  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);
      }
    };
    const fetchBids = async () => {
      try {
        const { data }: AxiosResponse<BidAPI[]> = await axiosInstance.get('/bids/');
        if (data.length > 0) {
          setNumBids(data.length);
          let numBidResponsesFound: number = 0;
          let numBidsSelectedFound: number = 0;
          let newBidsFound: number = 0;
          data.map((item) => {
            let foundNewBid: boolean = true;
            item.responses.map((response) => {
              if (response.vendor.user.id === account.id) {
                numBidResponsesFound = numBidResponsesFound + 1;
                foundNewBid = false;
              }
              if (response.vendor.user.id === account.id && response.status === 'selected') {
                numBidsSelectedFound = numBidsSelectedFound + 1;
              }
            });
            newBidsFound = foundNewBid ? newBidsFound + 1 : newBidsFound;
          });

          setNumBidResponses(numBidResponsesFound);
          setNumBidsSelected(numBidsSelectedFound);
          setNewBids(newBidsFound);
        }
      } catch (error) {
        console.log(error);
      }
    };
    const fetchConversations = async () => {
      try {
        const { data }: AxiosResponse<ConverationAPI[]> =
          await axiosInstance.get('/conversations/');
        if (data.length > 0) {
          setNumConversations(data.length);
        }
      } catch (error) {
        console.log(error);
      } finally {
        setLoadingData(false);
      }
    };
    fetchVendor();
    fetchBids();
    fetchConversations();
  }, []);
  if (loadingData) {
    return <DashboardLoading />;
  }
  if (vendor === null) {
    return <DashboardErrorPage />;
  }

  const vendorItem: VendorItem = {
    contactPerson: vendor.user.first_name + ' ' + vendor.user.last_name,
    name: vendor.business_name,
    description: vendor.description,
    phone: vendor.phone_number,
    email: vendor.user.email,
    address: vendor.address,
    vendorImageUrl: '',
    rating: 5,
    servicesOffered: vendor.services,
    serviceAreas: vendor.service_areas,
    categoryId: vendor.business_type,
    latitude: Number(vendor.latitude),
    longitude: Number(vendor.longitude),
    views: vendor.views,
  };
  return (
    <Container maxWidth="xl" sx={{ mt: 4, mb: 4 }}>
      <Typography variant="h4" component="h1" gutterBottom color="background.paper">
        Vendor Dashboard
      </Typography>
      {!account.profile_created && (
        <Alert severity="warning" sx={{ mb: 2 }}>
          Please set up your <a href="/profile">profile</a>
        </Alert>
      )}
      <Grid container spacing={3}>
        {/* Views Card */}
        <Grid size={{ xs: 12, sm: 6, md: 4 }}>
          <Card>
            <CardContent>
              <Box display="flex" alignItems="center" mb={2}>
                <VisibilityIcon color="primary" sx={{ fontSize: 36, mr: 1 }} />
                <Typography variant="h5" sx={{ fontWeight: 'bold' }}>
                  Profile Views
                </Typography>
              </Box>
              <Typography variant="h4" sx={{ fontWeight: 'bold' }}>
                {vendor.views.toLocaleString()}
              </Typography>
              <Typography variant="body2" color="text.secondary">
                Total Views
              </Typography>
              <Divider sx={{ my: 1 }} />
              <Typography variant="body1">
                {mockVendorData.views.last_30_days} in the last 30 days
              </Typography>
            </CardContent>
          </Card>
        </Grid>

        {/* Bids Card */}
        <Grid size={{ xs: 12, sm: 6, md: 4 }}>
          <Card>
            <CardContent>
              <Box display="flex" alignItems="center" mb={2}>
                <GavelIcon color="primary" sx={{ fontSize: 36, mr: 1 }} />
                <Typography variant="h5" sx={{ fontWeight: 'bold' }}>
                  Bids & Opportunities
                </Typography>
              </Box>
              <Box display="flex" justifyContent="space-around" textAlign="center">
                <Box>
                  <Typography variant="h4" sx={{ fontWeight: 'bold' }}>
                    {numBids}
                  </Typography>
                  <Typography variant="caption" color="text.secondary">
                    Total Bids
                  </Typography>
                </Box>
                <Box>
                  <Typography variant="h4" sx={{ fontWeight: 'bold' }}>
                    <Chip label={newBids} color="error" size="small" />
                  </Typography>
                  <Typography variant="caption" color="text.secondary">
                    New Bids
                  </Typography>
                </Box>
              </Box>
              <Divider sx={{ my: 1 }} />
              <Box display="flex" justifyContent="space-around" textAlign="center">
                <Box>
                  <Typography variant="h5" sx={{ fontWeight: 'bold' }}>
                    {numBidResponses}
                  </Typography>
                  <Typography variant="caption" color="text.secondary">
                    Responded To
                  </Typography>
                </Box>
                <Box>
                  <Typography variant="h5" sx={{ fontWeight: 'bold' }}>
                    {numBidsSelected}
                  </Typography>
                  <Typography variant="caption" color="text.secondary">
                    Selected For
                  </Typography>
                </Box>
              </Box>
            </CardContent>
          </Card>
        </Grid>

        {/* Conversations Card */}
        <Grid size={{ xs: 12, sm: 6, md: 4 }}>
          <Card>
            <CardContent>
              <Box display="flex" alignItems="center" mb={2}>
                <ChatBubbleIcon color="primary" sx={{ fontSize: 36, mr: 1 }} />
                <Typography variant="h5" sx={{ fontWeight: 'bold' }}>
                  Conversations
                </Typography>
              </Box>
              <Box textAlign="center" mb={1}>
                <Typography variant="h3" sx={{ fontWeight: 'bold', color: 'primary.main' }}>
                  {numConverstaions}
                </Typography>
                <Typography variant="subtitle1">Unread Messages</Typography>
              </Box>
              <Divider sx={{ my: 1 }} />
              <Typography variant="body2" color="text.secondary" textAlign="center">
                Stay on top of your messages to win more bids!
              </Typography>
            </CardContent>
          </Card>
        </Grid>

        {/* Example of other cards that could be useful */}

        {/*<Grid item xs={12} md={6}>
          <Card>
            <CardContent>
              <Box display="flex" alignItems="center" mb={2}>
                <PaidIcon color="primary" sx={{ fontSize: 36, mr: 1 }} />
                <Typography variant="h5" sx={{ fontWeight: 'bold' }}>
                  Recent Payments
                </Typography>
              </Box>
              <Typography variant="h6">You have no new payments.</Typography>
            </CardContent>
          </Card>
        </Grid>*/}
        <Grid size={{ xs: 12 }}>
          <Divider sx={{ my: 2 }} />
        </Grid>
        <Grid size={{ xs: 12, md: 12 }}>
          <VendorDetail vendor={vendorItem as VendorItem} showMessageBtn={false} />
        </Grid>
      </Grid>
    </Container>
  );
};

export default VendorDashboard;
