import React, { useState, useEffect, useContext, useRef } from 'react';
import { useSearchParams } from 'react-router-dom';
import { AxiosResponse } from 'axios';

import { axiosInstance } from '../../axiosApi';
import PageLoader from 'components/loading/PageLoader';
import {
  Box,
  Container,
  Typography,
  Paper,
  Grid,
  Stack,
  Button,
  List,
  ListItem,
  ListItemText,
  Avatar,
  TextField,
} from '@mui/material';
import { SupportCaseApi, SupportMessageApi } from 'types';
import { AccountContext } from 'contexts/AccountContext';
import { formatTimestamp } from 'utils';
import ChatBubbleOutlineIcon from '@mui/icons-material/ChatBubbleOutline';
import QuestionMarkOutlined from '@mui/icons-material/QuestionMarkOutlined';
import SendIcon from '@mui/icons-material/Send';
import CreateSupportCaseDialogContent from 'components/sections/dashboard/Home/Support/CreateSupportCaseDialogContent';

interface SupportManagerProps {}

const SupportManager: React.FC<SupportManagerProps> = ({}) => {
  const [searchParams] = useSearchParams();
  const { account } = useContext(AccountContext);
  const [supportCases, setSupportCases] = useState<SupportCaseApi[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(false);
  const [showDialog, setShowDialog] = useState<boolean>(false);
  const [selectedSupportCaseId, setSelectedSupportCaseId] = useState<number | null>(null);
  const [newMessageContent, setNewMessageContent] = useState<string>('');
  const [loadingMessages, setLoadingMessages] = useState(false);
  const [errorMessages, setErrorMssages] = useState(false);
  const [supportCase, setSupportCase] = useState<SupportCaseApi>(null);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const selectedSupportCase = searchParams.get('selectedSupportCase');
    if (selectedSupportCase) {
      console.log(selectedSupportCase);
      setSelectedSupportCaseId(parseInt(selectedSupportCase, 10));
    }
  }, [searchParams]);

  useEffect(() => {
    const fetchSupportCases = async () => {
      try {
        setLoading(true);
        setError(false);
        const { data }: AxiosResponse<SupportCaseApi[]> =
          await axiosInstance.get('/support/cases/');
        const data_with_messages: SupportCaseApi[] = data;
        for (let i = 0; i < data_with_messages.length; i++) {
          if (data_with_messages[i].messages === undefined) {
            data_with_messages[i].messages = [
              {
                id: 0,
                text: data_with_messages[i].description,
                created_at: data_with_messages[i].created_at,
                updated_at: data_with_messages[i].updated_at,
              },
            ];
          }
        }
        setSupportCases(data_with_messages);
      } catch (error) {
        console.error(error);
        setError(true);
      } finally {
        setLoading(false);
      }
    };
    fetchSupportCases();
  }, []);

  useEffect(() => {
    const fetchMessages = async () => {
      try {
        setLoadingMessages(true);
        setErrorMssages(false);
        const { data }: AxiosResponse<SupportCaseApi> = await axiosInstance.get(
          `/support/cases/${selectedSupportCaseId}/`,
        );
        console.log(data);
        // 1. Create a new SupportMessageApi object from the description
        const descriptionMessage: SupportMessageApi = {
          // You'll need to decide on values for these fields.
          // Since this is a synthetic message based on the case description,
          // you might use special values like -1 for id and 'System' for the user fields.
          id: -1, // Use a unique or sentinel value
          text: data.description,
          user: -1, // Sentinel user ID
          user_first_name: data.title, // Use the title as the sender/label
          user_last_name: 'Description',
          created_at: data.created_at, // Use the case's creation date
          updated_at: data.created_at,
        };

        // 2. Create the updated SupportCaseApi object
        const updatedSupportCase: SupportCaseApi = {
          ...data, // Keep all existing case data
          // Prepend the new description message to the existing messages array
          messages: [descriptionMessage, ...data.messages],
        };
        setSupportCase(updatedSupportCase);
      } catch (error) {
        setErrorMssages(true);
      } finally {
        setLoadingMessages(false);
      }
    };
    fetchMessages();
  }, [selectedSupportCaseId]);

  const handleOpenCreateSupportCaseDialog = () => {
    setShowDialog(true);
  };

  const handleCloseCreateSupportDialog = () => {
    setShowDialog(false);
    setSelectedSupportCaseId(null);
  };

  const handleCreateSupportCase = async (
    supportCase: Omit<SupportCaseApi, 'id' | 'status' | 'messages' | 'created_at' | 'updated_at'>,
  ) => {
    try {
      const response: AxiosResponse<SupportCaseApi> = await axiosInstance.post(
        '/support/cases/',
        supportCase,
      );
      setSupportCases((prevCases) => [...prevCases, response.data]);
      handleCloseCreateSupportDialog();
      setSelectedSupportCaseId(response.data.id);
    } catch (error) {
      console.error('Failed to create support case', error);
    }
  };

  // Handle sending a new message
  const handleSendMessage = async () => {
    if (!newMessageContent.trim() || !selectedSupportCaseId) {
      return; // Don't send empty messages or if no conversation is selected
    }

    // send the message to the backend
    try {
      const { data }: AxiosResponse<SupportMessageApi> = await axiosInstance.post(
        `/support/messages/`,
        {
          user: account?.id,
          text: newMessageContent.trim(),
          support_case: selectedSupportCaseId,
        },
      );

      setSupportCases((prevConversations) =>
        prevConversations.map((conv) =>
          conv.id === selectedSupportCaseId
            ? {
                ...conv,
                messages: [...conv.messages, data],
                updated_at: data.updated_at,
              }
            : conv,
        ),
      );
      setNewMessageContent(''); // Clear the input field
    } catch (error) {}
  };

  if (loading) {
    return <PageLoader />;
  }

  if (error) {
    return (
      <Container>
        <Box sx={{ textAlign: 'center', mt: 4 }}>
          <Typography variant="h6" color="error">
            Failed to load Support Cases. Please try again later.
          </Typography>
        </Box>
      </Container>
    );
  }

  const selectedSupportCase = supportCases.find((item) => item.id === selectedSupportCaseId);

  return (
    <Container
      sx={{ py: 4, height: '90vh', width: 'fill', display: 'flex', flexDirection: 'column' }}
    >
      <Paper
        elevation={3}
        sx={{ flexGrow: 1, display: 'flex', borderRadius: 3, overflow: 'hidden' }}
      >
        <Grid container sx={{ height: '100%', width: '100%' }}>
          {/* Left Panel: Conversation List */}
          <Grid
            size={{ xs: 12, md: 4 }}
            sx={{
              borderRight: { md: '1px solid', borderColor: 'grey.200' },
              display: 'flex',
              flexDirection: 'column',
            }}
          >
            <Box sx={{ p: 3, borderBottom: '1px solid', borderColor: 'grey.200', display: 'flex' }}>
              <Stack direction="row" sx={{ width: '100%' }}>
                <Typography variant="h5" component="h2" sx={{ fontWeight: 'bold' }}>
                  Support Cases
                </Typography>
                {account?.user_type === 'property_owner' && (
                  <Button
                    variant="contained"
                    color="primary"
                    sx={{ ml: 'auto' }}
                    onClick={handleOpenCreateSupportCaseDialog}
                  >
                    Create
                  </Button>
                )}
              </Stack>
            </Box>
            <List sx={{ flexGrow: 1, overflowY: 'auto', p: 1 }}>
              {supportCases.length === 0 ? (
                <Box sx={{ p: 2, textAlign: 'center', color: 'grey.500' }}>
                  <QuestionMarkOutlined sx={{ fontSize: 40, mb: 1 }} />
                  <Typography>No support cases yet.</Typography>
                </Box>
              ) : (
                supportCases
                  .sort(
                    (a, b) => new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime(),
                  )
                  .map((conv) => (
                    <ListItem
                      key={conv.id}
                      button
                      selected={selectedSupportCaseId === conv.id}
                      onClick={() => setSelectedSupportCaseId(conv.id)}
                      sx={{ py: 1.5, px: 2 }}
                    >
                      <ListItemText
                        primary={
                          <Typography variant="subtitle1" sx={{ fontWeight: 'medium' }}>
                            {conv.title}
                          </Typography>
                        }
                        secondary={
                          <Box
                            sx={{
                              display: 'flex',
                              justifyContent: 'space-between',
                              alignItems: 'center',
                            }}
                          >
                            <Typography
                              variant="body2"
                              color="text.secondary"
                              noWrap
                              sx={{ flexGrow: 1, pr: 1 }}
                            >
                              {conv.status}
                            </Typography>
                            <Typography variant="caption" color="text.disabled">
                              {formatTimestamp(conv.updated_at)}
                            </Typography>
                          </Box>
                        }
                      />
                    </ListItem>
                  ))
              )}
            </List>
          </Grid>

          {/* Right Panel: Conversation Detail */}
          <Grid size={{ xs: 12, md: 8 }} sx={{ display: 'flex', flexDirection: 'column' }}>
            {supportCase ? (
              <>
                {/* Support Case Header */}
                <Box
                  sx={{
                    p: 3,
                    borderBottom: '1px solid',
                    borderColor: 'grey.200',
                    display: 'flex',
                    alignItems: 'center',
                    gap: 2,
                  }}
                >
                  {/*<Avatar sx={{ bgcolor: 'purple.200' }}>
                    {supportCase.title
                      .split(' ')
                      .map((n) => n[0])
                      .join('')}
                  </Avatar>*/}
                  <Typography variant="h6" component="h3" sx={{ fontWeight: 'bold' }}>
                    {supportCase.title} | {supportCase.category}
                  </Typography>
                </Box>

                {/* Messages Area */}
                <Box sx={{ flexGrow: 1, overflowY: 'auto', p: 3, bgcolor: 'grey.50' }}>
                  {supportCase.messages.map((message) => (
                    <Box
                      key={message.id}
                      sx={{
                        display: 'flex',
                        justifyContent: message.user === account?.id ? 'flex-end' : 'flex-start',
                        mb: 2,
                      }}
                    >
                      <Box
                        sx={{
                          maxWidth: '75%',
                          p: 1.5,
                          borderRadius: 2,
                          bgcolor: message.user === account?.id ? 'purple.200' : 'lightblue.50',
                          color: 'grey.800',
                          boxShadow: '0 1px 2px rgba(0,0,0,0.05)',
                        }}
                      >
                        <Typography variant="body2" sx={{ fontWeight: 'medium', mb: 0.5 }}>
                          {message.user === account?.id ? 'You' : supportCase.withName}
                        </Typography>
                        <Typography variant="body1">{message.text}</Typography>
                        <Typography
                          variant="caption"
                          color="text.secondary"
                          sx={{ display: 'block', textAlign: 'right', mt: 0.5 }}
                        >
                          {formatTimestamp(message.updated_at)}
                        </Typography>
                      </Box>
                    </Box>
                  ))}
                  <div ref={messagesEndRef} /> {/* Scroll target */}
                </Box>

                {/* Message Input */}
                <Box
                  sx={{
                    p: 2,
                    borderTop: '1px solid',
                    borderColor: 'grey.200',
                    display: 'flex',
                    alignItems: 'center',
                    gap: 2,
                  }}
                >
                  <TextField
                    fullWidth
                    variant="outlined"
                    placeholder="Type your message..."
                    value={newMessageContent}
                    onChange={(e) => setNewMessageContent(e.target.value)}
                    onKeyPress={(e) => {
                      if (e.key === 'Enter') {
                        handleSendMessage();
                      }
                    }}
                    size="small"
                    sx={{ '& .MuiOutlinedInput-root': { borderRadius: 2 } }}
                  />
                  <Button
                    variant="contained"
                    color="primary"
                    onClick={handleSendMessage}
                    disabled={selectedSupportCaseId === null || supportCase.status !== 'opened'}
                    endIcon={<SendIcon />}
                    sx={{ px: 3, py: 1.2 }}
                  >
                    Send
                  </Button>
                </Box>
              </>
            ) : (
              <Box
                sx={{
                  flexGrow: 1,
                  display: 'flex',
                  flexDirection: 'column',
                  justifyContent: 'center',
                  alignItems: 'center',
                  p: 3,
                  color: 'grey.500',
                }}
              >
                <QuestionMarkOutlined sx={{ fontSize: 80, mb: 2 }} />
                <Typography variant="h6">Select a support case to view messages</Typography>
                <Typography variant="body2">
                  Click on a support case from the left panel to get started.
                </Typography>
              </Box>
            )}
          </Grid>
        </Grid>
      </Paper>
      <CreateSupportCaseDialogContent
        showDialog={showDialog}
        closeDialog={handleCloseCreateSupportDialog}
        createSupportCase={handleCreateSupportCase}
      />
    </Container>
  );
};

export default SupportManager;
