import React, { useState, useEffect } from 'react';
import { format } from 'date-fns';
import { es } from 'date-fns/locale';
import { Timestamp } from 'firebase/firestore';
import { auth } from '../../config/firebase';
import { getUserTests, deleteTest, VarroaTest } from '../../services/reportService';
import { useAuth } from '../../contexts/AuthContext';
import { 
  Box, 
  Typography, 
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  IconButton, 
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Divider,
  Chip,
  Grid,
  Card,
  CardContent,
  Snackbar,
  Button,
  LinearProgress
} from '@mui/material';
import { styled } from '@mui/material/styles';
import DeleteIcon from '@mui/icons-material/Delete';
import InfoIcon from '@mui/icons-material/Info';
import { Alert } from '@mui/material';
import {
  PieChart,
  Pie,
  Cell,
  ResponsiveContainer,
  Legend,
  Tooltip,
  RadarChart,
  PolarGrid,
  PolarAngleAxis,
  PolarRadiusAxis,
  Radar,
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Area,
  AreaChart,
  Bar,
  BarChart,
  ComposedChart
} from 'recharts';

interface TreatmentPredictionData {
  date: string;
  rate: number;
}

interface ExtendedVarroaTest extends VarroaTest {
  id: string;
  treatmentEffectiveness?: number;
  treatmentDuration?: number;
  costEffectiveness?: number;
}

interface FirestoreTimestamp {
  seconds: number;
  nanoseconds: number;
}

const StatusChip = styled(Chip)<{ status: string }>(({ theme, status }) => ({
  backgroundColor: 
    status === 'green' ? theme.palette.success.light :
    status === 'yellow' ? theme.palette.warning.light :
    theme.palette.error.light,
  color: 
    status === 'green' ? theme.palette.success.contrastText :
    status === 'yellow' ? theme.palette.warning.contrastText :
    theme.palette.error.contrastText,
}));

