import React from 'react';
import styled from 'styled-components';
import { Link, useNavigate, useParams } from 'react-router-dom';
import { isAxiosError } from 'axios';
import { HiArrowRight, HiClipboardList, HiPlus } from 'react-icons/hi';
import { useLocale } from '@/app/providers/LocaleProvider';
import { useAuthStore } from '@/features/auth/store/authStore';
import { Button, Card, Spinner } from '@/shared/components/ui';
import { ROUTES } from '@/shared/constants/routes';
import { DepartmentPortalHero } from '@/features/departmentPortal/components/DepartmentPortalHero';
import { DepartmentPortalLayout } from '@/features/departmentPortal/components/DepartmentPortalLayout';
import {
  CenteredState,
  PageStack,
  StateMessage,
} from '@/features/departmentPortal/components/departmentPortalStyles';
import { useDepartmentPortal } from '@/features/departmentPortal/hooks/useDepartmentPortal';

const ActionsGrid = styled.div`
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: ${({ theme }) => theme.layout.cardGap};
`;

const ActionCard = styled(Card)`
  display: flex;
  flex-direction: column;
  gap: ${({ theme }) => theme.spacing[6]};
  text-align: start;
  min-height: 220px;
  transition:
    box-shadow ${({ theme }) => theme.transitions.fast},
    transform ${({ theme }) => theme.transitions.fast},
    border-color ${({ theme }) => theme.transitions.fast};

  &:hover {
    transform: ${({ theme }) => theme.motion.hoverLift};
    box-shadow: ${({ theme }) => theme.shadows.lg};
    border-color: ${({ theme }) => theme.colors.border};
  }
`;

const ActionIcon = styled.span`
  width: 52px;
  height: 52px;
  border-radius: ${({ theme }) => theme.borderRadius.xl};
  display: inline-flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(
    145deg,
    ${({ theme }) => theme.colors.primaryLight} 0%,
    ${({ theme }) => theme.colors.surfaceMuted} 100%
  );
  color: ${({ theme }) => theme.colors.primary};
  box-shadow: ${({ theme }) => theme.shadows.xs};

  svg {
    width: 22px;
    height: 22px;
  }
`;

const ActionTitle = styled.h2`
  margin: 0;
  font-family: ${({ theme }) => theme.typography.fontFamily.headline};
  font-size: ${({ theme }) => theme.typography.fontSize.xl};
  font-weight: ${({ theme }) => theme.typography.fontWeight.semibold};
  letter-spacing: ${({ theme }) => theme.typography.letterSpacing.tight};
  color: ${({ theme }) => theme.colors.text.primary};
`;

const ActionText = styled.p`
  margin: 0;
  flex: 1;
  color: ${({ theme }) => theme.colors.text.secondary};
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  line-height: ${({ theme }) => theme.typography.lineHeight.relaxed};
`;

const LoginHint = styled.p`
  margin: 0;
  text-align: center;
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  color: ${({ theme }) => theme.colors.text.secondary};

  a {
    color: ${({ theme }) => theme.colors.primary};
    font-weight: ${({ theme }) => theme.typography.fontWeight.medium};
  }
`;

const loginRedirect = (path: string) =>
  `${ROUTES.LOGIN}?redirect=${encodeURIComponent(path)}`;

const DepartmentPortalPage: React.FC = () => {
  const { departmentSlug } = useParams<{ departmentSlug: string }>();
  const { t } = useLocale();
  const navigate = useNavigate();
  const isAuthenticated = useAuthStore((s) => s.isAuthenticated);
  const portalQuery = useDepartmentPortal(departmentSlug);

  const basePath = ROUTES.DEPARTMENT_PORTAL(departmentSlug ?? '');
  const createPath = ROUTES.DEPARTMENT_PORTAL_CREATE(departmentSlug ?? '');
  const myTicketsPath = ROUTES.DEPARTMENT_PORTAL_MY_TICKETS(departmentSlug ?? '');

  if (portalQuery.isLoading) {
    return (
      <DepartmentPortalLayout departmentSlug={departmentSlug}>
        <CenteredState>
          <Spinner size="lg" />
          <StateMessage>{t('common:status.loading')}</StateMessage>
        </CenteredState>
      </DepartmentPortalLayout>
    );
  }

  if (portalQuery.isError) {
    const status = isAxiosError(portalQuery.error) ? portalQuery.error.response?.status : undefined;
    const message =
      status === 403
        ? t('departmentPortal:restrictedDepartment')
        : status === 404
          ? t('departmentPortal:departmentUnavailable')
          : t('departmentPortal:errors.loadFailed');

    return (
      <DepartmentPortalLayout departmentSlug={departmentSlug}>
        <CenteredState>
          <StateMessage>{message}</StateMessage>
          <Button variant="outline" onClick={() => portalQuery.refetch()}>
            {t('dashboard:states.retry')}
          </Button>
        </CenteredState>
      </DepartmentPortalLayout>
    );
  }

  const portal = portalQuery.data!;
  const goCreate = () =>
    navigate(isAuthenticated ? createPath : loginRedirect(createPath));
  const goMyTickets = () =>
    navigate(isAuthenticated ? myTicketsPath : loginRedirect(myTicketsPath));

  return (
    <DepartmentPortalLayout departmentSlug={departmentSlug}>
      <PageStack>
        <DepartmentPortalHero portal={portal} />
        <ActionsGrid>
          <ActionCard variant="elevated" padding="lg" interactive onClick={goCreate}>
            <ActionIcon aria-hidden>
              <HiPlus />
            </ActionIcon>
            <ActionTitle>{t('departmentPortal:createTicket')}</ActionTitle>
            <ActionText>{t('departmentPortal:trackRequests')}</ActionText>
            <Button
              variant="primary"
              size="md"
              icon={<HiArrowRight />}
              iconPosition="right"
              onClick={(e) => {
                e.stopPropagation();
                goCreate();
              }}
            >
              {t('departmentPortal:createTicket')}
            </Button>
          </ActionCard>
          <ActionCard variant="elevated" padding="lg" interactive onClick={goMyTickets}>
            <ActionIcon aria-hidden>
              <HiClipboardList />
            </ActionIcon>
            <ActionTitle>{t('departmentPortal:myTickets')}</ActionTitle>
            <ActionText>{t('departmentPortal:trackRequests')}</ActionText>
            <Button
              variant="outline"
              size="md"
              onClick={(e) => {
                e.stopPropagation();
                goMyTickets();
              }}
            >
              {t('departmentPortal:myTickets')}
            </Button>
          </ActionCard>
        </ActionsGrid>
        {!isAuthenticated ? (
          <LoginHint>
            <Link to={loginRedirect(basePath)}>{t('departmentPortal:loginRequired')}</Link>
          </LoginHint>
        ) : null}
      </PageStack>
    </DepartmentPortalLayout>
  );
};

export default DepartmentPortalPage;
