import React from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Typography,
  Box,
  List,
  ListItem,
  ListItemIcon,
  ListItemText,
  Divider,
  Paper,
  IconButton,
  Accordion,
  AccordionSummary,
  AccordionDetails,
  Alert,
} from '@mui/material';
import {
  Timer as TimerIcon,
  CheckCircle as CheckIcon,
  Warning as WarningIcon,
  Info as InfoIcon,
  Build as BuildIcon,
  ExpandMore as ExpandMoreIcon,
  Science as ScienceIcon,
  Assignment as AssignmentIcon,
  Checklist as ChecklistIcon,
} from '@mui/icons-material';

interface MonitoringMethod {
  id: string;
  name: string;
  description: string;
  implementation: string[];
  accuracy: number;
  thresholds: {
    green: number;
    yellow: number;
  };
  timeRequired?: string;
}

interface MethodInfoDialogProps {
  open: boolean;
  onClose: () => void;
  method?: MonitoringMethod;
}

interface DetailedStep {
  title: string;
  content: string;
}

interface SugarRollThreshold {
  mites: number;
  percentage: number;
}

interface MonitoringBoardThreshold {
  mites: number;
  period: string;
}

interface BaseMethodDetails {
  overview: string;
  keyPoints: string[];
  materials: string[];
  detailedSteps: DetailedStep[];
}

interface SugarRollDetails extends BaseMethodDetails {
  seasonalThresholds: {
    may: SugarRollThreshold;
    august: SugarRollThreshold;
  };
}

interface MonitoringBoardDetails extends BaseMethodDetails {
  importance: string;
  seasonalThresholds: {
    may: MonitoringBoardThreshold;
    august: MonitoringBoardThreshold;
  };
  tips: string[];
}

interface AlcoholWashDetails extends BaseMethodDetails {
  importance: string;
  seasonalThresholds: {
    may: MonitoringBoardThreshold;
    august: MonitoringBoardThreshold;
  };
  tips: string[];
}

type MethodDetails = {
  'sugar-roll': SugarRollDetails;
  'sticky-board': MonitoringBoardDetails;
  'alcohol-wash': AlcoholWashDetails;
};

const SugarRollDetails: SugarRollDetails = {
  overview: `Sugar rolls are a non-lethal way to determine the varroa mite infestation rate on a subset of the adult bees within a colony. Test results allow you to compare the infestation rate with published thresholds and make decisions about whether or not treatment is warranted.

It's recommended to perform sugar rolls monthly throughout the entire bee-working season to monitor mite levels and plan treatments. A post-treatment sugar roll 10-14 days after treatment helps verify its effectiveness.`,
  
  keyPoints: [
    "Non-lethal testing method",
    "Monthly monitoring recommended",
    "Post-treatment verification after 10-14 days",
    "Consistent sampling methods crucial for accuracy",
    "Test nurse bees near brood area for best results",
    "Requires practice for optimal accuracy"
  ],

  materials: [
    "Dry powdered sugar",
    "Sampling jar with screened lid",
    "Half-cup measuring scoop",
    "Large plastic tub (cat litter box works well)",
    "Water spritzer",
    "Paper towels",
    "Timer"
  ],

  detailedSteps: [
    {
      title: "Queen Safety",
      content: "Before starting, ensure the queen is not among the bees being tested. If uncertain about queen location, select a frame away from brood nest and adjust results up by 20%."
    },
    {
      title: "Frame Selection",
      content: "Choose a frame just outside the brood area where nurse bees (with highest mite counts) are present. Verify the queen is not on this frame."
    },
    {
      title: "Collecting Bees",
      content: "Shake selected frame sharply over plastic tub. Nurse bees will remain while foragers and drones fly away. Return frame to hive immediately."
    },
    {
      title: "Sample Collection",
      content: "Consolidate bees in tub corner. Use half-cup scoop (~300 bees) to transfer to jar. Ensure accurate measurement for reliable results."
    },
    {
      title: "Sugar Application",
      content: "Add powdered sugar through screened lid. Roll jar for 2 minutes, maintaining angle for better coverage."
    },
    {
      title: "Testing Sequence",
      content: "Follow 2-2-2 timing: 2 minutes rolling, 2 minutes resting in shade, 2 minutes shaking over white paper towel."
    },
    {
      title: "Mite Count",
      content: "Spray water on sugar to reveal mites. Count total mites. Divide by 3 for infestation percentage (300 bees = 3%)."
    }
  ],

  seasonalThresholds: {
    may: { mites: 3, percentage: 1 },
    august: { mites: 6, percentage: 2 }
  }
};