const TestHistory: React.FC = () => {
  const [tests, setTests] = useState<ExtendedVarroaTest[]>([]);
  const [selectedTest, setSelectedTest] = useState<ExtendedVarroaTest | null>(null);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [testToDelete, setTestToDelete] = useState<string | null>(null);
  const [showSnackbar, setShowSnackbar] = useState(false);
  const [snackbarMessage, setSnackbarMessage] = useState('');
  const [snackbarSeverity, setSnackbarSeverity] = useState<'success' | 'error'>('success');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const { currentUser } = useAuth();

  useEffect(() => {
    const processTestData = async () => {
      if (!currentUser) return;

      try {
        const fetchedTests = await getUserTests(currentUser.uid);
        
        // Convertir todas las fechas a timestamps para comparar
        const sortedTests = fetchedTests.sort((a, b) => {
          const dateA = getDateFromField(a.monitoringHistory?.[0]?.date ? new Date(a.monitoringHistory[0].date) : a.evaluationDate);
          const dateB = getDateFromField(b.monitoringHistory?.[0]?.date ? new Date(b.monitoringHistory[0].date) : b.evaluationDate);
          
          console.log('Comparing dates:', {
            a: {
              original: a.monitoringHistory?.[0]?.date || a.evaluationDate,
              converted: dateA,
              timestamp: dateA.getTime()
            },
            b: {
              original: b.monitoringHistory?.[0]?.date || b.evaluationDate,
              converted: dateB,
              timestamp: dateB.getTime()
            }
          });
          
          return dateB.getTime() - dateA.getTime();
        });

        console.log('Sorted tests:', sortedTests.map(test => ({
          date: test.monitoringHistory?.[0]?.date || test.evaluationDate,
          timestamp: getDateFromField(test.monitoringHistory?.[0]?.date ? new Date(test.monitoringHistory[0].date) : test.evaluationDate).getTime()
        })));

        setTests(sortedTests);
        setError(null);
      } catch (error) {
        console.error('Error loading tests:', error);
        setSnackbarMessage('Error loading tests');
        setSnackbarSeverity('error');
        setShowSnackbar(true);
        setError('Error loading tests');
      } finally {
        setLoading(false);
      }
    };

    processTestData();
  }, [currentUser]);

  const formatDate = (date: Date | Timestamp | string | null | undefined) => {
    if (!date) {
      console.log('Date is null or undefined');
      return 'N/A';
    }
    
    try {
      console.log('Raw date value:', date);
      console.log('Type of date:', typeof date);

      let dateObj: Date;
      
      if (date instanceof Timestamp) {
        console.log('Date is Timestamp instance');
        dateObj = date.toDate();
      } else if (typeof date === 'string') {
        console.log('Date is string');
        dateObj = new Date(date);
      } else if (date instanceof Date) {
        console.log('Date is Date instance');
        dateObj = date;
      } else {
        console.error('Unsupported date type:', date);
        return 'Invalid date';
      }

      if (isNaN(dateObj.getTime())) {
        console.error('Invalid date value:', date);
        return 'Invalid date';
      }
      
      const formattedDate = format(dateObj, 'dd/MM/yyyy', { locale: es });
      console.log('Formatted date:', formattedDate);
      return formattedDate;
    } catch (error) {
      console.error('Error formatting date:', error, 'Date value:', date);
      return 'Invalid date';
    }
  };

  const getDateFromField = (dateField: Date | Timestamp): Date => {
    if (dateField instanceof Date) return dateField;
    if (dateField instanceof Timestamp) return dateField.toDate();
    return new Date();
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case 'green': return 'Low Infestation';
      case 'yellow': return 'Medium Infestation';
      case 'red': return 'High Infestation';
      default: return 'Not Specified';
    }
  };

  const calculateSeasonalStats = (testData: Array<ExtendedVarroaTest>) => {
    const seasons = ['Spring', 'Summer', 'Autumn', 'Winter'];
    return seasons.map(season => {
      const seasonTests = testData.filter(test => {
        try {
          let dateObj: Date;
          const date = test.evaluationDate;
          
          if (!date) return false;

          if (date instanceof Date) {
            dateObj = date;
          } else if (date instanceof Timestamp) {
            dateObj = date.toDate();
          } else if (typeof date === 'string') {
            dateObj = new Date(date);
          } else {
            return false;
          }

          // Verificar si la fecha es válida
          if (isNaN(dateObj.getTime())) {
            return false;
          }

          const month = dateObj.getMonth();
          switch(season) {
            case 'Spring': return month >= 2 && month <= 4;
            case 'Summer': return month >= 5 && month <= 7;
            case 'Autumn': return month >= 8 && month <= 10;
            case 'Winter': return month >= 11 || month <= 1;
            default: return false;
          }
        } catch (error) {
          console.error('Error processing date:', error);
          return false;
        }
      });
      
      const avgInfestation = seasonTests.reduce((acc, test) => 
        acc + (test.infestationRate || 0), 0) / (seasonTests.length || 1);
      
      return {
        name: season,
        infestationRate: avgInfestation,
        testCount: seasonTests.length
      };
    });
  };

  const calculateTreatmentEffectiveness = (testData: Array<ExtendedVarroaTest>) => {
    const treatments = new Map();
    testData.forEach(test => {
      if (test.treatmentApplied && test.treatmentEffectiveness !== undefined) {
        const current = treatments.get(test.treatmentApplied) || { total: 0, count: 0 };
        current.total += test.treatmentEffectiveness;
        current.count += 1;
        treatments.set(test.treatmentApplied, current);
      }
    });

    return Array.from(treatments.entries()).map(([name, data]: [string, any]) => ({
      name,
      effectiveness: (data.total / data.count).toFixed(1)
    }));
  };

  // Función auxiliar para manejar datos de predicción
  const getPredictionData = (test: ExtendedVarroaTest) => {
    const dateObj = getDateFromField(test.evaluationDate);
    return {
      date: formatDate(test.evaluationDate),
      effectiveness: test.treatmentEffectiveness ?? 0,
      treatment: test.treatmentApplied || 'No treatment',
      timestamp: dateObj.getTime()
    };
  };

  // Función auxiliar para obtener datos de proyección
  const getProjectedData = (test: ExtendedVarroaTest, index: number) => {
    return {
      date: test.treatmentPrediction?.projectedDates[index] ?? new Date().toISOString(),
      actual: index === 0 ? test.infestationRate : null,
      predicted: test.treatmentPrediction?.projectedInfestationRates[index] ?? 0
    };
  };

  const handleDeleteTest = async (testId: string) => {
    if (!currentUser) return;
    
    try {
      await deleteTest(currentUser.uid, testId);
      setTests(tests.filter(test => test.id !== testId));
      setSnackbarMessage('Test deleted successfully');
      setSnackbarSeverity('success');
      setShowSnackbar(true);
    } catch (error) {
      console.error('Error deleting test:', error);
      setSnackbarMessage('Error deleting test');
      setSnackbarSeverity('error');
      setShowSnackbar(true);
    }
  };

  // Función para preparar datos de infestación estacional
  const getInfestationData = (tests: ExtendedVarroaTest[]) => {
    return [...tests]
      .sort((a, b) => {
        const dateA = getDateFromField(a.evaluationDate);
        const dateB = getDateFromField(b.evaluationDate);
        return dateA.getTime() - dateB.getTime();
      })
      .map(test => ({
        date: formatDate(test.evaluationDate),
        rate: test.infestationRate,
        status: test.status
      }));
  };

  // Función para preparar datos de evolución de infestación
  const getInfestationEvolutionData = (tests: ExtendedVarroaTest[]) => {
    return [...tests]
      .sort((a, b) => {
        const dateA = getDateFromField(a.evaluationDate);
        const dateB = getDateFromField(b.evaluationDate);
        return dateA.getTime() - dateB.getTime();
      })
      .map(test => ({
        date: formatDate(test.evaluationDate),
        rate: test.infestationRate,
        status: test.status
      }));
  };

  // Función para obtener distribución de métodos
  const getMethodDistributionData = (tests: ExtendedVarroaTest[]) => {
    const methodCounts = tests.reduce((acc: { [key: string]: number }, test) => {
      const method = test.method || 'Not specified';
      acc[method] = (acc[method] || 0) + 1;
      return acc;
    }, {});

    return Object.entries(methodCounts).map(([method, count]) => ({
      method,
      count
    }));
  };

  // Función para obtener distribución de estados
  const getStatusDistributionData = (tests: ExtendedVarroaTest[]) => {
    const statusCounts = tests.reduce((acc: { [key: string]: number }, test) => {
      const status = test.status || 'Not specified';
      acc[status] = (acc[status] || 0) + 1;
      return acc;
    }, {});

    return Object.entries(statusCounts).map(([status, count]) => ({
      status: getStatusText(status),
      count
    }));
  };

  // Función para calcular promedios mensuales
  const getMonthlyAverages = (tests: ExtendedVarroaTest[]) => {
    const monthlyData: { [key: string]: { sum: number; count: number } } = {};
    const monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 
                       'July', 'August', 'September', 'October', 'November', 'December'];

    tests.forEach(test => {
      const date = getDateFromField(test.evaluationDate);
      const monthKey = monthNames[date.getMonth()];
      
      if (!monthlyData[monthKey]) {
        monthlyData[monthKey] = { sum: 0, count: 0 };
      }
      
      monthlyData[monthKey].sum += test.infestationRate || 0;
      monthlyData[monthKey].count += 1;
    });

    return monthNames
      .filter(month => monthlyData[month])
      .map(month => ({
        month,
        average: monthlyData[month].sum / monthlyData[month].count,
        tests: monthlyData[month].count
      }));
  };

  if (loading) {
    return (
      <Box display="flex" justifyContent="center" alignItems="center" minHeight="200px">
        <LinearProgress />
      </Box>
    );
  }

  if (error) {
    return (
      <Box m={2}>
        <Alert severity="error">{error}</Alert>
      </Box>
    );
  }

  if (tests.length === 0) {
    return (
      <Box m={2}>
        <Alert severity="info">No tests have been recorded yet.</Alert>
      </Box>
    );
  }

  const infestationData = getInfestationData(tests);
  const treatmentEffectivenessData = [...tests]
    .sort((a, b) => {
      const dateA = getDateFromField(a.evaluationDate);
      const dateB = getDateFromField(b.evaluationDate);
      return dateA.getTime() - dateB.getTime();
    })
    .filter(test => test.treatmentEffectiveness !== undefined)
    .map(getPredictionData)
    .sort((a, b) => a.timestamp - b.timestamp);

  return (
    <Box sx={{ width: '100%', p: 2 }}>
      <Typography variant="h4" gutterBottom>
        Test History
      </Typography>

      {/* Tabla de tests */}
      <TableContainer component={Paper} sx={{ mb: 4 }}>
        <Table>
          <TableHead>
            <TableRow>
              <TableCell>Evaluation Date</TableCell>
              <TableCell>Report Date</TableCell>
              <TableCell>Reference</TableCell>
              <TableCell>Method</TableCell>
              <TableCell>Infestation Rate</TableCell>
              <TableCell>Status</TableCell>
              <TableCell>Treatment</TableCell>
              <TableCell>Actions</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {tests.map((test) => (
              <TableRow key={test.id} hover>
                <TableCell>
                  {test.monitoringHistory && test.monitoringHistory.length > 0 && test.monitoringHistory[0].date
                    ? formatDate(test.monitoringHistory[0].date)
                    : formatDate(test.evaluationDate)}
                </TableCell>
                <TableCell>
                  {formatDate(test.reportGeneratedDate)}
                </TableCell>
                <TableCell>{test.reference || 'No reference'}</TableCell>
                <TableCell>{test.method || 'Not specified'}</TableCell>
                <TableCell>{(test.infestationRate || 0).toFixed(1)}%</TableCell>
                <TableCell>
                  <StatusChip
                    label={getStatusText(test.status)}
                    status={test.status}
                    size="small"
                  />
                </TableCell>
                <TableCell>{test.treatmentApplied || 'No treatment'}</TableCell>
                <TableCell>
                  <IconButton 
                    size="small" 
                    color="primary" 
                    onClick={() => setSelectedTest(test)}
                  >
                    <InfoIcon />
                  </IconButton>
                  <IconButton 
                    size="small" 
                    color="error"
                    onClick={() => handleDeleteTest(test.id)}
                  >
                    <DeleteIcon />
                  </IconButton>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>

      {/* Gráficas */}
      <Grid container spacing={3} sx={{ mt: 4 }}>
        {/* Promedios Mensuales */}
        <Grid item xs={12} md={6}>
          <Paper sx={{ p: 2 }}>
            <Typography variant="h6" gutterBottom>
              Monthly Average Infestation Rates
            </Typography>
            <ResponsiveContainer width="100%" height={300}>
              <ComposedChart data={getMonthlyAverages(tests)}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="month" />
                <YAxis yAxisId="left" label={{ value: 'Infestation Rate (%)', angle: -90, position: 'insideLeft' }} />
                <YAxis yAxisId="right" orientation="right" label={{ value: 'Number of Tests', angle: 90, position: 'insideRight' }} />
                <Tooltip />
                <Legend />
                <Bar yAxisId="right" dataKey="tests" fill="#82ca9d" name="Number of Tests" />
                <Line yAxisId="left" type="monotone" dataKey="average" stroke="#8884d8" name="Average Infestation Rate" />
              </ComposedChart>
            </ResponsiveContainer>
          </Paper>
        </Grid>

        {/* Evolución de la Tasa de Infestación */}
        <Grid item xs={12} md={6}>
          <Paper sx={{ p: 2 }}>
            <Typography variant="h6" gutterBottom>
              Infestation Rate Evolution
            </Typography>
            <ResponsiveContainer width="100%" height={300}>
              <ComposedChart data={getInfestationEvolutionData(tests)}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="date" />
                <YAxis />
                <Tooltip />
                <Legend />
                <Line type="monotone" dataKey="rate" name="Infestation Rate (%)" stroke="#8884d8" />
                <Bar dataKey="rate" name="Infestation Rate (%)" fill="#8884d8" opacity={0.3} />
              </ComposedChart>
            </ResponsiveContainer>
          </Paper>
        </Grid>

        {/* Distribución por Métodos */}
        <Grid item xs={12} md={6}>
          <Paper sx={{ p: 2 }}>
            <Typography variant="h6" gutterBottom>
              Sampling Methods Distribution
            </Typography>
            <ResponsiveContainer width="100%" height={300}>
              <PieChart>
                <Pie
                  data={getMethodDistributionData(tests)}
                  dataKey="count"
                  nameKey="method"
                  cx="50%"
                  cy="50%"
                  outerRadius={100}
                  fill="#8884d8"
                  label
                >
                  {getMethodDistributionData(tests).map((entry, index) => (
                    <Cell key={`cell-${index}`} fill="#8884d8" />
                  ))}
                </Pie>
                <Tooltip />
                <Legend />
              </PieChart>
            </ResponsiveContainer>
          </Paper>
        </Grid>

        {/* Estado de las Colmenas */}
        <Grid item xs={12} md={6}>
          <Paper sx={{ p: 2 }}>
            <Typography variant="h6" gutterBottom>
              Hive Status Distribution
            </Typography>
            <ResponsiveContainer width="100%" height={300}>
              <PieChart>
                <Pie
                  data={getStatusDistributionData(tests)}
                  dataKey="count"
                  nameKey="status"
                  cx="50%"
                  cy="50%"
                  outerRadius={100}
                  fill="#8884d8"
                  label
                >
                  {getStatusDistributionData(tests).map((entry, index) => (
                    <Cell 
                      key={`cell-${index}`} 
                      fill={entry.status.includes('Low') ? '#4caf50' : 
                            entry.status.includes('Medium') ? '#ff9800' : 
                            entry.status.includes('High') ? '#f44336' : 
                            '#9e9e9e'}
                    />
                  ))}
                </Pie>
                <Tooltip />
                <Legend />
              </PieChart>
            </ResponsiveContainer>
          </Paper>
        </Grid>
      </Grid>

      {/* Modal de detalles */}
      <Dialog
        open={Boolean(selectedTest)}
        onClose={() => setSelectedTest(null)}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>
          Test Details - {selectedTest && formatDate(selectedTest.evaluationDate)}
        </DialogTitle>
        <DialogContent>
          {selectedTest && (
            <Grid container spacing={3}>
              {/* Información básica */}
              <Grid item xs={12}>
                <Typography variant="h6" gutterBottom sx={{ borderBottom: 1, borderColor: 'divider', pb: 1 }}>
                  Basic Information
                </Typography>
                <Grid container spacing={2}>
                  <Grid item xs={12} sm={6}>
                    <Typography variant="subtitle2" color="textSecondary">Evaluation Date</Typography>
                    <Typography variant="body1">{formatDate(selectedTest.evaluationDate)}</Typography>
                  </Grid>
                  <Grid item xs={12} sm={6}>
                    <Typography variant="subtitle2" color="textSecondary">Report Date</Typography>
                    <Typography variant="body1">{formatDate(selectedTest.reportGeneratedDate)}</Typography>
                  </Grid>
                  <Grid item xs={12} sm={6}>
                    <Typography variant="subtitle2" color="textSecondary">Reference</Typography>
                    <Typography variant="body1">{selectedTest.reference || 'No reference'}</Typography>
                  </Grid>
                  <Grid item xs={12} sm={6}>
                    <Typography variant="subtitle2" color="textSecondary">Method</Typography>
                    <Typography variant="body1">{selectedTest.method || 'Not specified'}</Typography>
                  </Grid>
                </Grid>
              </Grid>

              {/* Resultados del test con gráficos */}
              <Grid item xs={12}>
                <Typography variant="h6" gutterBottom sx={{ borderBottom: 1, borderColor: 'divider', pb: 1 }}>
                  Test Results
                </Typography>
                <Grid container spacing={2}>
                  {/* Información textual */}
                  <Grid item xs={12} md={4}>
                    <Grid container spacing={2}>
                      <Grid item xs={12}>
                        <Typography variant="subtitle2" color="textSecondary">Sample Size</Typography>
                        <Typography variant="body1">{selectedTest.sampleSize} bees</Typography>
                      </Grid>
                      <Grid item xs={12}>
                        <Typography variant="subtitle2" color="textSecondary">Mite Count</Typography>
                        <Typography variant="body1">{selectedTest.miteCount} mites</Typography>
                      </Grid>
                      <Grid item xs={12}>
                        <Typography variant="subtitle2" color="textSecondary">Status</Typography>
                        <Chip
                          label={getStatusText(selectedTest.status)}
                          color={selectedTest.status === 'green' ? 'success' : 
                                 selectedTest.status === 'yellow' ? 'warning' : 
                                 selectedTest.status === 'red' ? 'error' : 'default'}
                          sx={{ mt: 1 }}
                        />
                      </Grid>
                    </Grid>
                  </Grid>

                  {/* Gráfico circular de proporción abejas/ácaros */}
                  <Grid item xs={12} md={4}>
                    <Box sx={{ position: 'relative', width: '100%', height: 200 }}>
                      <ResponsiveContainer>
                        <PieChart>
                          <Pie
                            data={[
                              { name: 'Healthy Bees', value: selectedTest.sampleSize - selectedTest.miteCount },
                              { name: 'Infested Bees', value: selectedTest.miteCount }
                            ]}
                            cx="50%"
                            cy="50%"
                            innerRadius={60}
                            outerRadius={80}
                            paddingAngle={5}
                            dataKey="value"
                          >
                            <Cell fill="#4caf50" />
                            <Cell fill="#f44336" />
                          </Pie>
                          <Tooltip />
                          <Legend />
                        </PieChart>
                      </ResponsiveContainer>
                    </Box>
                  </Grid>

                  {/* Medidor de infestación */}
                  <Grid item xs={12} md={4}>
                    <Box sx={{ position: 'relative', width: '100%', height: 200 }}>
                      <ResponsiveContainer>
                        <AreaChart
                          data={[
                            { value: 0 },
                            { value: selectedTest.infestationRate }
                          ]}
                          margin={{ top: 10, right: 30, left: 0, bottom: 0 }}
                        >
                          <defs>
                            <linearGradient id="colorValue" x1="0" y1="0" x2="0" y2="1">
                              <stop 
                                offset="5%" 
                                stopColor={
                                  selectedTest.status === 'green' ? '#4caf50' : 
                                  selectedTest.status === 'yellow' ? '#ff9800' : '#f44336'
                                } 
                                stopOpacity={0.8}
                              />
                              <stop 
                                offset="95%" 
                                stopColor={
                                  selectedTest.status === 'green' ? '#4caf50' : 
                                  selectedTest.status === 'yellow' ? '#ff9800' : '#f44336'
                                } 
                                stopOpacity={0}
                              />
                            </linearGradient>
                          </defs>
                          <YAxis 
                            domain={[0, 15]} 
                            ticks={[0, 3, 6, 9, 12, 15]}
                          />
                          <Area 
                            type="monotone" 
                            dataKey="value" 
                            stroke={
                              selectedTest.status === 'green' ? '#4caf50' : 
                              selectedTest.status === 'yellow' ? '#ff9800' : '#f44336'
                            }
                            fillOpacity={1}
                            fill="url(#colorValue)"
                          />
                          <text
                            x="50%"
                            y="45%"
                            textAnchor="middle"
                            dominantBaseline="middle"
                            style={{
                              fontSize: '24px',
                              fontWeight: 'bold',
                              fill: selectedTest.status === 'green' ? '#4caf50' : 
                                    selectedTest.status === 'yellow' ? '#ff9800' : '#f44336'
                            }}
                          >
                            {`${selectedTest.infestationRate.toFixed(1)}%`}
                          </text>
                        </AreaChart>
                      </ResponsiveContainer>
                    </Box>
                  </Grid>
                </Grid>
              </Grid>

              {/* Información del tratamiento con visualización */}
              {selectedTest.treatmentApplied && (
                <Grid item xs={12}>
                  <Typography variant="h6" gutterBottom sx={{ borderBottom: 1, borderColor: 'divider', pb: 1 }}>
                    Treatment Information
                  </Typography>
                  <Grid container spacing={2}>
                    <Grid item xs={12} md={6}>
                      <Paper sx={{ p: 2 }}>
                        <Typography variant="subtitle2" color="textSecondary">Treatment Applied</Typography>
                        <Typography variant="h6" sx={{ mt: 1 }}>{selectedTest.treatmentApplied}</Typography>
                        
                        {selectedTest.treatmentEffectiveness !== undefined && (
                          <Box sx={{ mt: 3 }}>
                            <Typography variant="subtitle2" color="textSecondary">
                              Treatment Effectiveness
                            </Typography>
                            <Box sx={{ mt: 2 }}>
                              <Box sx={{ display: 'flex', alignItems: 'center' }}>
                                <Box sx={{ width: '100%', mr: 1 }}>
                                  <LinearProgress
                                    variant="determinate"
                                    value={selectedTest.treatmentEffectiveness}
                                    sx={{
                                      height: 10,
                                      borderRadius: 5,
                                      bgcolor: 'grey.200',
                                      '& .MuiLinearProgress-bar': {
                                        borderRadius: 5,
                                        bgcolor: selectedTest.treatmentEffectiveness >= 75 ? '#4caf50' :
                                                selectedTest.treatmentEffectiveness >= 50 ? '#ff9800' :
                                                '#f44336'
                                      }
                                    }}
                                  />
                                </Box>
                                <Box sx={{ minWidth: 35 }}>
                                  <Typography variant="body2" color="text.secondary">
                                    {`${selectedTest.treatmentEffectiveness.toFixed(1)}%`}
                                  </Typography>
                                </Box>
                              </Box>
                            </Box>
                          </Box>
                        )}
                      </Paper>
                    </Grid>
                    <Grid item xs={12} md={6}>
                      <Paper sx={{ p: 2, height: '100%', display: 'flex', flexDirection: 'column' }}>
                        <Typography variant="subtitle2" color="textSecondary" gutterBottom>
                          Treatment Details
                        </Typography>
                        <Box sx={{ flexGrow: 1, display: 'flex', flexDirection: 'column', justifyContent: 'space-around' }}>
                          <Box>
                            <Typography color="textSecondary" variant="body2">Application Date</Typography>
                            <Typography variant="body1">{formatDate(selectedTest.evaluationDate)}</Typography>
                          </Box>
                          <Box>
                            <Typography color="textSecondary" variant="body2">Initial Infestation</Typography>
                            <Typography variant="body1">{selectedTest.infestationRate.toFixed(1)}%</Typography>
                          </Box>
                          {selectedTest.treatmentEffectiveness && (
                            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                              <Typography color="textSecondary" variant="body2">Effectiveness Level:</Typography>
                              <Chip 
                                label={
                                  selectedTest.treatmentEffectiveness >= 75 ? 'High' :
                                  selectedTest.treatmentEffectiveness >= 50 ? 'Medium' : 'Low'
                                }
                                color={
                                  selectedTest.treatmentEffectiveness >= 75 ? 'success' :
                                  selectedTest.treatmentEffectiveness >= 50 ? 'warning' : 'error'
                                }
                                size="small"
                              />
                            </Box>
                          )}
                        </Box>
                      </Paper>
                    </Grid>
                  </Grid>
                </Grid>
              )}
            </Grid>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setSelectedTest(null)}>Close</Button>
        </DialogActions>
      </Dialog>

      <Snackbar
        open={showSnackbar}
        autoHideDuration={6000}
        onClose={() => setShowSnackbar(false)}
      >
        <Alert 
          onClose={() => setShowSnackbar(false)} 
          severity={snackbarSeverity}
        >
          {snackbarMessage}
        </Alert>
      </Snackbar>
    </Box>
  );
};

export default TestHistory;
