import React, { useMemo } from 'react';
import { Link, useParams } from 'react-router-dom';
import styled from 'styled-components';
import { useQuery } from '@tanstack/react-query';
import {
  HiCheckCircle,
  HiExclamation,
  HiFlag,
  HiLightningBolt,
} from 'react-icons/hi';
import { PageSection } from '@/shared/components/layout/PageSection';
import { ContentPanel } from '@/shared/components/layout/ContentPanel';
import { Card, StatusBadge } from '@/shared/components/ui';
import { PanelLoadingState } from '@/shared/components/ui/PageState';
import { StatCard } from '@/features/dashboard/components/StatCard';
import { useLocale } from '@/app/providers/LocaleProvider';
import { ProjectPageShell } from '@/features/projects/components/ProjectPageShell';
import { ProjectsStatsGrid } from '@/features/projects/components/projectsLayout';
import { healthStatusTone } from '@/features/projects/utils/projectDisplay';
import { ReportChart } from '@/features/projects/components/ReportChart';
import { SprintHealthBreakdown } from '@/features/projects/components/SprintHealthBreakdown';
import { fetchExecutiveDashboard } from '@/features/projects/services/projectService';
import { ROUTES } from '@/shared/constants/routes';

const Stack = styled.div`
  display: flex;
  flex-direction: column;
  gap: ${({ theme }) => theme.spacing[8]};
`;

/* Section 1 — Project Health */
const HealthGrid = styled.div`
  display: grid;
  grid-template-columns: minmax(220px, 320px) 1fr;
  gap: ${({ theme }) => theme.spacing[6]};

  @media (max-width: 900px) {
    grid-template-columns: 1fr;
  }
`;

const HealthHero = styled(ContentPanel)`
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  gap: ${({ theme }) => theme.spacing[3]};
`;

const HealthScore = styled.div<{ $level: string }>`
  font-size: 4.5rem;
  font-weight: ${({ theme }) => theme.typography.fontWeight.bold};
  line-height: 1;
  color: ${({ theme, $level }) => {
    if ($level === 'healthy' || $level === 'good') return theme.colors.success;
    if ($level === 'at_risk' || $level === 'warning') return theme.colors.warning;
    return theme.colors.error;
  }};
`;

const CompletionBar = styled.div`
  width: 100%;
  margin-top: ${({ theme }) => theme.spacing[2]};
`;

const Track = styled.div`
  height: 8px;
  border-radius: 999px;
  background: ${({ theme }) => theme.colors.surfaceInset};
  overflow: hidden;
`;

const Fill = styled.div<{ $value: number; $level: string }>`
  height: 100%;
  width: ${({ $value }) => Math.min(100, Math.max(0, $value))}%;
  background: ${({ theme, $level }) =>
    $level === 'critical' ? theme.colors.error : $level === 'at_risk' ? theme.colors.warning : theme.colors.success};
  transition: width 0.3s ease;
`;

const ExplanationList = styled.ul`
  margin: 0;
  padding-inline-start: ${({ theme }) => theme.spacing[5]};
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  color: ${({ theme }) => theme.colors.text.secondary};
  line-height: 1.7;
`;

/* Generic two-column chart row */
const TwoCol = styled.div`
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: ${({ theme }) => theme.spacing[6]};

  @media (max-width: 900px) {
    grid-template-columns: 1fr;
  }
`;

const ChartCaption = styled.div`
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  font-weight: ${({ theme }) => theme.typography.fontWeight.semibold};
  color: ${({ theme }) => theme.colors.text.primary};
  margin-bottom: ${({ theme }) => theme.spacing[3]};
  display: flex;
  align-items: center;
  justify-content: space-between;
`;

const EmptyChart = styled.div`
  min-height: 220px;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  padding: ${({ theme }) => theme.spacing[6]};
  color: ${({ theme }) => theme.colors.text.secondary};
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
`;

