'use client';

import React from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  useTheme,
  Grid,
  LinearProgress,
  Chip,
} from '@mui/material';
import { AppLoader } from '@/components/core/app-loader';
import { useRouter } from 'next/navigation';
import { Chart } from '@/components/core/chart';
import { FormCompletionOverview, VolunteerFormStatus } from '@/services/analytics.service';

interface FormCompletionStatsProps {
  overview: FormCompletionOverview;
  volunteerFormStatus: VolunteerFormStatus;
  loading?: boolean;
}

export function FormCompletionStats({ overview, volunteerFormStatus, loading }: FormCompletionStatsProps) {
  const theme = useTheme();
  const router = useRouter();

  const handleVolunteerCardClick = () => {
    router.push('/dashboard/volunteers');
  };

  // Add default values and error handling
  const safeVolunteerFormStatus = {
    accepted: volunteerFormStatus?.accepted || { count: 0, percentage: 0 },
    rejected: volunteerFormStatus?.rejected || { count: 0, percentage: 0 },
    pending: volunteerFormStatus?.pending || { count: 0, percentage: 0 },
  };

  const safeOverview = {
    totalUsers: overview?.totalUsers || 0,
    profileCompletedUsers: overview?.profileCompletedUsers || 0,
    volunteerFormUsers: overview?.volunteerFormUsers || 0,
    profileCompletionRate: overview?.profileCompletionRate || 0,
    volunteerFormRate: overview?.volunteerFormRate || 0,
  };

  const donutChartOptions = {
    chart: {
      type: 'donut' as const,
      height: 250,
      background: 'transparent',
      toolbar: {
        show: false,
      },
    },
    colors: [theme.palette.success.main, theme.palette.warning.main],
    labels: ['Profile Completed', 'Profile Incomplete'],
    legend: {
      position: 'bottom' as const,
      labels: {
        colors: theme.palette.text.secondary,
      },
      fontSize: '14px',
      fontFamily: theme.typography.fontFamily,
    },
    plotOptions: {
      pie: {
        donut: {
          size: '60%',
          labels: {
            show: true,
            name: {
              show: true,
              fontSize: '16px',
              fontWeight: 600,
              color: theme.palette.text.primary,
            },
            value: {
              show: true,
              fontSize: '24px',
              fontWeight: 700,
              color: theme.palette.text.primary,
              formatter: (val: string) => {
                const parsed = Number.parseInt(val, 10);
                return Number.isFinite(parsed) ? parsed.toLocaleString() : '0';
              },
            },
            total: {
              show: true,
              showAlways: false,
              label: 'Total Users',
              fontSize: '14px',
              fontWeight: 600,
              color: theme.palette.text.secondary,
              formatter: (w: { globals?: { seriesTotals?: number[] } }) => {
                const totals = w.globals?.seriesTotals ?? [];
                const total = totals.reduce((sum, value) => {
                  const parsed = Number(value);
                  return sum + (Number.isFinite(parsed) ? parsed : 0);
                }, 0);
                return total.toLocaleString();
              },
            },
          },
        },
      },
    },
    dataLabels: {
      enabled: false,
    },
    tooltip: {
      theme: (theme.palette.mode === 'dark' ? 'dark' : 'light') as 'dark' | 'light',
      y: {
        formatter: (val: number) => {
          return val.toLocaleString() + ' users';
        },
      },
    },
    responsive: [
      {
        breakpoint: 480,
        options: {
          chart: {
            height: 200,
          },
          legend: {
            position: 'bottom' as const,
          },
        },
      },
    ],
  };

  const incompleteUsers = Math.max(
    0,
    (safeOverview.totalUsers || 0) - (safeOverview.profileCompletedUsers || 0)
  );

  const donutSeries = [
    Math.max(0, safeOverview.profileCompletedUsers || 0),
    incompleteUsers,
  ];

  // Check if we have valid data to display
  const hasValidData = safeOverview.totalUsers > 0;
  const totalSum = donutSeries.reduce((a, b) => a + b, 0);

  const barChartOptions = {
    chart: {
      type: 'bar' as const,
      height: 200,
      toolbar: {
        show: false,
      },
    },
    colors: [theme.palette.success.main, theme.palette.error.main, theme.palette.warning.main],
    xaxis: {
      categories: ['Accepted', 'Rejected', 'Pending'],
      labels: {
        style: {
          colors: theme.palette.text.secondary,
        },
      },
    },
    yaxis: {
      labels: {
        style: {
          colors: theme.palette.text.secondary,
        },
      },
    },
    grid: {
      borderColor: theme.palette.divider,
      strokeDashArray: 3,
    },
    tooltip: {
      theme: (theme.palette.mode === 'dark' ? 'dark' : 'light') as 'dark' | 'light',
    },
  };

  const barSeries = [
    {
      name: 'Volunteer Applications',
      data: [
        Number(safeVolunteerFormStatus.accepted.count ?? 0),
        Number(safeVolunteerFormStatus.rejected.count ?? 0),
        Number(safeVolunteerFormStatus.pending.count ?? 0),
      ],
    },
  ];

  return (
    <Grid container spacing={3}>
      {/* Profile Completion Overview */}
      <Grid item xs={12} md={6}>
        <Card
          sx={{
            borderRadius: 3,
            boxShadow: theme.shadows[2],
            height: '100%',
          }}
        >
          <CardContent>
            <Box sx={{ mb: 3 }}>
              <Typography variant="h6" fontWeight={600} gutterBottom>
                Profile Completion Rate
              </Typography>
              <Typography variant="body2" color="text.secondary">
                User profile completion statistics
              </Typography>
            </Box>

            <Box sx={{ mb: 3 }}>
              <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
                <Typography variant="body2">Profile Completion</Typography>
                <Typography variant="body2" fontWeight={600}>
                  {safeOverview.profileCompletionRate}%
                </Typography>
              </Box>
              <LinearProgress
                variant="determinate"
                value={safeOverview.profileCompletionRate}
                sx={{
                  height: 8,
                  borderRadius: 4,
                  backgroundColor: theme.palette.grey[200],
                  '& .MuiLinearProgress-bar': {
                    borderRadius: 4,
                    backgroundColor: theme.palette.success.main,
                  },
                }}
              />
            </Box>

            <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 2 }}>
              <Box sx={{ textAlign: 'center' }}>
                <Typography variant="h5" fontWeight={700} color="success.main">
                  {safeOverview.profileCompletedUsers}
                </Typography>
                <Typography variant="caption" color="text.secondary">
                  Completed
                </Typography>
              </Box>
              <Box sx={{ textAlign: 'center' }}>
                <Typography variant="h5" fontWeight={700}>
                  {safeOverview.totalUsers}
                </Typography>
                <Typography variant="caption" color="text.secondary">
                  Total Users
                </Typography>
              </Box>
            </Box>

            {loading ? (
              <Box sx={{ position: 'relative', height: 250 }}>
                <AppLoader fill size="md" />
              </Box>
            ) : !hasValidData || totalSum === 0 ? (
              <Box sx={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', height: 250 }}>
                <Typography variant="h6" color="text.secondary" gutterBottom>
                  No Data Available
                </Typography>
                <Typography variant="body2" color="text.secondary" textAlign="center">
                  No user profile data to display at this time.
                </Typography>
              </Box>
            ) : (
              <Chart
                options={donutChartOptions}
                series={donutSeries}
                type="donut"
                height={250}
              />
            )}
          </CardContent>
        </Card>
      </Grid>

      {/* Volunteer Form Status */}
      <Grid item xs={12} md={6}>
        <Card
          onClick={handleVolunteerCardClick}
          sx={{
            borderRadius: 3,
            boxShadow: theme.shadows[2],
            height: '100%',
            cursor: 'pointer',
            transition: 'all 0.3s ease-in-out',
            '&:hover': {
              boxShadow: theme.shadows[4],
              transform: 'translateY(-2px)',
              backgroundColor: theme.palette.action.hover,
            },
          }}
        >
          <CardContent>
            <Box sx={{ mb: 3 }}>
              <Typography variant="h6" fontWeight={600} gutterBottom>
                Volunteer Applications
              </Typography>
              <Typography variant="body2" color="text.secondary">
                Volunteer form submission status
              </Typography>
            </Box>

            <Box sx={{ mb: 3 }}>
              <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
                <Typography variant="body2">Volunteer Form Rate</Typography>
                <Typography variant="body2" fontWeight={600}>
                  {safeOverview.volunteerFormRate}%
                </Typography>
              </Box>
              <LinearProgress
                variant="determinate"
                value={safeOverview.volunteerFormRate}
                sx={{
                  height: 8,
                  borderRadius: 4,
                  backgroundColor: theme.palette.grey[200],
                  '& .MuiLinearProgress-bar': {
                    borderRadius: 4,
                    backgroundColor: theme.palette.primary.main,
                  },
                }}
              />
            </Box>

            <Box sx={{ display: 'flex', gap: 2, mb: 3, flexWrap: 'wrap' }}>
              <Chip
                label={`Accepted: ${safeVolunteerFormStatus.accepted.count}`}
                color="success"
                variant="outlined"
                size="small"
              />
              <Chip
                label={`Rejected: ${safeVolunteerFormStatus.rejected.count}`}
                color="error"
                variant="outlined"
                size="small"
              />
              <Chip
                label={`Pending: ${safeVolunteerFormStatus.pending.count}`}
                color="warning"
                variant="outlined"
                size="small"
              />
            </Box>

            {loading ? (
              <Box sx={{ position: 'relative', height: 200 }}>
                <AppLoader fill size="md" />
              </Box>
            ) : (
              <Chart
                options={barChartOptions}
                series={barSeries}
                type="bar"
                height={200}
              />
            )}
          </CardContent>
        </Card>
      </Grid>
    </Grid>
  );
}
