import React, { useMemo, useState } from 'react';
import { useParams } from 'react-router-dom';
import styled from 'styled-components';
import toast from 'react-hot-toast';
import { Button, Input, Select, StatusBadge } from '@/shared/components/ui';
import { ContentPanel } from '@/shared/components/layout/ContentPanel';
import { EmptyStateCard } from '@/features/onboarding/components/EmptyStateCard';
import { StatCard } from '@/features/dashboard/components/StatCard';
import { PanelLoadingState } from '@/shared/components/ui/PageState';
import { ProjectPageShell } from '@/features/projects/components/ProjectPageShell';
import { useProject } from '@/features/projects/hooks/useProject';
import { useProjectPermissions } from '@/features/projects/hooks/useProjectPermissions';
import {
  AgileContentSection,
  AgileFiltersSection,
  AgileMetricsSection,
  ProjectsStatsGrid,
} from '@/features/projects/components/projectsLayout';
import { useProjectSprints } from '@/features/projects/hooks/useProjectSprints';
import {
  useCapacityPlanning,
  useSyncCapacityAllocations,
} from '@/features/projects/hooks/useSprintTeamCapacity';
import { useLocale } from '@/app/providers/LocaleProvider';
import { HiExclamation, HiTrendingUp, HiUserGroup } from 'react-icons/hi';

const CapacityPanel = styled(ContentPanel)`
  overflow: hidden;
`;

const CapacityPanelHeader = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: ${({ theme }) => theme.spacing[4]};
  flex-wrap: wrap;
  margin-bottom: ${({ theme }) => theme.spacing[5]};
`;

const CapacityPanelTitle = styled.h2`
  margin: 0;
  font-size: ${({ theme }) => theme.typography.fontSize.lg};
  font-weight: ${({ theme }) => theme.typography.fontWeight.semibold};
  color: ${({ theme }) => theme.colors.text.primary};
`;

const TableWrap = styled.div`
  overflow-x: auto;
  margin: 0 calc(-1 * ${({ theme }) => theme.layout.cardPaddingMd});
  padding: 0 ${({ theme }) => theme.layout.cardPaddingMd};
`;

const CapacityTable = styled.table`
  width: 100%;
  min-width: 52rem;
  border-collapse: separate;
  border-spacing: 0;
`;

const Th = styled.th`
  padding: ${({ theme }) => `${theme.spacing[3]} ${theme.spacing[4]}`};
  text-align: start;
  font-size: ${({ theme }) => theme.typography.fontSize.xs};
  font-weight: ${({ theme }) => theme.typography.fontWeight.semibold};
  letter-spacing: ${({ theme }) => theme.typography.letterSpacing.wide};
  text-transform: uppercase;
  color: ${({ theme }) => theme.colors.text.tertiary};
  border-bottom: 1px solid ${({ theme }) => theme.colors.borderSoft};
  background: ${({ theme }) => theme.colors.surfaceInset};
`;

const Td = styled.td`
  padding: ${({ theme }) => `${theme.spacing[4]} ${theme.spacing[4]}`};
  vertical-align: middle;
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  color: ${({ theme }) => theme.colors.text.primary};
  border-bottom: 1px solid ${({ theme }) => theme.colors.borderSoft};
`;

const BodyRow = styled.tr`
  transition: background ${({ theme }) => theme.transitions.fast};

  &:hover {
    background: ${({ theme }) => theme.colors.surfaceInset};
  }

  &:last-child td {
    border-bottom: none;
  }
`;

const MemberCell = styled.div`
  display: flex;
  align-items: center;
  gap: ${({ theme }) => theme.spacing[3]};
  min-width: 10rem;
`;

const Avatar = styled.span`
  flex-shrink: 0;
  width: 36px;
  height: 36px;
  border-radius: ${({ theme }) => theme.borderRadius.full};
  display: inline-flex;
  align-items: center;
  justify-content: center;
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  font-weight: ${({ theme }) => theme.typography.fontWeight.semibold};
  color: ${({ theme }) => theme.colors.primary};
  background: ${({ theme }) => theme.colors.primary}14;
`;

const MemberName = styled.strong`
  display: block;
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
`;

const UtilBlock = styled.div`
  display: flex;
  flex-direction: column;
  gap: ${({ theme }) => theme.spacing[1]};
  min-width: 6rem;
`;

const UtilBar = styled.div`
  height: 6px;
  border-radius: ${({ theme }) => theme.borderRadius.full};
  background: ${({ theme }) => theme.colors.borderSoft};
  overflow: hidden;