const MonitoringBoardDetails: MonitoringBoardDetails = {
  overview: `Mite Monitoring boards (sticky boards) are an easy way to monitor varroa mite levels in your hive – easy for you and very easy on the bees since you don't even have to open the hive. Regular, season-long mite monitoring is an essential tool for keeping your bees healthy.

Varroa mites are dangerous pests in nearly all bee colonies. Not only do they harm bees by biting them, but they also spread viral diseases that can kill a strong hive in just a few months. Mite-spread diseases are frequently the cause of winter losses.`,

  importance: `There are many mite-control strategies you can use to protect your bees, but first you have to know the scope of the problem. Getting that data requires some form of mite monitoring.

Mite monitoring boards, which measure the number of mites falling from the hive over a period of time, are the least intrusive method. They are a good way to get started on a mite monitoring program. If you do them regularly all season long, you'll be alerted to any dangerous increase in mite levels in time to deal with it.`,
  
  keyPoints: [
    "Non-invasive method - no need to open the hive",
    "Measures natural mite fall over time",
    "Weekly monitoring recommended for trend analysis",
    "Helps prevent serious colony damage from mite-spread diseases",
    "Simple process taking only a few minutes",
    "Requires consistent monitoring for best results"
  ],

  materials: [
    "Screened bottom board",
    "Mite collection surface (tray or white corrugated plastic)",
    "Cooking oil (can use stale kitchen oil)",
    "Paper towels",
    "Magnifying glass",
    "Wooden toothpicks",
    "Optional: 3-M Original Blue Painters' tape (1.88\" wide, no writing)"
  ],

  detailedSteps: [
    {
      title: "Board Preparation",
      content: "With the screened bottom board in place, pour 2 tablespoons of oil on the board and spread it evenly using a paper towel. Slide the oiled board into the slot. If using tape, seal the slot to keep bees and ants out."
    },
    {
      title: "Monitoring Period",
      content: "Leave the board in place for exactly three days to collect falling mites."
    },
    {
      title: "Mite Counting",
      content: "Remove the board and take it to a well-lit area. Use a magnifying glass to locate mites. Use a moistened toothpick to pick up and move each mite to a clear counting area on the board."
    },
    {
      title: "Calculating Results",
      content: "Count the total mites found and divide by 3 (days) to get your average daily mite count. Compare this number with seasonal thresholds to determine if treatment is needed."
    },
    {
      title: "Record Keeping",
      content: "Write down your counts and consider plotting them on a graph to visualize trends over time. Early season numbers should be low, with potential rapid increases by midsummer."
    },
    {
      title: "Board Maintenance",
      content: "After counting, scrape debris into trash (not onto ground to prevent beetle larvae). Return clean board to slot for next test."
    }
  ],

  seasonalThresholds: {
    may: { mites: 9, period: "24 hours" },
    august: { mites: 12, period: "24 hours" }
  },

  tips: [
    "Start monitoring early in the season when numbers are typically low",
    "Don't wait until reaching treatment threshold to plan your control strategy",
    "Some control methods take time to reduce mite levels effectively",
    "Continue monitoring to verify treatment effectiveness",
    "Keep consistent weekly monitoring schedule"
  ]
};

