import React, { useState, useMemo } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import styled from 'styled-components';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import toast from 'react-hot-toast';
import { Button, StatusBadge } from '@/shared/components/ui';
import { ContentPanel } from '@/shared/components/layout/ContentPanel';
import { EmptyStateCard } from '@/features/onboarding/components/EmptyStateCard';
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 { useProjectMembers } from '@/features/projects/hooks/useProjectMembers';
import { AgileContentSection } from '@/features/projects/components/projectsLayout';
import { useProjectSprints } from '@/features/projects/hooks/useProjectSprints';
import { useCapacityPlanning } from '@/features/projects/hooks/useSprintTeamCapacity';
import { useLocale } from '@/app/providers/LocaleProvider';
import { HiChevronDown, HiChevronRight, HiUserAdd } from 'react-icons/hi';
import { ROUTES } from '@/shared/constants/routes';
import { TeamExecutiveAnalytics } from '@/features/projects/components/TeamExecutiveAnalytics';
import { AddProjectMemberModal } from '@/features/projects/components/AddProjectMemberModal';
import { projectMembersQueryKey } from '@/features/projects/hooks/useProjectMembers';
import { removeProjectMember } from '@/features/projects/services/projectService';
import type { ProjectMemberRole } from '@/features/projects/types/project.types';

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

const TeamPanelHeader = 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 TeamPanelTitle = 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 MembersTable = styled.table`
  width: 100%;
  min-width: 60rem;
  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: 12rem;
`;

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 MemberInfo = styled.div`
  display: flex;
  flex-direction: column;
  gap: 2px;
`;

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

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

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: 'green' | 'yellow' | 'red' }>`
  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') 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.span`
  font-variant-numeric: tabular-nums;
`;

const MoreViewsToggle = styled.button`
  display: inline-flex;
  align-items: center;
  gap: ${({ theme }) => theme.spacing[2]};
  margin-bottom: ${({ theme }) => theme.spacing[5]};
  padding: 0;
  border: none;
  background: none;
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  font-weight: ${({ theme }) => theme.typography.fontWeight.medium};
  color: ${({ theme }) => theme.colors.primary};
  cursor: pointer;
