import React, { useState } from 'react';
import {
  Box,
  Card,
  CardContent,
  CardMedia,
  Typography,
  Chip,
  Grid,
  Divider,
  IconButton,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Container,
  CardActions,
} from '@mui/material';
import { styled } from '@mui/material/styles';
import VisibilityIcon from '@mui/icons-material/Visibility';

// Mock de datos de noticias (esto vendría del backend)
const newsData = [
  {
    id: 1,
    title: "Neonicotinoids and Varroa: A Double Threat to Honey Bee Colonies",
    date: '2024-01-20',
    image: '/images/beelife-mission.jpg',
    summary: 'Groundbreaking research reveals that neonicotinoid pesticides significantly increase Varroa mite infestations in honey bee colonies, creating a compound threat to bee health.',
    category: 'Research',
    content: `A groundbreaking study conducted by researchers from the University of Georgia, University of Delaware, and Auburn University has uncovered a disturbing connection between neonicotinoid pesticides and increased Varroa mite infestations in honey bee colonies. This research, published in the Journal of Insect Science, represents the first field-based evidence of how neonicotinoids can exacerbate parasitic pressures on honey bee colonies.

Key Research Findings:
• Colonies exposed to neonicotinoids showed an average of 5.3 more mites dropping in 24 hours compared to non-exposed colonies
• Mite wash counts were consistently higher in exposed colonies
• The study found no protective effect from increased genetic diversity in colonies
• Evidence suggests potential immunosuppression effects making bees more susceptible to mite infestations

Methodology:
The researchers established three outdoor apiary sites across Georgia, Delaware, and Alabama, each containing 24 experimental colonies. The study employed controlled feeding experiments where colonies were provided with either clean pollen patties or those containing measured doses of clothianidin or thiamethoxam insecticides.

Implications for Beekeeping:
This research has significant implications for both commercial and hobbyist beekeepers:
1. The need for more frequent Varroa monitoring in areas with high pesticide exposure
2. Potential revision of treatment thresholds in affected areas
3. Importance of communication with local farmers about pesticide applications
4. Development of new integrated pest management strategies

Future Research Directions:
The research team is now investigating:
• Molecular mechanisms behind the increased susceptibility to mites
• Potential protective measures for colonies in high-risk areas
• Long-term effects on colony survival and productivity
• Alternative pest management strategies for agricultural crops

The findings emphasize the urgent need for a more holistic approach to both pest management in agriculture and Varroa control in apiculture.`
  },
  {
    id: 2,
    title: "Dramatic Surge in Varroa Infestations: Spanish Study Reveals Critical Patterns",
    date: '2024-01-15',
    image: '/images/1.jpg',
    summary: 'Recent clinical study in northern Spanish apiaries documents unprecedented increase in Varroa infestation levels, challenging current monitoring practices.',
    category: 'Field Research',
    content: `A comprehensive clinical study conducted in northern Spanish apiaries has revealed alarming patterns in Varroa mite population dynamics. The research, spanning August and September 2024, documented a dramatic tenfold increase in infestation levels over just two months, challenging current understanding of mite population growth rates.

Detailed Findings:
1. Infestation Dynamics:
   • Initial CBPI (Corrected Bee Parasitization Index) levels were within acceptable ranges
   • Rapid escalation to severe infestation levels within 60 days
   • Strong correlation between colony conditions and infestation rates
   • Significant impact of bee-to-brood ratio on mite population growth

2. Monitoring Methodology:
   • Regular sampling of 20% of colonies (8 hives per 40-hive group)
   • Measurement of adult bee population using frame coverage
   • Brood frame counting and assessment
   • CO₂ testing on 300-bee samples for accurate mite counts

3. Environmental Factors:
   • Temperature and humidity correlations
   • Impact of local flora and farming practices
   • Seasonal variations in colony development
   • Regional climate patterns affecting mite reproduction

Critical Implications:
The study highlights several crucial aspects for beekeeping practices:
• Traditional monitoring intervals may be insufficient
• Need for adaptive treatment thresholds based on colony conditions
• Importance of considering multiple factors in infestation assessment
• Limitations of current predictive models

Recommendations for Beekeepers:
Based on the findings, the researchers recommend:
1. Increased monitoring frequency during critical periods
2. Implementation of comprehensive sampling protocols
3. Integration of multiple assessment methods
4. Development of region-specific management strategies

The study emphasizes that successful Varroa management requires a more dynamic and context-aware approach than previously thought.`
  },
  {
    id: 3,
    title: 'Revolutionary AI System Transforms Early Varroa Detection',
    date: '2024-01-18',
    image: '/images/2.jpg',
    summary: 'Innovative AI-powered monitoring system achieves breakthrough in early Varroa detection, combining multiple sensor types with machine learning algorithms.',
    category: 'Technology',
    content: `A revolutionary advancement in beekeeping technology has emerged with the development of an AI-powered early warning system for Varroa mite detection. This sophisticated system combines multiple sensor types with advanced machine learning algorithms to provide unprecedented accuracy in early infestation detection.

Technical Specifications:

1. Sensor Array Integration:
   • Thermal imaging cameras for bee activity monitoring
   • Acoustic sensors for behavior pattern analysis
   • Chemical sensors for pheromone detection
   • Weight sensors for population dynamics tracking
   • Visual monitoring with high-resolution cameras

2. AI Implementation:
   • Deep learning algorithms for pattern recognition
   • Real-time data processing capabilities
   • Adaptive learning from historical data
   • Multi-parameter analysis for accurate predictions
   • Cloud-based processing for complex calculations

Performance Metrics:
• 95% accuracy in early detection
• False positive rate below 2%
• Detection capability 2-3 weeks earlier than traditional methods
• Continuous 24/7 monitoring capability
• Real-time alerts via mobile application

Field Testing Results:
The system has undergone extensive testing across various environmental conditions:
1. Spring Testing (March-May 2024):
   • 150 colonies monitored
   • 98% successful early detection rate
   • Average detection 18 days before visible signs

2. Summer Testing (June-August 2024):
   • 200 colonies across different regions
   • 93% accuracy in high-temperature conditions
   • Successful integration with existing hive management systems

3. Autumn Testing (September-November 2024):
   • 175 colonies in varying weather conditions
   • 94% accuracy in predicting winter survival rates
   • Effective monitoring during preparation for winter

Implementation Benefits:
• Reduced colony losses through early intervention
• Lower treatment costs through targeted applications
• Improved winter survival rates
• Better understanding of colony dynamics
• Enhanced research capabilities

Future Development:
The research team is currently working on:
1. Enhanced prediction models for different climatic zones
2. Integration with automated treatment systems
3. Expanded monitoring capabilities for other health issues
4. Development of cost-effective versions for smaller apiaries

This technology represents a significant leap forward in Varroa management capabilities, offering beekeepers unprecedented insight into colony health and mite population dynamics.`
  },
  {
    id: 4,
    title: 'Climate Change Reshapes Varroa Management Strategies in Europe',
    date: '2024-01-12',
    image: '/images/3.jpg',
    summary: 'Extensive European study reveals significant impacts of climate change on Varroa mite behavior and treatment efficacy, forcing adaptation in management practices.',
    category: 'Environmental Research',
    content: `A comprehensive three-year study across multiple European regions has revealed profound changes in Varroa mite dynamics due to climate change, necessitating significant adaptations in beekeeping practices. The research, involving over 1,000 colonies across 12 countries, provides detailed insights into the changing patterns of mite behavior and colony interactions.

Climate Impact Analysis:

1. Temperature Effects:
   • Extended breeding seasons for both bees and mites
   • Altered timing of traditional treatment windows
   • Changes in mite reproduction rates
   • Impact on treatment efficacy at different temperatures

2. Precipitation Patterns:
   • Influence on colony humidity levels
   • Effects on treatment application timing
   • Changes in foraging patterns affecting colony strength
   • Impact on natural mite control mechanisms

3. Seasonal Shifts:
   • Earlier spring build-up of colonies
   • Extended autumn activity periods
   • Reduced winter mortality of mites
   • Changes in brood cycle timing

Key Research Findings:

1. Colony Development:
   • 25% longer breeding season in southern regions
   • 15-20% increase in mite reproduction cycles
   • Significant changes in swarming patterns
   • Altered drone production timing

2. Treatment Efficacy:
   • Reduced effectiveness of temperature-dependent treatments
   • Need for adjusted application timing
   • Impact on organic acid treatment protocols
   • Changes in treatment threshold levels

3. Economic Impact:
   • 20-30% increase in treatment frequency
   • Higher monitoring costs
   • Increased labor requirements
   • Additional equipment needs

Adaptation Strategies:

1. Modified Treatment Protocols:
   • Season-specific treatment timing
   • Alternative treatment combinations
   • Adjusted application methods
   • Enhanced monitoring systems

2. Colony Management:
   • Adapted feeding schedules
   • Modified queen rearing timing
   • Adjusted migration patterns
   • Enhanced ventilation systems

3. Research Initiatives:
   • Development of climate-resilient bee stocks
   • Testing of new treatment methods
   • Monitoring of regional adaptations
   • Collection of long-term data

Recommendations for Beekeepers:

1. Immediate Actions:
   • Increase monitoring frequency
   • Adjust treatment timing
   • Enhance ventilation systems
   • Modify feeding practices

2. Long-term Strategies:
   • Invest in climate-resistant equipment
   • Develop local breeding programs
   • Establish regional cooperation networks
   • Implement comprehensive data collection

This research underscores the urgent need for adaptive management strategies in modern beekeeping, highlighting the complex interactions between climate change and Varroa control.`
  }
];

