/* eslint-disable -- temporary disable for development/testing purposes */

'use client';

import React, { useState, useEffect } from 'react';
import {
  Box,
  Card,
  Typography,
  Tabs,
  Tab,
  Divider,
  Link,
  Accordion,
  AccordionSummary,
  AccordionDetails,
  CircularProgress,
  Chip,
  Avatar
} from '@mui/material';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import { useParams } from 'next/navigation';

const PatientDetailsPage = () => {
  const { id } = useParams(); // assuming route is /patients/[id]
  const [tabIndex, setTabIndex] = useState(0);
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState<any>(null);

  const handleTabChange = (_: React.SyntheticEvent, newIndex: number) => {
    setTabIndex(newIndex);
  };

  useEffect(() => {
    const fetchData = async () => {
      try {
        const res = await fetch(`/admin/api/customers/${id}/details`);
        const result = await res.json();
        // console.log(result.chats,'chatschats')
        setData(result);
      } catch (error) {
        // console.error('Error fetching patient data:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [id]);

  if (loading) {
    return (
      <Box p={4}>
        <CircularProgress />
      </Box>
    );
  }

  if (!data) {
    return (
      <Box p={4}>
        <Typography color="error">Failed to load data.</Typography>
      </Box>
    );
  }

  const { user, appointments, homeExercises, attachments, chats, callLogs } = data;

  const upcomingAppointments = appointments?.filter((a: any) => a.status === 'pending') || [];
  const pastAppointments = appointments?.filter((a: any) => a.status !== 'pending') || [];

  return (
    <Box p={4}>
      {/* Header */}
      <Typography variant="h4" gutterBottom>
        Patient Profile
      </Typography>

      {/* Basic Info */}
      <Card sx={{ p: 3, mb: 4 }}>
        <Typography variant="h6">Basic Info</Typography>
        <Typography>Name: {user?.name}</Typography>
        <Typography>Email: {user?.email}</Typography>
        <Typography>Phone: {user.mobile_number}</Typography>
        <Typography>Gender: {user.gender}</Typography>
        <Typography>Address: {user.address}</Typography>
        {data?.userTags?.length > 0 && (
    <Box mt={2}>
      <Typography variant="subtitle1" gutterBottom>
        Tags:
      </Typography>
      <Box display="flex" flexWrap="wrap" gap={1}>
        {data.userTags.map((tag: any) => (
          <Chip
            key={tag.id}
            label={tag.name}
            style={{
              backgroundColor: tag.color,
              color: '#fff',
              fontWeight: 500,
            }}
          />
        ))}
      </Box>
    </Box>
  )}
      </Card>

      {/* Tabs */}
      <Tabs value={tabIndex} onChange={handleTabChange} sx={{ mb: 3 }}>
        <Tab label="Details" />
        <Tab label="TEAM CHAT" />
        <Tab label="CALL LOGS" />
        <Tab label="Documentation" />
      </Tabs>

      {/* Details Tab */}
      {tabIndex === 0 && (
        <Box>
      <Accordion sx={{ mb: 2 }}>
  <AccordionSummary expandIcon={<ExpandMoreIcon />}>
    <Typography variant="h6">Shared Notes</Typography>
  </AccordionSummary>
  <AccordionDetails>
    {data.notes?.map((note: any, index: number) => (
      <Box key={index} mb={2} p={2} border={1} borderColor="grey.300" borderRadius={2}>
      
        <Typography variant="subtitle1" fontWeight="bold" gutterBottom>
          {note.title}
        </Typography>
        <Typography>{note.description}</Typography>
        <Box display="flex" justifyContent="space-between" mb={1}>
          <Typography variant="body2" color="textSecondary">
            Added by: <strong>{note.doctor_name}</strong> ({note.doctor_degree})
          </Typography>
          <Typography variant="body2" color="textSecondary">
            {note.date}
          </Typography>
        </Box>
      </Box>
    ))}
  </AccordionDetails>
</Accordion>


<Accordion sx={{ mb: 2 }}>
  <AccordionSummary expandIcon={<ExpandMoreIcon />}>
    <Typography variant="h6">Home Exercises</Typography>
  </AccordionSummary>
  <AccordionDetails>
    {data.homeExercises?.map((note: any, index: number) => (
      <Box key={index} mb={2} p={2} border={1} borderColor="grey.300" borderRadius={2}>
      
        <Typography variant="subtitle1" fontWeight="bold" gutterBottom>
          {note.title}
        </Typography>
        <Typography>{note.description}</Typography>
        <Box display="flex" justifyContent="space-between" mb={1}>
          <Typography variant="body2" color="textSecondary">
            Added by: <strong>{note.doctor_name}</strong> ({note.doctor_degree})
          </Typography>
          <Typography variant="body2" color="textSecondary">
            {note.date}
          </Typography>
        </Box>
      </Box>
    ))}
  </AccordionDetails>
</Accordion>

         

<Accordion sx={{ mb: 2 }}>
  <AccordionSummary expandIcon={<ExpandMoreIcon />}>
    <Typography variant="h6">Attachments</Typography>
  </AccordionSummary>
  <AccordionDetails>
    {attachments && attachments.length > 0 ? (
      attachments.map((file: any, index: number) => {
        const fileUrl = `https://helloprovider.co/app/images/${file.profile}`;
        return (
          <Box
            key={index}
            mb={2}
            p={2}
            border={1}
            borderColor="grey.300"
            borderRadius={2}
            display="flex"
            flexDirection="column"
          >
            {/* Image Preview (if applicable) */}
            {file.profile?.match(/\.(jpeg|jpg|png|gif|bmp)$/i) && (
              <Box mb={1}>
                <img
                  src={fileUrl}
                  alt={file.profile}
                  style={{ width: '100px', height: 'auto', borderRadius: 8 }}
                />
              </Box>
            )}

            {/* File Name Link */}
            <Link href={fileUrl} target="_blank" rel="noopener" underline="hover">
              {file.profile}
            </Link>

            {/* Metadata */}
            <Typography variant="body2" color="textSecondary" mt={1}>
              Added by: <strong>{file.doctor_name}</strong> ({file.doctor_degree})
            </Typography>
            <Typography variant="body2" color="textSecondary">
              {file.date}
            </Typography>
          </Box>
        );
      })
    ) : (
      <Typography>No attachments found</Typography>
    )}
  </AccordionDetails>
</Accordion>


          <Accordion sx={{ mb: 2 }}>
  <AccordionSummary expandIcon={<ExpandMoreIcon />}>
    <Typography variant="h6">Upcoming Appointments</Typography>
  </AccordionSummary>
  <AccordionDetails>
    {upcomingAppointments && upcomingAppointments.length > 0 ? (
      upcomingAppointments.map((appt: any, index: number) => (
        <Typography key={index}>
          – {appt.date} – {appt.doctor_name} – {appt.time}
        </Typography>
      ))
    ) : (
      <Typography>No active appointment found</Typography>
    )}
  </AccordionDetails>
</Accordion>


          <Accordion sx={{ mb: 2 }}>
  <AccordionSummary expandIcon={<ExpandMoreIcon />}>
    <Typography variant="h6">Past & Cancelled Appointments</Typography>
  </AccordionSummary>
  <AccordionDetails>
    {pastAppointments.map((appt: any, index: number) => (
      <Box
        key={index}
        mb={2}
        p={2}
        border={1}
        borderColor="grey.300"
        borderRadius={2}
      >
        <Box display="flex" justifyContent="space-between" alignItems="flex-start" mb={1}>
          <Box>
            <Typography fontWeight="bold">
              Dr. {appt.doctor_name} ({appt.doctor_degree})
            </Typography>
            <Typography variant="body2" color="textSecondary">
              {appt.date} ({appt.day}) at {appt.time}
            </Typography>
          </Box>

          <Box textAlign="right">
            <Typography
              variant="body2"
              sx={{ color: appt.status === 'complete' ? 'green' : 'red', fontWeight: 'bold' }}
            >
              {appt.status}
            </Typography>
            <Typography variant="body2" color="textSecondary">
              {appt.category}
            </Typography>
          </Box>
        </Box>
      </Box>
    ))}
  </AccordionDetails>
</Accordion>


        </Box>
      )}

{tabIndex === 1 && (
  <Card sx={{ p: 2 }}>
    <Typography variant="h6" gutterBottom>Team Chat</Typography>
    <Divider sx={{ mb: 2 }} />
    
    {chats && chats.length > 0 ? (
      chats.map((chat: any, index: number) => {
        const isFile = chat.last_message?.startsWith('/uploads/');
        const isImage = /\.(jpg|jpeg|png|gif)$/i.test(chat.last_message);
        const isPDF = /\.pdf$/i.test(chat.last_message);
        const fileExt = chat.last_message?.split('.').pop()?.toLowerCase();
        const companyName = `${chat.company_first_name} ${chat.company_last_name}`;
        const formattedTime = new Date(chat.timestamp).toLocaleDateString('en-GB');

        return (
          <Box
            key={index}
            sx={{
              backgroundColor: '#fff',
              borderRadius: 2,
              boxShadow: 3,
              p: 2,
              mb: 3,
              width: '95%',
              mx: 'auto',
            }}
          >
            {/* Company name bar */}
            <Box sx={{ display: 'flex', justifyContent: 'flex-end', borderBottom: 1, borderColor: 'lightgray', mb: 2 }}>
              <Box sx={{ backgroundColor: '#AEE6FB', px: 2, py: 0.5, borderRadius: 0.5 }}>
                <Typography sx={{ color: '#92BC2A', fontWeight: 'bold' }}>
                  {companyName}
                </Typography>
              </Box>
            </Box>

            {/* Main content row */}
            <Box sx={{ display: 'flex', alignItems: 'center' }}>
              <Avatar src={chat.chat_image} alt="Chat Avatar" sx={{ width: 48, height: 48, mr: 2 }} />
              <Box sx={{ flex: 1 }}>
                <Typography variant="subtitle1" fontWeight="bold" noWrap>
                  {chat.group_name}
                </Typography>

                {/* Last message display */}
                {chat.last_message ? (
                  isImage ? (
                    <Box sx={{ display: 'flex', alignItems: 'center', mt: 0.5 }}>
                      <Typography variant="body2" sx={{ color: 'gray' }}>
                        {chat.last_sender_name && `${chat.last_sender_name}: `}
                      </Typography>
                      <Typography variant="body2" sx={{ color: 'gray', fontWeight: 'bold', ml: 1 }}>
                        🖼️ Photo
                      </Typography>
                    </Box>
                  ) : isPDF ? (
                    <Box sx={{ display: 'flex', alignItems: 'center', mt: 0.5 }}>
                      <Typography variant="body2" sx={{ color: 'gray' }}>
                        {chat.last_sender_name && `${chat.last_sender_name}: `}
                      </Typography>
                      <Typography variant="body2" sx={{ color: 'gray', fontWeight: 'bold', ml: 1 }}>
                        📄 File
                      </Typography>
                    </Box>
                  ) : (
                    <Typography
                      variant="body2"
                      sx={{ color: 'gray', mt: 0.5 }}
                      noWrap
                    >
                      {chat.last_sender_name && `${chat.last_sender_name}: `}{chat.last_message}
                    </Typography>
                  )
                ) : (
                  <Typography variant="body2" color="gray" sx={{ mt: 0.5 }}>
                    No message in channel yet
                  </Typography>
                )}
              </Box>
            </Box>

            {/* Time and Members */}
            <Box sx={{ display: 'flex', justifyContent: 'space-between', mt: 2 }}>
              <Typography variant="caption" color="text.secondary">
                Members: {chat.member_names}
              </Typography>
              <Typography variant="caption" fontWeight="bold" color="gray">
                {formattedTime}
              </Typography>
            </Box>
          </Box>
        );
      })
    ) : (
      <Typography variant="body2" color="text.secondary" align="center">
        No chat found
      </Typography>
    )}
  </Card>
)}



      {/* Call Logs Tab */}
      {tabIndex === 2 && (
  <Card sx={{ p: 2 }}>
    <Typography variant="h6" gutterBottom>Call Logs</Typography>
    <Divider sx={{ mb: 2 }} />
    
    {callLogs && callLogs.length > 0 ? (
      callLogs.map((log: any, index: number) => {
        const dateObj = new Date(log.date);
        const formattedDate = dateObj.toLocaleDateString('en-GB', {
          weekday: 'short',
          day: '2-digit',
          month: 'short',
          year: 'numeric'
        });
        const formattedTime = dateObj.toLocaleTimeString('en-GB', {
          hour: '2-digit',
          minute: '2-digit'
        });

        return (
          <Box key={index} sx={{ mb: 2, p: 2, border: '1px solid #ccc', borderRadius: 2, backgroundColor: '#f9f9f9' }}>
            <Typography variant="subtitle2" color="text.secondary">
              {formattedTime} on {formattedDate}
            </Typography>
            <Typography variant="body1">
              📞 <strong>Mobile:</strong> {log.mobile_no}
            </Typography>
            <Typography variant="body2">
              👤 <strong>User:</strong> {log.user_name} &nbsp;|&nbsp; 👨‍⚕️ <strong>Doctor:</strong> {log.doctor_name}
            </Typography>
            <Typography variant="body2">
              ⏱ <strong>Duration:</strong> {log.duration || 'Missed'} &nbsp;|&nbsp; 🔄 <strong>Type:</strong> {log.type}
            </Typography>
            {log.note && (
              <Typography variant="body2">
                📝 <strong>Note:</strong> {log.note}
              </Typography>
            )}
            <Typography variant="body2" sx={{ mt: 0.5 }}>
              📋 <strong>Status:</strong> {log.status}
            </Typography>
          </Box>
        );
      })
    ) : (
      <Typography variant="body2" color="text.secondary" align="center">
        No call logs found
      </Typography>
    )}
  </Card>
)}


      {/* Documentation Tab */}
      {tabIndex === 3 && (
        <Card sx={{ p: 2 }}>
          <Typography variant="h6">Documentation (Voice Notes)</Typography>
          <Divider sx={{ my: 1 }} />
          {attachments
            ?.filter((file: any) => file.filename.endsWith('.mp3'))
            .map((file: any, index: number) => (
              <Link key={index} href={file.url} target="_blank">
                {file.filename}
              </Link>
            ))}
        </Card>
      )}
    </Box>
  );
};

export default PatientDetailsPage;
