'use client';

import React, { useEffect, useState } from 'react';
import { useRouter, useParams } from 'next/navigation';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Avatar,
  Stack,
  Chip,
  Button,
  IconButton,
  Divider,
  Grid,
  Paper,
  List,
  ListItem,
  ListItemText,
  ListItemIcon,
  Alert,
} from '@mui/material';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import EmailIcon from '@mui/icons-material/Email';
import PhoneIcon from '@mui/icons-material/Phone';
import LocationOnIcon from '@mui/icons-material/LocationOn';
import AccessTimeIcon from '@mui/icons-material/AccessTime';
import WorkIcon from '@mui/icons-material/Work';
import StarIcon from '@mui/icons-material/Star';
import PersonIcon from '@mui/icons-material/Person';
import { enqueueSnackbar } from 'notistack';

import { Volunteer } from '@/types/volunteer';
import { useVolunteers } from '@/contexts/VolunteersContext';
import { AppLoader } from '@/components/core/app-loader';

const VolunteerDetail: React.FC = () => {
  const [volunteer, setVolunteer] = useState<Volunteer | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const router = useRouter();
  const params = useParams();
  const volunteerId = params?.id as string;
  const { getVolunteerById } = useVolunteers();

  useEffect(() => {
    try {
      setIsLoading(true);
      setError(null);
      
      const foundVolunteer = getVolunteerById(volunteerId);
      
      if (foundVolunteer) {
        setVolunteer(foundVolunteer);
      } else {
        setError('Volunteer not found');
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to load volunteer details';
      setError(errorMessage);
      enqueueSnackbar(errorMessage, { variant: 'error' });
    } finally {
      setIsLoading(false);
    }
  }, [volunteerId, getVolunteerById]);

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'active': return 'success';
      case 'inactive': return 'error';
      case 'pending': return 'warning';
      default: return 'default';
    }
  };

  const getStatusLabel = (status: string) => {
    switch (status) {
      case 'active': return 'Active';
      case 'inactive': return 'Inactive';
      case 'pending': return 'Pending';
      default: return 'Unknown';
    }
  };

  if (isLoading) {
    return <AppLoader size="lg" viewport="content" label="Loading volunteer details..." />;
  }

  if (error || !volunteer) {
    return (
      <Box sx={{ p: 3 }}>
        <Alert severity="error" sx={{ mb: 2 }}>
          {error || 'Volunteer not found'}
        </Alert>
        <Button
          variant="outlined"
          startIcon={<ArrowBackIcon />}
          onClick={() => router.back()}
        >
          Go Back
        </Button>
      </Box>
    );
  }

  return (
    <Box sx={{ p: 3 }}>
      {/* Header */}
      <Stack direction="row" alignItems="center" spacing={2} mb={3}>
        <IconButton onClick={() => router.back()} sx={{ mr: 1 }}>
          <ArrowBackIcon />
        </IconButton>
        <Typography variant="h4" fontWeight={700}>
          Volunteer Details
        </Typography>
      </Stack>

      <Grid container spacing={3}>
        {/* Main Info Card */}
        <Grid item xs={12} md={4}>
          <Card sx={{ height: 'fit-content' }}>
            <CardContent>
              <Stack alignItems="center" spacing={2}>
                        <Avatar
                          sx={{
                            width: 80,
                            height: 80,
                            bgcolor: '#667eea',
                            fontSize: '2rem',
                            fontWeight: 600,
                          }}
                        >
                          {volunteer.name ? volunteer.name.charAt(0).toUpperCase() : <PersonIcon />}
                        </Avatar>
                        <Stack alignItems="center" spacing={1}>
                          <Typography variant="h5" fontWeight={600}>
                            {volunteer.name || 'No Name'}
                          </Typography>
                  <Chip
                    label={getStatusLabel(volunteer.status)}
                    color={getStatusColor(volunteer.status) as any}
                    size="small"
                    variant="filled"
                  />
                </Stack>
              </Stack>

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

              <Stack spacing={2}>
                <Stack direction="row" alignItems="center" spacing={2}>
                  <EmailIcon color="action" />
                  <Typography variant="body2" color="text.secondary">
                    {volunteer.formData.emailAddress || 'No email'}
                  </Typography>
                </Stack>
                <Stack direction="row" alignItems="center" spacing={2}>
                  <PhoneIcon color="action" />
                  <Typography variant="body2" color="text.secondary">
                    {volunteer.formData.phoneNumber || 'No phone'}
                  </Typography>
                </Stack>
                <Stack direction="row" alignItems="center" spacing={2}>
                  <LocationOnIcon color="action" />
                  <Typography variant="body2" color="text.secondary">
                    {volunteer.formData.address || 'Location not specified'}
                  </Typography>
                </Stack>
                <Stack direction="row" alignItems="center" spacing={2}>
                  <AccessTimeIcon color="action" />
                  <Typography variant="body2" color="text.secondary">
                    {volunteer.formData.hearFrom || 'Source not specified'}
                  </Typography>
                </Stack>
              </Stack>
            </CardContent>
          </Card>
        </Grid>

        {/* Details and Tasks */}
        <Grid item xs={12} md={8}>
          <Stack spacing={3}>
            {/* Registration Info */}
            <Card>
              <CardContent>
                <Typography variant="h6" gutterBottom>
                  Registration Information
                </Typography>
                <Grid container spacing={2}>
                  <Grid item xs={12} sm={6}>
                    <Typography variant="body2" color="text.secondary">
                      Signup Date
                    </Typography>
                    <Typography variant="body1">
                      {volunteer.signupDate
                        ? new Date(volunteer.signupDate).toLocaleDateString('en-US', {
                            weekday: 'long',
                            year: 'numeric',
                            month: 'long',
                            day: 'numeric'
                          })
                        : 'Unknown'
                      }
                    </Typography>
                  </Grid>
                </Grid>
              </CardContent>
            </Card>

            {/* Skills */}
            <Card>
              <CardContent>
                <Typography variant="h6" gutterBottom>
                  Skills & Expertise
                </Typography>
                {volunteer.formData.goodAt ? (
                  <Typography variant="body2">
                    {volunteer.formData.goodAt}
                  </Typography>
                ) : (
                  <Typography variant="body2" color="text.secondary">
                    No skills listed
                  </Typography>
                )}
              </CardContent>
            </Card>

            {/* Interests */}
            {volunteer.formData.interest && volunteer.formData.interest.length > 0 && (
              <Card>
                <CardContent>
                  <Typography variant="h6" gutterBottom>
                    Interests
                  </Typography>
                  <Stack direction="row" flexWrap="wrap" gap={1}>
                    {volunteer.formData.interest.map((interest, index) => (
                      <Chip
                        key={index}
                        label={interest}
                        variant="filled"
                        size="small"
                        color="primary"
                        sx={{ bgcolor: 'primary.50', color: 'primary.main' }}
                      />
                    ))}
                  </Stack>
                </CardContent>
              </Card>
            )}

            {/* Additional Information */}
            <Card>
              <CardContent>
                <Typography variant="h6" gutterBottom>
                  Additional Information
                </Typography>
                <Grid container spacing={2}>
                  <Grid item xs={12} sm={6}>
                    <Typography variant="body2" color="text.secondary">
                      Preferred Contact Method
                    </Typography>
                    <Typography variant="body1">
                      {volunteer.formData.preferedMethodOfcontact === 'emailAddress' ? 'Email' : 'Phone'}
                    </Typography>
                  </Grid>
                  <Grid item xs={12} sm={6}>
                    <Typography variant="body2" color="text.secondary">
                      How did they hear about us?
                    </Typography>
                    <Typography variant="body1">
                      {volunteer.formData.hearFrom || 'Not specified'}
                    </Typography>
                  </Grid>
                  <Grid item xs={12} sm={6}>
                    <Typography variant="body2" color="text.secondary">
                      Email Subscriptions
                    </Typography>
                    <Typography variant="body1">
                      {volunteer.formData.isEmailSubscribed ? 'Yes' : 'No'}
                    </Typography>
                  </Grid>
                  <Grid item xs={12} sm={6}>
                    <Typography variant="body2" color="text.secondary">
                      Phone Subscriptions
                    </Typography>
                    <Typography variant="body1">
                      {volunteer.formData.isPhoneSubscribed ? 'Yes' : 'No'}
                    </Typography>
                  </Grid>
                </Grid>
              </CardContent>
            </Card>
          </Stack>
        </Grid>
      </Grid>
    </Box>
  );
};

export default VolunteerDetail;