const AlcoholWashDetails: AlcoholWashDetails = {
  overview: `Alcohol washes are an accurate and fast way to determine the varroa mite infestation rate on a subset of the adult bees within a colony. Test results allow you to compare the infestation rate with published thresholds and make decisions about whether or not treatment is warranted.`,

  importance: `While mite inspections had a reputation for being tedious and occasionally inaccurate, the alcohol wash method makes it quick and easy to keep an eye on mite counts. The disadvantage is that the sample of 300 bees is sacrificed during the test. However, keep in mind that although 300 bees seems like a large number, a queen typically produces between 1,000 and 1,500 eggs per day and the loss of 300 bees has no harmful consequence.`,

  keyPoints: [
    "Most accurate method for mite detection",
    "Monthly monitoring recommended",
    "Post-treatment verification after 10-14 days",
    "Requires sacrificing test bees",
    "Fast and reliable results",
    "Best performed on nurse bees near brood area"
  ],

  materials: [
    "Varroa EasyCheck or Varroa Mite Sample Bottle",
    "Half-cup measuring scoop",
    "Isopropyl alcohol and water mixture (1:4 ratio) or non-foaming windshield washer fluid",
    "Large plastic tub (cat litter box works well)",
    "Timer",
    "Fine mesh strainer",
    "Quart-sized plastic container for straining",
    "Larger container with lid for used sampling fluid",
    "Protective beekeeping gear"
  ],

  detailedSteps: [
    {
      title: "Queen Safety",
      content: "Before starting, locate and isolate the queen to ensure she is not among the test bees. You can temporarily place her and her frame in a nuc box. If you cannot find the queen, select a frame away from brood nest."
    },
    {
      title: "Prepare Testing Device",
      content: "Fill the alcohol wash device with isopropyl alcohol mixture (1:4 with water) or non-foaming windshield washer fluid until it covers the bottom of the inner perforated cylinder."
    },
    {
      title: "Bee Collection - Method 1",
      content: "Set plastic tub on ground. Shake selected frame sharply over tub to collect nurse bees. Consolidate bees in corner and use half-cup scoop to transfer to test bottle."
    },
    {
      title: "Bee Collection - Method 2",
      content: "Alternatively, brush bees directly from brood frame into basket or slide basket up frame to collect bees until reaching the 300-bee mark line."
    },
    {
      title: "Washing Process",
      content: "Shake container once to wet bees, add fluid to upper line. Shake gently for 60 seconds in various motions (vertical, horizontal, circular) to separate mites from bees."
    },
    {
      title: "Counting Mites",
      content: "Hold container to light and count mites at bottom. Divide total by 3 to get infestation percentage (e.g., 15 mites/300 bees = 5%)."
    },
    {
      title: "Clean Up",
      content: "Remove and discard bees. Strain fluid to remove mites and debris. Fluid can be reused several times before replacement."
    }
  ],

  seasonalThresholds: {
    may: { mites: 6, period: "24 hours" },
    august: { mites: 9, period: "24 hours" }
  },

  tips: [
    "Select nurse bees from brood area for most accurate results",
    "Maintain consistent sample size of 300 bees",
    "Consider 2% (6 mites per 300 bees) as treatment threshold",
    "Perform test monthly during active season",
    "Verify treatment effectiveness after 10-14 days",
    "Keep sampling fluid for multiple tests",
    "Always wear appropriate protective gear"
  ]
};

const methodDetails: MethodDetails = {
  'sugar-roll': SugarRollDetails,
  'sticky-board': MonitoringBoardDetails,
  'alcohol-wash': AlcoholWashDetails
};

