import React from 'react';
import {
  Box,
  Typography,
  Grid,
  Card,
  CardContent,
  List,
  ListItem,
  ListItemText,
  ListItemIcon,
  Chip,
  Paper,
} from '@mui/material';
import {
  Build as BuildIcon,
  Package as PackageIcon,
  Publish as PublishIcon,
  CheckCircle as SuccessIcon,
  Error as ErrorIcon,
  Schedule as InProgressIcon,
} from '@mui/icons-material';
import { usePackages } from '../hooks/usePackages';
import { useProjectStatus } from '../hooks/useProjects';
import { useActivePublications } from '../hooks/usePublications';
import { StatusChip } from '../components/common/StatusChip';
import { LoadingSpinner } from '../components/common/LoadingSpinner';
import { ErrorDisplay } from '../components/common/ErrorDisplay';
import { PublicationStatus, PackageStatus, BuildStatus } from '../types';
import { format } from 'date-fns';

export const DashboardPage: React.FC = () => {
  const { data: packagesData, isLoading: packagesLoading } = usePackages(1, 5);
  const { data: projectsData, isLoading: projectsLoading } = useProjectStatus();
  const { data: activePublications, isLoading: publicationsLoading } = useActivePublications();

  const isLoading = packagesLoading || projectsLoading || publicationsLoading;

  if (isLoading) return <LoadingSpinner message="Loading dashboard..." />;

  const packages = packagesData?.data || [];
  const projects = projectsData?.data || [];
  const publications = activePublications?.data || [];

  // Calculate statistics
  const packageStats = {
    total: packagesData?.totalCount || 0,
    published: packages.filter(p => p.status === PackageStatus.Published).length,
    failed: packages.filter(p => p.status === PackageStatus.Failed).length,
    publishing: packages.filter(p => p.status === PackageStatus.Publishing).length,
  };

  const buildStats = {
    success: projects.filter(p => p.status === BuildStatus.Success).length,
    failure: projects.filter(p => p.status === BuildStatus.Failure).length,
    inProgress: projects.filter(p => p.status === BuildStatus.InProgress).length,
  };

  const publicationStats = {
    active: publications.filter(p => p.status === PublicationStatus.InProgress).length,
    queued: publications.filter(p => p.status === PublicationStatus.Queued).length,
  };

  return (
    <Box>
      <Typography variant="h4" component="h1" gutterBottom>
        Dashboard
      </Typography>

      {/* Statistics Cards */}
      <Grid container spacing={3} mb={4}>
        <Grid item xs={12} sm={6} md={3}>
          <Card>
            <CardContent>
              <Box display="flex" alignItems="center" justifyContent="space-between">
                <Box>
                  <Typography color="text.secondary" gutterBottom variant="h6">
                    Packages
                  </Typography>
                  <Typography variant="h4">
                    {packageStats.total}
                  </Typography>
                  <Box display="flex" gap={1} mt={1}>
                    <Chip label={`${packageStats.published} Published`} size="small" color="success" />
                    <Chip label={`${packageStats.publishing} Publishing`} size="small" color="info" />
                  </Box>
                </Box>
                <PackageIcon sx={{ fontSize: 40, color: 'primary.main' }} />
              </Box>
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12} sm={6} md={3}>
          <Card>
            <CardContent>
              <Box display="flex" alignItems="center" justifyContent="space-between">
                <Box>
                  <Typography color="text.secondary" gutterBottom variant="h6">
                    Projects
                  </Typography>
                  <Typography variant="h4">
                    {projects.length}
                  </Typography>
                  <Box display="flex" gap={1} mt={1}>
                    <Chip label={`${buildStats.success} Success`} size="small" color="success" />
                    <Chip label={`${buildStats.failure} Failed`} size="small" color="error" />
                  </Box>
                </Box>
                <BuildIcon sx={{ fontSize: 40, color: 'primary.main' }} />
              </Box>
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12} sm={6} md={3}>
          <Card>
            <CardContent>
              <Box display="flex" alignItems="center" justifyContent="space-between">
                <Box>
                  <Typography color="text.secondary" gutterBottom variant="h6">
                    Active Publications
                  </Typography>
                  <Typography variant="h4">
                    {publicationStats.active}
                  </Typography>
                  <Box display="flex" gap={1} mt={1}>
                    <Chip label={`${publicationStats.queued} Queued`} size="small" color="warning" />
                  </Box>
                </Box>
                <PublishIcon sx={{ fontSize: 40, color: 'primary.main' }} />
              </Box>
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12} sm={6} md={3}>
          <Card>
            <CardContent>
              <Box display="flex" alignItems="center" justifyContent="space-between">
                <Box>
                  <Typography color="text.secondary" gutterBottom variant="h6">
                    System Status
                  </Typography>
                  <Typography variant="h6" color="success.main">
                    All Systems Operational
                  </Typography>
                </Box>
                <SuccessIcon sx={{ fontSize: 40, color: 'success.main' }} />
              </Box>
            </CardContent>
          </Card>
        </Grid>
      </Grid>

      {/* Recent Activity */}
      <Grid container spacing={3}>
        <Grid item xs={12} md={6}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>
                Recent Packages
              </Typography>
              <List>
                {packages.length === 0 ? (
                  <ListItem>
                    <ListItemText 
                      primary="No packages found"
                      secondary="Create your first package to get started"
                    />
                  </ListItem>
                ) : (
                  packages.map((pkg) => (
                    <ListItem key={pkg.id}>
                      <ListItemIcon>
                        <PackageIcon />
                      </ListItemIcon>
                      <ListItemText
                        primary={pkg.title}
                        secondary={`Version ${pkg.version} • ${pkg.project?.name}`}
                      />
                      <StatusChip status={pkg.status} />
                    </ListItem>
                  ))
                )}
              </List>
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12} md={6}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>
                Project Build Status
              </Typography>
              <List>
                {projects.length === 0 ? (
                  <ListItem>
                    <ListItemText 
                      primary="No projects found"
                      secondary="Projects will appear here once configured"
                    />
                  </ListItem>
                ) : (
                  projects.slice(0, 5).map((project) => (
                    <ListItem key={project.id}>
                      <ListItemIcon>
                        {project.status === BuildStatus.Success ? (
                          <SuccessIcon color="success" />
                        ) : project.status === BuildStatus.Failure ? (
                          <ErrorIcon color="error" />
                        ) : (
                          <InProgressIcon color="info" />
                        )}
                      </ListItemIcon>
                      <ListItemText
                        primary={project.name}
                        secondary={project.description}
                      />
                      <StatusChip status={project.status} />
                    </ListItem>
                  ))
                )}
              </List>
            </CardContent>
          </Card>
        </Grid>

        {publications.length > 0 && (
          <Grid item xs={12}>
            <Card>
              <CardContent>
                <Typography variant="h6" gutterBottom>
                  Active Publications
                </Typography>
                <List>
                  {publications.map((publication) => (
                    <ListItem key={publication.id}>
                      <ListItemIcon>
                        <PublishIcon />
                      </ListItemIcon>
                      <ListItemText
                        primary={publication.package?.title}
                        secondary={`Version ${publication.package?.version} • Started ${
                          publication.publishedAt ? 
                            format(new Date(publication.publishedAt), 'MMM dd, HH:mm') : 
                            'Unknown'
                        }`}
                      />
                      <StatusChip status={publication.status} />
                    </ListItem>
                  ))}
                </List>
              </CardContent>
            </Card>
          </Grid>
        )}
      </Grid>
    </Box>
  );
};