/* Section 4 — forecast / lists */
const ForecastDate = styled.div`
  font-size: ${({ theme }) => theme.typography.fontSize['2xl']};
  font-weight: ${({ theme }) => theme.typography.fontWeight.bold};
  color: ${({ theme }) => theme.colors.text.primary};
`;

const ForecastMeta = styled.div`
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  color: ${({ theme }) => theme.colors.text.secondary};
  margin-top: ${({ theme }) => theme.spacing[2]};
`;

const ListStack = styled.div`
  display: flex;
  flex-direction: column;
  gap: ${({ theme }) => theme.spacing[2]};
`;

const Row = styled.div<{ $tone?: 'error' | 'warning' | 'default' }>`
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: ${({ theme }) => theme.spacing[3]};
  padding: ${({ theme }) => theme.spacing[3]};
  border-radius: ${({ theme }) => theme.borderRadius.sm};
  background: ${({ theme, $tone }) =>
    $tone === 'error'
      ? `${theme.colors.error}10`
      : $tone === 'warning'
        ? `${theme.colors.warning}10`
        : theme.colors.surfaceInset};
  border-inline-start: 3px solid
    ${({ theme, $tone }) =>
      $tone === 'error' ? theme.colors.error : $tone === 'warning' ? theme.colors.warning : 'transparent'};
`;

const RowTitle = styled.div`
  font-weight: ${({ theme }) => theme.typography.fontWeight.medium};
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
`;

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