const MethodInfoDialog: React.FC<MethodInfoDialogProps> = ({ open, onClose, method }) => {
  const details = method?.id ? methodDetails[method.id as keyof MethodDetails] : undefined;

  const isMonitoringBoardMethod = (method: typeof details): method is MonitoringBoardDetails => {
    return method !== undefined && 'importance' in method;
  };

  const isAlcoholWashMethod = (method: typeof details): method is AlcoholWashDetails => {
    return method !== undefined && 'importance' in method;
  };

  const renderThresholds = () => {
    if (!details) return null;

    if (isMonitoringBoardMethod(details)) {
      return (
        <>
          <Paper elevation={2} sx={{ flex: 1, p: 2 }}>
            <Typography variant="subtitle2" gutterBottom>May</Typography>
            <Typography variant="h6">{details.seasonalThresholds.may.mites} mites</Typography>
            <Typography variant="body2" color="text.secondary">
              per {details.seasonalThresholds.may.period}
            </Typography>
          </Paper>
          <Paper elevation={2} sx={{ flex: 1, p: 2 }}>
            <Typography variant="subtitle2" gutterBottom>August</Typography>
            <Typography variant="h6">{details.seasonalThresholds.august.mites} mites</Typography>
            <Typography variant="body2" color="text.secondary">
              per {details.seasonalThresholds.august.period}
            </Typography>
          </Paper>
        </>
      );
    } else if (isAlcoholWashMethod(details)) {
      return (
        <>
          <Paper elevation={2} sx={{ flex: 1, p: 2 }}>
            <Typography variant="subtitle2" gutterBottom>May</Typography>
            <Typography variant="h6">{details.seasonalThresholds.may.mites} mites</Typography>
            <Typography variant="body2" color="text.secondary">
              per {details.seasonalThresholds.may.period}
            </Typography>
          </Paper>
          <Paper elevation={2} sx={{ flex: 1, p: 2 }}>
            <Typography variant="subtitle2" gutterBottom>August</Typography>
            <Typography variant="h6">{details.seasonalThresholds.august.mites} mites</Typography>
            <Typography variant="body2" color="text.secondary">
              per {details.seasonalThresholds.august.period}
            </Typography>
          </Paper>
        </>
      );
    } else {
      return (
        <>
          <Paper elevation={2} sx={{ flex: 1, p: 2 }}>
            <Typography variant="subtitle2" gutterBottom>May</Typography>
            <Typography variant="h6">{details.seasonalThresholds.may.mites} mites</Typography>
            <Typography variant="body2" color="text.secondary">
              ({details.seasonalThresholds.may.percentage}% threshold)
            </Typography>
          </Paper>
          <Paper elevation={2} sx={{ flex: 1, p: 2 }}>
            <Typography variant="subtitle2" gutterBottom>August</Typography>
            <Typography variant="h6">{details.seasonalThresholds.august.mites} mites</Typography>
            <Typography variant="body2" color="text.secondary">
              ({details.seasonalThresholds.august.percentage}% threshold)
            </Typography>
          </Paper>
        </>
      );
    }
  };

  if (!details) {
    return (
      <Dialog
        open={open}
        onClose={onClose}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle sx={{ 
          display: 'flex', 
          alignItems: 'center', 
          gap: 1,
          bgcolor: 'error.main',
          color: 'error.contrastText',
        }}>
          <WarningIcon />
          <Typography variant="h6" component="span">
            Method Not Found
          </Typography>
        </DialogTitle>
        <DialogContent>
          <Typography sx={{ mt: 2 }}>
            The monitoring method "{method?.name}" is not available or has not been implemented yet.
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={onClose} variant="contained" color="error">
            Close
          </Button>
        </DialogActions>
      </Dialog>
    );
  }

  return (
    <Dialog
      open={open}
      onClose={onClose}
      maxWidth="md"
      fullWidth
      scroll="paper"
      PaperProps={{
        sx: {
          borderRadius: 2,
          maxHeight: '90vh',
        },
      }}
    >
      <DialogTitle sx={{ 
        display: 'flex', 
        alignItems: 'center', 
        gap: 1,
        bgcolor: 'primary.main',
        color: 'primary.contrastText',
      }}>
        <InfoIcon />
        <Typography variant="h6" component="span">
          {method?.name} - Detailed Guide
        </Typography>
      </DialogTitle>

      <DialogContent dividers>
        <Box sx={{ p: 2 }}>
          <Typography variant="h6" gutterBottom color="primary" sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <InfoIcon />
            Overview
          </Typography>
          <Typography paragraph>
            {details.overview}
          </Typography>

          {(isMonitoringBoardMethod(details) || isAlcoholWashMethod(details)) && (
            <Typography paragraph>
              {details.importance}
            </Typography>
          )}

          <Alert severity="info" sx={{ my: 2 }}>
            <Typography variant="subtitle2" gutterBottom>
              Key Points:
            </Typography>
            <List dense>
              {details.keyPoints.map((point, index) => (
                <ListItem key={index}>
                  <ListItemIcon>
                    <CheckIcon color="info" fontSize="small" />
                  </ListItemIcon>
                  <ListItemText primary={point} />
                </ListItem>
              ))}
            </List>
          </Alert>

          <Divider sx={{ my: 3 }} />

          <Typography variant="h6" gutterBottom color="primary" sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <BuildIcon />
            Required Materials
          </Typography>
          <List dense>
            {details.materials.map((material, index) => (
              <ListItem key={index}>
                <ListItemIcon>
                  <CheckIcon color="success" fontSize="small" />
                </ListItemIcon>
                <ListItemText primary={material} />
              </ListItem>
            ))}
          </List>

          <Divider sx={{ my: 3 }} />

          <Typography variant="h6" gutterBottom color="primary" sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <AssignmentIcon />
            Step-by-Step Implementation
          </Typography>
          {details.detailedSteps.map((step, index) => (
            <Accordion key={index}>
              <AccordionSummary expandIcon={<ExpandMoreIcon />}>
                <Typography sx={{ fontWeight: 'medium' }}>
                  {index + 1}. {step.title}
                </Typography>
              </AccordionSummary>
              <AccordionDetails>
                <Typography>{step.content}</Typography>
              </AccordionDetails>
            </Accordion>
          ))}

          <Divider sx={{ my: 3 }} />

          <Typography variant="h6" gutterBottom color="primary">
            Treatment Thresholds
          </Typography>
          <Box sx={{ display: 'flex', gap: 2, mt: 2 }}>
            {renderThresholds()}
          </Box>

          {(isMonitoringBoardMethod(details) || isAlcoholWashMethod(details)) && (
            <>
              <Divider sx={{ my: 3 }} />
              <Alert severity="warning" sx={{ mt: 2 }}>
                <Typography variant="subtitle2" gutterBottom>
                  Important Tips:
                </Typography>
                <List dense>
                  {details.tips.map((tip: string, index: number) => (
                    <ListItem key={index}>
                      <ListItemIcon>
                        <WarningIcon color="warning" fontSize="small" />
                      </ListItemIcon>
                      <ListItemText primary={tip} />
                    </ListItem>
                  ))}
                </List>
              </Alert>
            </>
          )}

          <Box sx={{ mt: 3, p: 2, bgcolor: 'info.light', borderRadius: 1 }}>
            <Typography variant="subtitle1" sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
              <WarningIcon color="info" />
              Test Accuracy
            </Typography>
            <Typography variant="body1">
              This method has a {method?.accuracy}% accuracy rate when performed correctly. The accuracy depends on consistent monitoring and proper technique.
            </Typography>
          </Box>

          {method?.timeRequired && (
            <Box sx={{ mt: 3, p: 2, bgcolor: 'grey.100', borderRadius: 1 }}>
              <Typography variant="subtitle1" sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                <TimerIcon color="action" />
                Time Required
              </Typography>
              <Typography variant="body1">
                {method.timeRequired}
              </Typography>
            </Box>
          )}
        </Box>
      </DialogContent>

      <DialogActions sx={{ p: 2 }}>
        <Button onClick={onClose} variant="contained">
          Close
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default MethodInfoDialog;