`;

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

const roleLabel = (role: ProjectMemberRole): string => {
  const labels: Record<ProjectMemberRole, string> = {
    owner: 'Owner',
    manager: 'Manager',
    member: 'Member',
    viewer: 'Viewer',
  };
  return labels[role] || role;
};

const roleTone = (role: ProjectMemberRole) => {
  if (role === 'owner') return 'active' as const;
  if (role === 'manager') return 'inProgress' as const;
  if (role === 'member') return 'success' as const;
  return 'draft' as const;
};

const healthFromUtilization = (util: number): 'green' | 'yellow' | 'red' => {
  if (util > 100) return 'red';
  if (util >= 80) return 'yellow';
  return 'green';
};

const statusFromUtilization = (util: number): string => {
  if (util > 100) return 'Overloaded';
  if (util >= 80) return 'Near Capacity';
  if (util > 0) return 'Available';
  return 'Unallocated';
};

const statusTone = (util: number) => {
  if (util > 100) return 'error' as const;
  if (util >= 80) return 'warning' as const;
  return 'success' as const;
};

type ViewTab = 'members' | 'workload' | 'analytics';

const ProjectTeamPage: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { t } = useLocale();
  const { data: project } = useProject(id);
  const { canManage, readOnly } = useProjectPermissions(project);
  const queryClient = useQueryClient();
  const { data: members, isLoading: membersLoading } = useProjectMembers(id);
  const { data: sprints } = useProjectSprints(id);
  const [activeTab, setActiveTab] = useState<ViewTab>('members');
  const [moreViewsOpen, setMoreViewsOpen] = useState(false);
  const [addMemberOpen, setAddMemberOpen] = useState(false);

  const removeMemberMutation = useMutation({
    mutationFn: (userId: string) => removeProjectMember(id!, userId),
    onSuccess: () => {
      toast.success(t('projects:team.memberRemoved'));
      void queryClient.invalidateQueries({ queryKey: projectMembersQueryKey(id!) });
    },
    onError: () => toast.error(t('projects:team.removeFailed')),
  });

  const activeSprint = useMemo(
    () => sprints?.find((s) => s.status === 'active'),
    [sprints],
  );

  const { data: capacityData, isLoading: capacityLoading } = useCapacityPlanning(
    id,
    activeSprint?.id,
  );

  const memberWorkload = useMemo(() => {
    if (!members || !capacityData?.team) return [];

    const capacityMap = new Map(
      capacityData.team.map((t) => [t.user_id, t]),
    );

    return members.map((member) => {
      const capacity = capacityMap.get(member.user_id);
      return {
        ...member,
        capacity_md: capacity?.capacity_md ?? 0,
        assigned_md: capacity?.assigned_md ?? 0,
        remaining_md: capacity?.remaining_md ?? 0,
        utilization_percent: capacity?.utilization_percent ?? 0,
        health: capacity?.health ?? 'green',
        isParticipant: Boolean(capacity),
      };
    });
  }, [members, capacityData]);

  const isLoading =
    membersLoading || (moreViewsOpen && activeTab !== 'members' && activeSprint && capacityLoading);
  const existingMemberIds = useMemo(
    () => (members ?? []).map((member) => member.user_id),
    [members],
  );

  const handleRemoveMember = (userId: string) => {
    if (!window.confirm(t('projects:team.removeConfirm'))) {
      return;
    }
    removeMemberMutation.mutate(userId);
  };

  return (
    <ProjectPageShell projectId={id}>
      {() => (
        <>
          <AgileContentSection>
            <TeamPanel variant="elevated" padding="md">
              <TeamPanelHeader>
                <TeamPanelTitle>{t('projects:team.membersTitle')}</TeamPanelTitle>
                  {canManage && !readOnly && activeTab === 'members' && (
                    <Button
                      type="button"
                      variant="primary"
                      icon={<HiUserAdd />}
                      onClick={() => setAddMemberOpen(true)}
                    >
                      {t('projects:team.addMember')}
                    </Button>
                  )}
              </TeamPanelHeader>

              <MoreViewsToggle type="button" onClick={() => setMoreViewsOpen((v) => !v)}>
                {moreViewsOpen ? <HiChevronDown aria-hidden /> : <HiChevronRight aria-hidden />}
                {t('projects:team.moreViews')}
              </MoreViewsToggle>
              {moreViewsOpen && (
                <div style={{ display: 'flex', gap: '0.5rem', marginBottom: '1.25rem', flexWrap: 'wrap' }}>
                  <Button
                    type="button"
                    variant={activeTab === 'workload' ? 'primary' : 'secondary'}
                    size="sm"
                    onClick={() => setActiveTab('workload')}
                  >
                    {t('projects:team.workloadTab')}
                  </Button>
                  <Button
                    type="button"
                    variant={activeTab === 'analytics' ? 'primary' : 'secondary'}
                    size="sm"
                    onClick={() => setActiveTab('analytics')}
                  >
                    {t('projects:team.analyticsTab')}
                  </Button>
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    onClick={() => id && navigate(ROUTES.PROJECT_WORKLOAD(id))}
                  >
                    {t('projects:nav.workload')}
                  </Button>
                </div>
              )}

              {activeTab === 'analytics' && moreViewsOpen ? (
                <TeamExecutiveAnalytics projectId={id!} />
              ) : isLoading ? (
                <PanelLoadingState label={t('projects:states.loading')} />
              ) : !members || members.length === 0 ? (
                <EmptyStateCard
                  icon="👥"
                  title={t('projects:team.emptyTitle')}
                  description={t('projects:team.emptyDescription')}
                  actionLabel={canManage && !readOnly ? t('projects:team.addMember') : undefined}
                  onAction={canManage && !readOnly ? () => setAddMemberOpen(true) : undefined}
                />
              ) : activeTab === 'members' || !moreViewsOpen ? (
                <TableWrap>
                  <MembersTable>
                    <thead>
                      <tr>
                        <Th>{t('projects:team.col.member')}</Th>
                        <Th>{t('projects:team.col.projectRole')}</Th>
                        <Th>{t('projects:team.col.department')}</Th>
                        {canManage && !readOnly && <Th>{t('projects:team.col.actions')}</Th>}
                      </tr>
                    </thead>
                    <tbody>
                      {(members ?? []).map((member) => (
                        <BodyRow key={member.id}>
                          <Td>
                            <MemberCell>
                              <Avatar aria-hidden>
                                {memberInitials(member.user?.name ?? '')}
                              </Avatar>
                              <MemberInfo>
                                <MemberName>{member.user?.name ?? '—'}</MemberName>
                                <MemberEmail>{member.user?.email ?? '—'}</MemberEmail>
                              </MemberInfo>
                            </MemberCell>
                          </Td>
                          <Td>
                            <StatusBadge tone={roleTone(member.role)}>
                              {roleLabel(member.role)}
                            </StatusBadge>
                          </Td>
                          <Td>{project?.department?.name ?? '—'}</Td>
                          {canManage && !readOnly && (
                            <Td>
                              {member.role !== 'owner' && (
                                <Button
                                  type="button"
                                  variant="ghost"
                                  size="sm"
                                  loading={removeMemberMutation.isPending}
                                  onClick={() => handleRemoveMember(member.user_id)}
                                >
                                  {t('projects:team.remove')}
                                </Button>
                              )}
                            </Td>
                          )}
                        </BodyRow>
                      ))}
                    </tbody>
                  </MembersTable>
                </TableWrap>
              ) : activeTab === 'workload' && moreViewsOpen ? (
                <TableWrap>
                  <MembersTable>
                    <thead>
                      <tr>
                        <Th>{t('projects:team.col.member')}</Th>
                        <Th>{t('projects:team.col.assigned')}</Th>
                        <Th>{t('projects:team.col.completed')}</Th>
                        <Th>{t('projects:team.col.overdue')}</Th>
                        <Th>{t('projects:team.col.capacity')}</Th>
                        <Th>{t('projects:team.col.utilization')}</Th>
                        <Th>{t('projects:team.col.sprintParticipation')}</Th>
                        <Th>{t('projects:team.col.health')}</Th>
                      </tr>
                    </thead>
                    <tbody>
                      {memberWorkload.map((member) => (
                        <BodyRow key={member.id}>
                          <Td>
                            <MemberCell>
                              <Avatar aria-hidden>
                                {memberInitials(member.user?.name ?? '')}
                              </Avatar>
                              <MemberInfo>
                                <MemberName>{member.user?.name ?? '—'}</MemberName>
                              </MemberInfo>
                            </MemberCell>
                          </Td>
                          <Td>
                            <NumericCell>{member.assigned_md} MD</NumericCell>
                          </Td>
                          <Td>
                            <NumericCell>—</NumericCell>
                          </Td>
                          <Td>
                            <NumericCell>—</NumericCell>
                          </Td>
                          <Td>
                            <NumericCell>{member.capacity_md} MD</NumericCell>
                          </Td>
                          <Td>
                            <UtilBlock>
                              <UtilBar>
                                <UtilFill
                                  $pct={member.utilization_percent}
                                  $health={healthFromUtilization(member.utilization_percent)}
                                />
                              </UtilBar>
                              <UtilLabel>{member.utilization_percent}%</UtilLabel>
                            </UtilBlock>
                          </Td>
                          <Td>
                            <StatusBadge tone={member.isParticipant ? 'success' : 'draft'}>
                              {member.isParticipant
                                ? t('projects:team.participating')
                                : t('projects:team.notParticipating')}
                            </StatusBadge>
                          </Td>
                          <Td>
                            <StatusBadge tone={statusTone(member.utilization_percent)}>
                              {statusFromUtilization(member.utilization_percent)}
                            </StatusBadge>
                          </Td>
                        </BodyRow>
                      ))}
                    </tbody>
                  </MembersTable>
                </TableWrap>
              ) : null}
            </TeamPanel>
          </AgileContentSection>

          {project && canManage && !readOnly && (
            <AddProjectMemberModal
              projectId={project.id}
              departmentId={project.department_id}
              existingMemberIds={existingMemberIds}
              ownerUserId={project.owner_user_id}
              isOpen={addMemberOpen}
              onClose={() => setAddMemberOpen(false)}
            />
          )}
        </>
      )}
    </ProjectPageShell>
  );
};

export default ProjectTeamPage;