const ProjectExecutivePage: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const { t } = useLocale();

  const { data, isLoading } = useQuery({
    queryKey: ['projects', id, 'executive-dashboard'],
    queryFn: () => fetchExecutiveDashboard(id!),
    enabled: Boolean(id),
    refetchInterval: 60000,
  });

  const velocityChart = useMemo(() => {
    const history = [...(data?.velocity.history ?? [])].reverse();
    return {
      labels: history.map((h) => h.sprint_name),
      datasets: [
        {
          label: t('projects:manDay.velocity'),
          data: history.map((h) => h.velocity_md),
          borderColor: '#6366f1',
          backgroundColor: 'rgba(99, 102, 241, 0.15)',
          fill: true,
        },
      ],
    };
  }, [data, t]);

  const burndownChart = useMemo(() => {
    const bd = data?.burndown;
    if (!bd) return null;
    const labels = bd.chart_data.ideal.map((p) => p.date);
    return {
      labels,
      datasets: [
        {
          label: 'Ideal',
          data: bd.chart_data.ideal.map((p) => p.value),
          borderColor: '#94a3b8',
          borderDash: [6, 6],
          fill: false,
        },
        {
          label: 'Actual',
          data: bd.chart_data.actual.map((p) => p.value),
          borderColor: '#6366f1',
          backgroundColor: 'rgba(99, 102, 241, 0.15)',
          fill: true,
        },
      ],
    };
  }, [data]);

  const riskByStatusChart = useMemo(() => {
    const rs = data?.risk_summary;
    if (!rs) return null;
    const all: Array<[string, number]> = [
      ['Open', rs.open],
      ['Critical', rs.critical],
      ['Mitigated', rs.mitigated],
      ['Closed', rs.closed],
    ];
    const entries = all.filter(([, v]) => v > 0);
    if (entries.length === 0) return null;
    return {
      labels: entries.map(([k]) => k),
      datasets: [
        {
          label: t('projects:executive.riskByStatus'),
          data: entries.map(([, v]) => v),
          backgroundColor: ['#f59e0b', '#ef4444', '#10b981', '#94a3b8'].slice(0, entries.length),
        },
      ],
    };
  }, [data, t]);

  if (!id) return null;

  return (
    <ProjectPageShell projectId={id}>
      {() => {
        if (isLoading || !data) {
          return <PanelLoadingState label={t('projects:states.loading')} />;
        }

        const health = data.health;
        const sprintStatus = data.sprint_status;
        const forecast = data.forecast;
        const breakdown = health.breakdown;
        const sprintProgress =
          sprintStatus?.items && sprintStatus.items.total > 0
            ? Math.round((sprintStatus.items.completed / sprintStatus.items.total) * 100)
            : null;

        return (
          <Stack>
            {/* SECTION 1 — PROJECT HEALTH */}
            <PageSection title={t('projects:executive.projectHealth')}>
              <HealthGrid>
                <HealthHero variant="elevated" padding="lg">
                  <HiFlag />
                  <HealthScore $level={health.level}>
                    {health.score ?? '—'}
                  </HealthScore>
                  <StatusBadge tone={healthStatusTone(health.level)} size="md">
                    {(health.level === 'initializing' ? 'INITIALIZING' : health.level.replace('_', ' ').toUpperCase())}
                  </StatusBadge>
                  {health.message && (
                    <p style={{ margin: 0, fontSize: '0.875rem', color: 'var(--text-secondary, #64748b)' }}>
                      {health.message}
                    </p>
                  )}
                  <CompletionBar>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '0.75rem', marginBottom: 4 }}>
                      <span>{t('projects:executive.completion')}</span>
                      <span>{data.project.completion_percent}%</span>
                    </div>
                    <Track>
                      <Fill $value={data.project.completion_percent} $level={health.level} />
                    </Track>
                  </CompletionBar>
                </HealthHero>

                <ContentPanel variant="elevated" padding="lg">
                  <ChartCaption>{t('projects:executive.breakdown')}</ChartCaption>
                  {health.explanation.length > 0 ? (
                    <ExplanationList>
                      {health.explanation.map((reason, idx) => (
                        <li key={idx}>{reason}</li>
                      ))}
                    </ExplanationList>
                  ) : (
                    <p style={{ margin: 0, color: 'var(--text-secondary)' }}>
                      {t('projects:executive.noAttentionItems')}
                    </p>
                  )}
                  <div style={{ marginTop: '1.25rem' }}>
                    <ProjectsStatsGrid>
                      <StatCard
                        kpi
                        label={t('projects:executive.workCompleted')}
                        value={`${breakdown.work_items.completed}/${breakdown.work_items.total}`}
                        icon={HiCheckCircle}
                      />
                      <StatCard
                        kpi
                        label={t('projects:executive.completionRate')}
                        value={`${breakdown.work_items.completion_rate}%`}
                      />
                    </ProjectsStatsGrid>
                  </div>
                </ContentPanel>
              </HealthGrid>
            </PageSection>

            {/* SECTION 2 — SPRINT DELIVERY */}
            <PageSection title={t('projects:executive.sprintDelivery')}>
              <TwoCol>
                <Card variant="elevated" padding="lg">
                  <ChartCaption>{t('projects:executive.velocity')}</ChartCaption>
                  {velocityChart.labels.length > 0 ? (
                    <ReportChart type="line" data={velocityChart} height={240} />
                  ) : (
                    <EmptyChart>{t('projects:executive.noVelocityData')}</EmptyChart>
                  )}
                </Card>
                <Card variant="elevated" padding="lg">
                  <ChartCaption>{t('projects:executive.burndownTitle')}</ChartCaption>
                  {burndownChart ? (
                    <ReportChart type="line" data={burndownChart} height={240} />
                  ) : (
                    <EmptyChart>{t('projects:executive.noBurndownData')}</EmptyChart>
                  )}
                </Card>
              </TwoCol>

              {sprintStatus?.has_active && sprintStatus.sprint && (
                <Card variant="elevated" padding="lg" style={{ marginTop: '1.5rem' }}>
                  <ChartCaption>
                    <Link to={ROUTES.PROJECT_SPRINT(id, sprintStatus.sprint.id)}>
                      {sprintStatus.sprint.name}
                    </Link>
                    {sprintProgress != null && <span>{t('projects:executive.sprintProgress')}: {sprintProgress}%</span>}
                    {sprintStatus.health && (
                      <StatusBadge tone={healthStatusTone(sprintStatus.health.status)} size="sm">
                        {sprintStatus.health.status.replace('_', ' ')} ({sprintStatus.health.score})
                      </StatusBadge>
                    )}
                  </ChartCaption>
                  {data.capacity_utilization && (
                    <ProjectsStatsGrid style={{ marginBottom: '1rem' }}>
                      <StatCard kpi label={t('projects:executive.capacityUtilization')} value={`${data.capacity_utilization.utilization_percent}%`} />
                      <StatCard kpi label={t('projects:executive.teamCapacity')} value={`${data.capacity_utilization.assigned_md}/${data.capacity_utilization.total_capacity_md} MD`} />
                      <StatCard kpi label={t('projects:executive.overloadedMembers')} value={data.capacity_utilization.overloaded_members} accent={data.capacity_utilization.overloaded_members > 0 ? 'warning' : undefined} />
                    </ProjectsStatsGrid>
                  )}
                  <ProjectsStatsGrid>
                    <StatCard kpi label={t('projects:executive.timeElapsed')} value={`${sprintStatus.progress?.time_percent ?? 0}%`} />
                    <StatCard
                      kpi
                      label={t('projects:executive.daysLeft')}
                      value={sprintStatus.progress?.days_remaining ?? 0}
                      accent={sprintStatus.progress?.is_overdue ? 'error' : undefined}
                    />
                    <StatCard
                      kpi
                      label={t('projects:executive.itemsComplete')}
                      value={`${sprintStatus.items?.completed ?? 0}/${sprintStatus.items?.total ?? 0}`}
                    />
                  </ProjectsStatsGrid>
                  {sprintStatus.health?.breakdown &&
                    Object.keys(sprintStatus.health.breakdown).length > 0 && (
                      <div style={{ marginTop: '1.25rem' }}>
                        <SprintHealthBreakdown
                          health={{
                            score: sprintStatus.health.score,
                            status: sprintStatus.health.status,
                            classification:
                              sprintStatus.health.classification ?? sprintStatus.health.status,
                            breakdown: sprintStatus.health.breakdown,
                            recommendations: sprintStatus.health.recommendations ?? [],
                          }}
                        />
                      </div>
                    )}
                </Card>
              )}
            </PageSection>

            {/* SECTION 3 — RISKS & DEPENDENCIES */}
            <PageSection title={t('projects:executive.risksAndDependencies')}>
              <TwoCol>
                <Card variant="elevated" padding="lg">
                  <ProjectsStatsGrid>
                    <StatCard
                      kpi
                      label={t('projects:executive.openRisks')}
                      value={data.risk_summary.open}
                      icon={HiExclamation}
                      accent={data.risk_summary.critical > 0 ? 'error' : 'warning'}
                    />
                    <StatCard
                      kpi
                      label={t('projects:executive.criticalRisks')}
                      value={data.risk_summary.critical}
                      accent="error"
                    />
                    <StatCard
                      kpi
                      label={t('projects:executive.blockedWork')}
                      value={data.blocked_work.count}
                      accent={data.blocked_work.count > 0 ? 'warning' : undefined}
                    />
                    <StatCard
                      kpi
                      label={t('projects:executive.dependencies')}
                      value={data.open_dependencies.count}
                      accent={data.open_dependencies.count > 0 ? 'warning' : undefined}
                    />
                  </ProjectsStatsGrid>
                  <div style={{ marginTop: '1rem' }}>
                    <Link to={ROUTES.PROJECT_RISKS(id)}>{t('projects:executive.viewAllRisks')} →</Link>
                  </div>
                </Card>
                <Card variant="elevated" padding="lg">
                  <ChartCaption>{t('projects:executive.riskByStatus')}</ChartCaption>
                  {riskByStatusChart ? (
                    <ReportChart type="doughnut" data={riskByStatusChart} height={240} />
                  ) : (
                    <EmptyChart>{t('projects:executive.noRiskData')}</EmptyChart>
                  )}
                </Card>
              </TwoCol>
            </PageSection>

            {/* SECTION 4 — FORECAST */}
            <PageSection title={t('projects:executive.forecast')}>
              <TwoCol>
                <Card variant="elevated" padding="lg">
                  <ChartCaption>{t('projects:executive.forecast')}</ChartCaption>
                  {forecast.can_forecast ? (
                    <>
                      <ForecastDate>{forecast.forecast_date}</ForecastDate>
                      <ForecastMeta>
                        {t('projects:executive.basedOn', {
                          work: forecast.remaining_work_md,
                          velocity: forecast.average_velocity_md,
                        })}
                      </ForecastMeta>
                      {data.forecast_accuracy?.can_calculate && (
                        <ForecastMeta>
                          {t('projects:executive.forecastAccuracy', {
                            percent: data.forecast_accuracy.average_accuracy_percent,
                          })}
                        </ForecastMeta>
                      )}
                      {forecast.days_variance != null && (
                        <div style={{ marginTop: '1rem' }}>
                          <StatusBadge tone={forecast.is_late ? 'error' : 'success'} size="sm">
                            {forecast.is_late
                              ? t('projects:executive.forecastLate', { days: Math.abs(forecast.days_variance) })
                              : t('projects:executive.forecastOnTime', { days: Math.abs(forecast.days_variance) })}
                          </StatusBadge>
                        </div>
                      )}
                    </>
                  ) : (
                    <EmptyChart>{forecast.reason}</EmptyChart>
                  )}

                  <div style={{ marginTop: '1.5rem' }}>
                    <ChartCaption>{t('projects:executive.upcomingMilestones')}</ChartCaption>
                    {data.upcoming_milestones.length > 0 ? (
                      <ListStack>
                        {data.upcoming_milestones.slice(0, 4).map((m) => (
                          <Row key={m.id} $tone={m.is_overdue ? 'error' : m.days_until <= 7 ? 'warning' : 'default'}>
                            <div>
                              <RowTitle>{m.name}</RowTitle>
                              <RowDesc>{m.due_date}</RowDesc>
                            </div>
                            <StatusBadge tone={m.is_overdue ? 'error' : m.days_until <= 7 ? 'warning' : 'active'} size="sm">
                              {m.is_overdue
                                ? t('projects:executive.overdue')
                                : t('projects:executive.daysUntil', { days: m.days_until })}
                            </StatusBadge>
                          </Row>
                        ))}
                      </ListStack>
                    ) : (
                      <p style={{ margin: 0, color: 'var(--text-secondary)' }}>
                        {t('projects:executive.noMilestones')}
                      </p>
                    )}
                  </div>
                </Card>

                <Card variant="elevated" padding="lg">
                  <ChartCaption>{t('projects:executive.attentionRequired')}</ChartCaption>
                  {data.attention_items.length > 0 ? (
                    <ListStack>
                      {data.attention_items.map((item, idx) => (
                        <Row key={idx} $tone={item.severity === 'high' ? 'error' : 'warning'}>
                          <div style={{ display: 'flex', gap: '0.5rem' }}>
                            <span style={{ color: item.severity === 'high' ? 'var(--error)' : 'var(--warning)' }}>
                              {item.severity === 'high' ? <HiExclamation /> : <HiLightningBolt />}
                            </span>
                            <div>
                              <RowTitle>{item.title}</RowTitle>
                              <RowDesc>{item.description} • {item.action}</RowDesc>
                            </div>
                          </div>
                        </Row>
                      ))}
                    </ListStack>
                  ) : (
                    <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', color: 'var(--success)' }}>
                      <HiCheckCircle />
                      {t('projects:executive.noAttentionItems')}
                    </div>
                  )}
                </Card>
              </TwoCol>
            </PageSection>

            {/* SECTION 5 — DELIVERY INSIGHTS */}
            <PageSection title={t('projects:executive.deliveryInsights')}>
              <TwoCol>
                <Card variant="elevated" padding="lg">
                  <ChartCaption>{t('projects:executive.capacityBottlenecks')}</ChartCaption>
                  {data.capacity_bottlenecks?.has_bottlenecks ? (
                    <ListStack>
                      {data.capacity_bottlenecks.overloaded_members.map((m) => (
                        <Row key={m.user_id} $tone="warning">
                          <div>
                            <RowTitle>{m.name}</RowTitle>
                            <RowDesc>{m.utilization_percent}% · {m.overload_md} MD overload</RowDesc>
                          </div>
                        </Row>
                      ))}
                    </ListStack>
                  ) : (
                    <EmptyChart>{t('projects:executive.noBottlenecks')}</EmptyChart>
                  )}
                </Card>
                <Card variant="elevated" padding="lg">
                  <ChartCaption>{t('projects:executive.criticalDependencies')}</ChartCaption>
                  {data.critical_dependencies?.critical_count > 0 ? (
                    <ListStack>
                      {data.critical_dependencies.dependencies.slice(0, 5).map((dep) => (
                        <Row key={dep.id} $tone="error">
                          <div>
                            <RowTitle>{dep.blocker.subject} → {dep.blocked.subject}</RowTitle>
                            <RowDesc>{dep.type}</RowDesc>
                          </div>
                        </Row>
                      ))}
                    </ListStack>
                  ) : (
                    <EmptyChart>{t('projects:executive.noCriticalDependencies')}</EmptyChart>
                  )}
                </Card>
              </TwoCol>
              <TwoCol style={{ marginTop: '1.5rem' }}>
                <Card variant="elevated" padding="lg">
                  <ChartCaption>{t('projects:executive.blockedWorkList')}</ChartCaption>
                  {data.blocked_work.items.length > 0 ? (
                    <ListStack>
                      {data.blocked_work.items.slice(0, 5).map((item) => (
                        <Row key={item.id}>
                          <div>
                            <RowTitle>{item.subject}</RowTitle>
                            <RowDesc>{item.ticket_number}</RowDesc>
                          </div>
                        </Row>
                      ))}
                    </ListStack>
                  ) : (
                    <EmptyChart>{t('projects:executive.noBlockedWork')}</EmptyChart>
                  )}
                </Card>
                <Card variant="elevated" padding="lg">
                  <ChartCaption>{t('projects:executive.upcomingDeadlines')}</ChartCaption>
                  {data.upcoming_deadlines?.length > 0 ? (
                    <ListStack>
                      {data.upcoming_deadlines.slice(0, 5).map((d, idx) => (
                        <Row key={`${d.type}-${d.name}-${idx}`} $tone={d.days_until <= 7 ? 'warning' : 'default'}>
                          <div>
                            <RowTitle>{d.name}</RowTitle>
                            <RowDesc>{d.type} · {d.due_date}</RowDesc>
                          </div>
                          <StatusBadge tone={d.days_until <= 7 ? 'warning' : 'active'} size="sm">
                            {d.days_until}d
                          </StatusBadge>
                        </Row>
                      ))}
                    </ListStack>
                  ) : (
                    <EmptyChart>{t('projects:executive.noUpcomingDeadlines')}</EmptyChart>
                  )}
                </Card>
              </TwoCol>
              {data.projects_at_risk?.is_at_risk && (
                <Card variant="elevated" padding="lg" style={{ marginTop: '1.5rem' }}>
                  <ChartCaption>{t('projects:executive.projectRiskIndicators')}</ChartCaption>
                  <ListStack>
                    {data.projects_at_risk.indicators.map((ind, idx) => (
                      <Row key={idx} $tone={ind.severity === 'high' ? 'error' : 'warning'}>
                        <RowTitle>{ind.message}</RowTitle>
                      </Row>
                    ))}
                  </ListStack>
                </Card>
              )}
            </PageSection>
          </Stack>
        );
      }}
    </ProjectPageShell>
  );
};

export default ProjectExecutivePage;
