import React, { useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { HiPlus } from 'react-icons/hi';
import { Button } from '@/shared/components/ui';
import { PageSection } from '@/shared/components/layout/PageSection';
import { PanelLoadingState, PanelEmpty } from '@/shared/components/ui/PageState';
import { ProjectPageShell } from '@/features/projects/components/ProjectPageShell';
import { CreateSprintModal } from '@/features/projects/components/CreateSprintModal';
import { EditSprintModal } from '@/features/projects/components/EditSprintModal';
import { ClosureChecklistModal } from '@/features/projects/components/ClosureChecklistModal';
import { SprintGridCard } from '@/features/projects/components/SprintGridCard';
import {
  AgileActionsSection,
  AgileContentSection,
  InlineActions,
  SprintCardsGrid,
} from '@/features/projects/components/projectsLayout';
import { ROUTES } from '@/shared/constants/routes';
import { useProjectSprints } from '@/features/projects/hooks/useProjectSprints';
import { useProjectMutations } from '@/features/projects/hooks/useProjectMutations';
import { useProjectPermissions } from '@/features/projects/hooks/useProjectPermissions';
import { fetchSprintClosureChecklist } from '@/features/projects/services/projectService';
import { useLocale } from '@/app/providers/LocaleProvider';
import type { ProjectSprint, ProjectSummary } from '@/features/projects/types/project.types';

const ProjectSprintsContent: React.FC<{ project: ProjectSummary }> = ({ project }) => {
  const { t } = useLocale();
  const navigate = useNavigate();
  const { data: sprints, isLoading } = useProjectSprints(project.id);
  const {
    startSprintMutation,
    closeSprintMutation,
    cancelSprintMutation,
    archiveSprintMutation,
    restoreSprintMutation,
    deleteSprintMutation,
    duplicateSprintMutation,
  } = useProjectMutations();
  const { canManage } = useProjectPermissions(project);
  const [editingSprint, setEditingSprint] = useState<ProjectSprint | null>(null);
  const [closingSprintId, setClosingSprintId] = useState<string | null>(null);
  const [createOpen, setCreateOpen] = useState(false);

  const lifecycleActionPending =
    cancelSprintMutation.isPending ||
    archiveSprintMutation.isPending ||
    restoreSprintMutation.isPending ||
    deleteSprintMutation.isPending ||
    duplicateSprintMutation.isPending;

  return (
    <>
      {canManage && (
        <AgileActionsSection>
          <InlineActions>
            <Button
              type="button"
              variant="primary"
              size="lg"
              icon={<HiPlus aria-hidden />}
              onClick={() => setCreateOpen(true)}
            >
              {t('projects:sprints.createAction')}
            </Button>
            <Button
              type="button"
              variant="secondary"
              size="lg"
              onClick={() => navigate(ROUTES.PROJECT_SPRINT_PLANNING(project.id))}
            >
              {t('projects:sprints.planAction')}
            </Button>
          </InlineActions>
        </AgileActionsSection>
      )}

      <AgileContentSection>
        <PageSection title={t('projects:nav.sprints')}>
          {isLoading ? (
            <PanelLoadingState label={t('projects:states.loading')} />
          ) : (sprints?.length ?? 0) === 0 ? (
            <>
              <PanelEmpty
                title={t('projects:sprints.empty')}
                hint={t('projects:sprints.emptyHint')}
              />
              {canManage && (
                <AgileActionsSection>
                  <InlineActions>
                    <Button
                      type="button"
                      variant="primary"
                      size="lg"
                      icon={<HiPlus aria-hidden />}
                      onClick={() => setCreateOpen(true)}
                    >
                      {t('projects:sprints.emptyAction')}
                    </Button>
                  </InlineActions>
                </AgileActionsSection>
              )}
            </>
          ) : (
            <SprintCardsGrid>
              {sprints!.map((sprint) => (
                <SprintGridCard
                  key={sprint.id}
                  sprint={sprint}
                  projectId={project.id}
                  variant="simple"
                  startLoading={startSprintMutation.isPending}
                  closeLoading={closeSprintMutation.isPending}
                  actionLoading={lifecycleActionPending}
                  onEdit={canManage ? () => setEditingSprint(sprint) : undefined}
                  onStart={
                    canManage && sprint.status === 'planned'
                      ? () =>
                          startSprintMutation.mutate({
                            projectId: project.id,
                            sprintId: sprint.id,
                          })
                      : undefined
                  }
                  onClose={
                    canManage && sprint.status === 'active'
                      ? () => setClosingSprintId(sprint.id)
                      : undefined
                  }
                  onCancel={
                    canManage
                      ? () =>
                          cancelSprintMutation.mutate({
                            projectId: project.id,
                            sprintId: sprint.id,
                          })
                      : undefined
                  }
                  onArchive={
                    canManage
                      ? () =>
                          archiveSprintMutation.mutate({
                            projectId: project.id,
                            sprintId: sprint.id,
                          })
                      : undefined
                  }
                  onRestore={
                    canManage
                      ? () =>
                          restoreSprintMutation.mutate({
                            projectId: project.id,
                            sprintId: sprint.id,
                          })
                      : undefined
                  }
                  onDelete={
                    canManage
                      ? () => {
                          if (!sprint.lifecycle?.can_delete) return;
                          if (window.confirm(t('projects:sprints.deleteConfirm'))) {
                            deleteSprintMutation.mutate({
                              projectId: project.id,
                              sprintId: sprint.id,
                            });
                          }
                        }
                      : undefined
                  }
                  onDuplicate={
                    canManage
                      ? () =>
                          duplicateSprintMutation.mutate({
                            projectId: project.id,
                            sprintId: sprint.id,
                          })
                      : undefined
                  }
                />
              ))}
            </SprintCardsGrid>
          )}
        </PageSection>
      </AgileContentSection>

      <CreateSprintModal
        projectId={project.id}
        isOpen={createOpen}
        onClose={() => setCreateOpen(false)}
      />

      <EditSprintModal
        projectId={project.id}
        sprint={editingSprint}
        isOpen={editingSprint !== null}
        onClose={() => setEditingSprint(null)}
      />

      <ClosureChecklistModal
        open={closingSprintId !== null}
        title={t('projects:closure.sprintTitle')}
        loadChecklist={() => fetchSprintClosureChecklist(project.id, closingSprintId!)}
        confirmLabel={t('projects:closure.sprintConfirm')}
        overrideLabel={t('projects:closure.sprintOverride')}
        emptyLabel={t('projects:closure.sprintEmpty')}
        onCancel={() => setClosingSprintId(null)}
        onConfirm={(overrideReason) => {
          if (!closingSprintId) return;
          closeSprintMutation.mutate(
            {
              projectId: project.id,
              sprintId: closingSprintId,
              closureOverrideReason: overrideReason,
            },
            { onSuccess: () => setClosingSprintId(null) },
          );
        }}
      />
    </>
  );
};

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

  return (
    <ProjectPageShell projectId={id}>
      {({ project }) => <ProjectSprintsContent project={project} />}
    </ProjectPageShell>
  );
};

export default ProjectSprintsPage;