`;

const UtilFill = styled.div<{ $pct: number; $health: string }>`
  height: 100%;
  width: ${({ $pct }) => Math.min(100, Math.max(0, $pct))}%;
  border-radius: inherit;
  background: ${({ theme, $health }) => {
    if ($health === 'green') return theme.colors.status.success.text;
    if ($health === 'yellow' || $health === 'orange') return theme.colors.status.warning.text;
    return theme.colors.status.error.text;
  }};
  transition: width ${({ theme }) => theme.transitions.fast};
`;

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

const NumericCell = styled.strong`
  font-variant-numeric: tabular-nums;
`;

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

const healthTone = (health: string) => {
  if (health === 'green') return 'success' as const;
  if (health === 'yellow' || health === 'orange') return 'warning' as const;
  return 'error' as const;
};

const recLabel = (key: string | undefined, t: (k: string) => string) => {
  if (!key) return '—';
  const path = `projects:capacity.rec.${key}`;
  const label = t(path);
  return label === path ? key : label;
};

const memberInitials = (name: string) =>
  name
    .split(/\s+/)
    .slice(0, 2)
    .map((part) => part[0]?.toUpperCase() ?? '')
    .join('');

const ProjectCapacityPage: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const { t } = useLocale();
  const { data: project } = useProject(id);
  const { readOnly, canPlanCapacity } = useProjectPermissions(project);
  const capacityEditable = canPlanCapacity && !readOnly;
  const { data: sprints } = useProjectSprints(id);
  const planned = useMemo(
    () => sprints?.filter((s) => !['completed', 'cancelled', 'archived'].includes(s.status)) ?? [],
    [sprints],
  );
  const [sprintId, setSprintId] = useState('');
  const activeSprintId = sprintId || planned.find((s) => s.status === 'active')?.id || planned[0]?.id;
  const { data, isLoading } = useCapacityPlanning(id, activeSprintId);
  const syncMutation = useSyncCapacityAllocations(id ?? '');
  const [draft, setDraft] = useState<Record<string, string>>({});

  React.useEffect(() => {
    if (!data?.team) {
      return;
    }
    const next: Record<string, string> = {};
    data.team.forEach((row) => {
      next[row.user_id] = String(row.capacity_md);
    });
    setDraft(next);
  }, [data?.team, activeSprintId]);

  const handleSave = () => {
    if (!id || !activeSprintId || !data?.team) {
      return;
    }
    const invalid = data.team.some((row) => {
      const v = Number(draft[row.user_id] ?? row.capacity_md);
      return Number.isNaN(v) || v < 0;
    });
    if (invalid) {
      toast.error(t('projects:capacity.saveFailed'));
      return;
    }
    syncMutation.mutate(
      {
        sprintId: activeSprintId,
        allocations: data.team.map((row) => ({
          user_id: row.user_id,
          capacity_md: Number(draft[row.user_id] ?? row.capacity_md),
        })),
      },
      {
        onSuccess: () => toast.success(t('projects:capacity.saved')),
        onError: () => toast.error(t('projects:capacity.saveFailed')),
      },
    );
  };

  return (
    <ProjectPageShell projectId={id}>
      {() => (
        <>
          <AgileFiltersSection>
            <Select
              label={t('projects:capacity.sprint')}
              value={activeSprintId ?? ''}
              onChange={(e) => setSprintId(e.target.value)}
              options={planned.map((s) => ({ value: s.id, label: s.name }))}
              fullWidth
            />
          </AgileFiltersSection>

          {!activeSprintId ? (
            <EmptyStateCard
              icon="📊"
              title={t('projects:capacity.selectSprintEmpty')}
              description={t('projects:capacity.explainBody')}
            />
          ) : isLoading || !data ? (
            <PanelLoadingState label={t('projects:states.loading')} />
          ) : !data.team || data.team.length === 0 ? (
            <EmptyStateCard
              icon="👥"
              title={t('projects:capacity.noParticipantsEmpty')}
              description={data.message ?? t('projects:capacity.noParticipantsHint')}
            />
          ) : (
            <>
              <ContentPanel variant="elevated" padding="lg">
                <strong>{t('projects:capacity.explainTitle')}</strong>
                <p style={{ margin: '0.5rem 0 0', fontSize: '0.875rem' }}>
                  {t('projects:capacity.explainBody')}
                </p>
                <strong style={{ display: 'block', marginTop: '1rem' }}>
                  {t('projects:capacity.legendTitle')}
                </strong>
                <ExplainList>
                  <li>{t('projects:capacity.legendGreen')}</li>
                  <li>{t('projects:capacity.legendYellow')}</li>
                  <li>{t('projects:capacity.legendOrange')}</li>
                  <li>{t('projects:capacity.legendRed')}</li>
                </ExplainList>
              </ContentPanel>

              <AgileMetricsSection>
                <ProjectsStatsGrid>
                  <StatCard
                    kpi
                    label={t('projects:capacity.totalCapacity')}
                    value={`${data.metrics.total_capacity_md} MD`}
                    icon={HiUserGroup}
                  />
                  <StatCard
                    kpi
                    label={t('projects:capacity.assigned')}
                    value={`${data.metrics.assigned_md} MD`}
                    icon={HiTrendingUp}
                  />
                  <StatCard
                    kpi
                    label={t('projects:capacity.remaining')}
                    value={`${data.metrics.remaining_md} MD`}
                    icon={HiTrendingUp}
                  />
                  <StatCard
                    kpi
                    label={t('projects:capacity.overallocated')}
                    value={data.metrics.overallocated_users}
                    icon={HiExclamation}
                  />
                </ProjectsStatsGrid>
              </AgileMetricsSection>

              <AgileContentSection>
                <CapacityPanel variant="elevated" padding="md">
                  <CapacityPanelHeader>
                    <CapacityPanelTitle>{t('projects:nav.capacity')}</CapacityPanelTitle>
                    {capacityEditable && (
                      <Button
                        type="button"
                        variant="primary"
                        loading={syncMutation.isPending}
                        onClick={handleSave}
                      >
                        {t('projects:capacity.save')}
                      </Button>
                    )}
                  </CapacityPanelHeader>
                  <TableWrap>
                    <CapacityTable>
                      <thead>
                        <tr>
                          <Th>{t('projects:capacity.member')}</Th>
                          <Th>{t('projects:capacity.role')}</Th>
                          <Th>{t('projects:capacity.capacity')}</Th>
                          <Th>{t('projects:capacity.assignedCol')}</Th>
                          <Th>{t('projects:capacity.remainingCol')}</Th>
                          <Th>{t('projects:capacity.utilization')}</Th>
                          <Th>{t('projects:capacity.healthLabel')}</Th>
                          <Th>{t('projects:capacity.recommendation')}</Th>
                        </tr>
                      </thead>
                      <tbody>
                        {data.team.map((row) => (
                          <BodyRow key={row.user_id}>
                            <Td>
                              <MemberCell>
                                <Avatar aria-hidden>{memberInitials(row.name)}</Avatar>
                                <MemberName>{row.name}</MemberName>
                              </MemberCell>
                            </Td>
                            <Td>{row.role ?? '—'}</Td>
                            <Td>
                              <Input
                                type="number"
                                min={0}
                                step={0.5}
                                value={draft[row.user_id] ?? String(row.capacity_md)}
                                disabled={!capacityEditable}
                                onChange={(e) =>
                                  setDraft((prev) => ({ ...prev, [row.user_id]: e.target.value }))
                                }
                              />
                            </Td>
                            <Td>
                              <NumericCell>{row.assigned_md} MD</NumericCell>
                            </Td>
                            <Td>
                              <NumericCell>
                                {row.remaining_md < 0
                                  ? `+${Math.abs(row.remaining_md)} MD ${t('projects:capacity.overload')}`
                                  : row.remaining_md > 0
                                    ? `-${row.remaining_md} MD ${t('projects:capacity.available')}`
                                    : '0 MD'}
                              </NumericCell>
                            </Td>
                            <Td>
                              <UtilBlock>
                                <UtilBar>
                                  <UtilFill
                                    $pct={row.utilization_percent}
                                    $health={row.health}
                                  />
                                </UtilBar>
                                <UtilLabel>{row.utilization_percent}%</UtilLabel>
                              </UtilBlock>
                            </Td>
                            <Td>
                              <StatusBadge tone={healthTone(row.health)}>
                                {t(`projects:capacity.health.${row.health}`)}
                              </StatusBadge>
                            </Td>
                            <Td>{recLabel(row.recommendation, t)}</Td>
                          </BodyRow>
                        ))}
                      </tbody>
                    </CapacityTable>
                  </TableWrap>
                </CapacityPanel>
              </AgileContentSection>
            </>
          )}
        </>
      )}
    </ProjectPageShell>
  );
};

export default ProjectCapacityPage;
