import React, { useState } from 'react';
import { Link, useParams } from 'react-router-dom';
import styled from 'styled-components';
import { HiChevronDown, HiChevronRight } from 'react-icons/hi';
import { PageSection } from '@/shared/components/layout/PageSection';
import { useLocale } from '@/app/providers/LocaleProvider';
import { ProjectPageShell } from '@/features/projects/components/ProjectPageShell';
import { AnalyticsReportCard } from '@/features/projects/components/AnalyticsReportCard';
import { ENTERPRISE_REPORTS, REPORT_ROUTE_BY_KEY } from '@/features/projects/reports/reportCatalog';

const PRIMARY_KEYS = ['velocity', 'burndown', 'sprint-health', 'capacity-trend', 'risk-trend'];

const Subtitle = styled.p`
  margin: 0 0 ${({ theme }) => theme.spacing[6]};
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  color: ${({ theme }) => theme.colors.text.secondary};
  max-width: 64ch;
`;

const Grid = styled.div`
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: ${({ theme }) => theme.spacing[6]};
`;

const MoreToggle = styled.button`
  display: flex;
  align-items: center;
  gap: ${({ theme }) => theme.spacing[2]};
  background: none;
  border: none;
  padding: ${({ theme }) => `${theme.spacing[3]} 0`};
  cursor: pointer;
  font-size: ${({ theme }) => theme.typography.fontSize.base};
  font-weight: ${({ theme }) => theme.typography.fontWeight.semibold};
  color: ${({ theme }) => theme.colors.text.primary};
`;

const MoreHint = styled.span`
  font-weight: ${({ theme }) => theme.typography.fontWeight.normal};
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  color: ${({ theme }) => theme.colors.text.secondary};
`;

const MoreGrid = styled.div`
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: ${({ theme }) => theme.spacing[3]};
`;

const SecondaryLink = styled(Link)`
  display: block;
  padding: ${({ theme }) => theme.spacing[3]} ${({ theme }) => theme.spacing[4]};
  border: 1px solid ${({ theme }) => theme.colors.borderSoft};
  border-radius: ${({ theme }) => theme.borderRadius.md};
  text-decoration: none;
  color: ${({ theme }) => theme.colors.text.primary};
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  font-weight: ${({ theme }) => theme.typography.fontWeight.medium};
  transition: border-color 0.15s ease;

  &:hover {
    border-color: ${({ theme }) => theme.colors.primary};
  }
`;

const SecondaryDesc = styled.div`
  margin-top: ${({ theme }) => theme.spacing[1]};
  font-size: ${({ theme }) => theme.typography.fontSize.xs};
  font-weight: ${({ theme }) => theme.typography.fontWeight.normal};
  color: ${({ theme }) => theme.colors.text.secondary};
`;

const ProjectReportsPage: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const { t } = useLocale();
  const [showMore, setShowMore] = useState(false);

  if (!id) return null;

  const primary = PRIMARY_KEYS.map((key) => ENTERPRISE_REPORTS.find((r) => r.key === key)).filter(
    (d): d is NonNullable<typeof d> => Boolean(d),
  );
  const secondary = ENTERPRISE_REPORTS.filter((r) => !PRIMARY_KEYS.includes(r.key));

  return (
    <ProjectPageShell projectId={id}>
      {() => (
        <>
          <PageSection title={t('projects:analyticsCenter.title')}>
            <Subtitle>{t('projects:analyticsCenter.subtitle')}</Subtitle>
            <Grid>
              {primary.map((definition) => (
                <AnalyticsReportCard key={definition.key} projectId={id} definition={definition} />
              ))}
            </Grid>
          </PageSection>

          <PageSection>
            <MoreToggle type="button" onClick={() => setShowMore((v) => !v)} aria-expanded={showMore}>
              {showMore ? <HiChevronDown /> : <HiChevronRight />}
              {t('projects:analyticsCenter.more')}
              <MoreHint>· {t('projects:analyticsCenter.moreHint')}</MoreHint>
            </MoreToggle>
            {showMore && (
              <MoreGrid>
                {secondary.map((definition) => {
                  const route = REPORT_ROUTE_BY_KEY[definition.key]?.(id);
                  if (!route) return null;
                  return (
                    <SecondaryLink key={definition.key} to={route}>
                      {t(`projects:reportsHub.${definition.key}.title`)}
                      <SecondaryDesc>
                        {t(`projects:reportsHub.${definition.key}.description`)}
                      </SecondaryDesc>
                    </SecondaryLink>
                  );
                })}
              </MoreGrid>
            )}
          </PageSection>
        </>
      )}
    </ProjectPageShell>
  );
};

export default ProjectReportsPage;