// Hero section styles
const HeroSection = styled(Box)(({ theme }) => ({
  position: 'relative',
  color: 'white',
  minHeight: '10vh',
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  textAlign: 'center',
  overflow: 'hidden',
  marginTop: '0',
  marginBottom: theme.spacing(4),
  padding: theme.spacing(4, 0),
  '&::before': {
    content: '""',
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    background: `linear-gradient(45deg, ${theme.palette.primary.main}dd 30%, ${theme.palette.secondary.main}dd 90%)`,
    zIndex: 1
  }
}));

const HeroContent = styled(Box)({
  position: 'relative',
  zIndex: 2,
  width: '100%',
  padding: '10px'
});

const News = () => {
  const [selectedNews, setSelectedNews] = useState<typeof newsData[0] | null>(null);
  const [open, setOpen] = useState(false);

  const handleClose = () => {
    setOpen(false);
  };

  const handleOpen = (news: typeof newsData[0]) => {
    setSelectedNews(news);
    setOpen(true);
  };

  return (
    <Box sx={{ width: '100%', margin: 0, padding: 0 }}>
      {/* Hero Section */}
      <HeroSection>
        <HeroContent>
          <Container maxWidth="lg">
            <Typography variant="h3" component="h1" gutterBottom>
              Latest News
            </Typography>
            <Typography variant="h6" sx={{ mb: 2 }}>
              Stay updated with the latest research and developments in beekeeping
            </Typography>
          </Container>
        </HeroContent>
      </HeroSection>

      {/* Main Content */}
      <Container maxWidth="lg">
        <Box sx={{ mt: 4, pb: 8 }}>
          <Typography variant="h4" gutterBottom sx={{ mb: 4 }}>
            Latest News
          </Typography>

          <Grid container spacing={3}>
            {newsData.map((news, index) => (
              <Grid item xs={12} key={news.id}>
                <Card 
                  sx={{ 
                    display: 'flex',
                    mb: 2,
                    height: 160,
                    '&:hover': {
                      boxShadow: 6,
                    },
                  }}
                >
                  <Box sx={{ 
                    width: 200,
                    height: 160,
                    minWidth: 200,
                    position: 'relative',
                    overflow: 'hidden'
                  }}>
                    <CardMedia
                      component="img"
                      sx={{ 
                        width: '100%',
                        height: '100%',
                        objectFit: 'cover',
                        objectPosition: 'center'
                      }}
                      image={news.image}
                      alt={news.title}
                    />
                  </Box>
                  <Box sx={{ display: 'flex', flexDirection: 'column', width: '100%' }}>
                    <CardContent sx={{ flex: '1 0 auto' }}>
                      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1 }}>
                        <Box sx={{ display: 'flex', alignItems: 'center' }}>
                          <Chip 
                            label={news.category}
                            size="small"
                            color="primary"
                            sx={{ mr: 1 }}
                          />
                          <Typography variant="caption" color="text.secondary">
                            {new Date(news.date).toLocaleDateString('es-ES', {
                              year: 'numeric',
                              month: 'long',
                              day: 'numeric'
                            })}
                          </Typography>
                        </Box>
                        <IconButton 
                          onClick={() => handleOpen(news)}
                          color="primary"
                          size="small"
                          title="Ver noticia completa"
                        >
                          <VisibilityIcon />
                        </IconButton>
                      </Box>
                      
                      <Typography component="h5" variant="h6">
                        {news.title}
                      </Typography>
                      
                      <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
                        {news.summary}
                      </Typography>
                    </CardContent>
                  </Box>
                </Card>
                {index < newsData.length - 1 && (
                  <Divider sx={{ my: 2 }} />
                )}
              </Grid>
            ))}
          </Grid>
        </Box>
      </Container>

      {/* Dialog */}
      <Dialog
        open={open}
        onClose={handleClose}
        maxWidth="md"
        fullWidth
        scroll="paper"
      >
        {selectedNews && (
          <>
            <DialogTitle>
              <Typography variant="h5" component="div">
                {selectedNews.title}
              </Typography>
              <Box sx={{ display: 'flex', alignItems: 'center', mt: 1 }}>
                <Chip 
                  label={selectedNews.category}
                  size="small"
                  color="primary"
                  sx={{ mr: 1 }}
                />
                <Typography variant="caption" color="text.secondary">
                  {new Date(selectedNews.date).toLocaleDateString('es-ES', {
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric'
                  })}
                </Typography>
              </Box>
            </DialogTitle>
            <DialogContent dividers>
              <Box sx={{ mb: 2 }}>
                <img
                  src={selectedNews.image}
                  alt={selectedNews.title}
                  style={{ width: '100%', maxHeight: '300px', objectFit: 'cover' }}
                />
              </Box>
              <Typography variant="body1" component="div" sx={{ whiteSpace: 'pre-line' }}>
                {selectedNews.content}
              </Typography>
            </DialogContent>
            <DialogActions>
              <Button onClick={handleClose} color="primary">
                Close
              </Button>
            </DialogActions>
          </>
        )}
      </Dialog>
    </Box>
  );
};

export default News;
