import React, { useMemo } from 'react';
import styled from 'styled-components';
import {
  HiCalendar,
  HiCheckCircle,
  HiClock,
  HiExclamation,
  HiInbox,
  HiShieldCheck,
  HiTicket,
} from 'react-icons/hi';
import { useLocale } from '@/app/providers/LocaleProvider';
import { AppLayout } from '@/shared/components/layout/AppLayout';
import { PageHeader } from '@/shared/components/layout/PageHeader';
import { PageSection } from '@/shared/components/layout/PageSection';
import { PageStack } from '@/shared/components/layout/PageStack';
import { Card } from '@/shared/components/ui';
import { PanelError, PanelLoadingState } from '@/shared/components/ui/PageState';
import { useDashboardOverview } from '@/features/dashboard/hooks/useDashboardOverview';
import { useDashboardTicketTrends } from '@/features/dashboard/hooks/useDashboardTicketTrends';
import { useDashboardAssigneePerformance } from '@/features/dashboard/hooks/useDashboardAssigneePerformance';
import { TicketTrendsChart } from '@/features/dashboard/components/TicketTrendsChart';
import { HorizontalBarChart } from '@/features/dashboard/components/HorizontalBarChart';
import { DistributionDonutChart } from '@/features/dashboard/components/DistributionDonutChart';
import { AssigneePerformanceChart } from '@/features/dashboard/components/AssigneePerformanceChart';
import { RecentActivityFeed } from '@/features/dashboard/components/RecentActivityFeed';
import { StatCard } from '@/features/dashboard/components/StatCard';
import { DashboardSkeleton } from '@/features/dashboard/components/DashboardSkeleton';
import { ChecklistCard } from '@/features/onboarding/components/ChecklistCard';
import { EmptyStateCard } from '@/features/onboarding/components/EmptyStateCard';
import { useOnboarding } from '@/features/onboarding/hooks/useOnboarding';
import {
  formatCount,
  formatHours,
  formatPercent,
} from '@/features/dashboard/utils/formatMetrics';
import { buildLabelMap } from '@/features/dashboard/utils/translateMetricLabel';

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

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

  & > * {
    height: 100%;
    min-height: 320px;
  }
`;

const OperationsIntro = styled.p`
  margin: ${({ theme }) => `-${theme.spacing[2]} 0 ${theme.spacing[5]}`};
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  color: ${({ theme }) => theme.colors.text.tertiary};
  max-width: 40rem;
  line-height: ${({ theme }) => theme.typography.lineHeight.relaxed};
  text-align: start;
`;

const DashboardPage: React.FC = () => {
  const { t, locale } = useLocale();
  const { data, isLoading, isError, error, refetch, isFetching } = useDashboardOverview();
  const ticketTrendsQuery = useDashboardTicketTrends();
  const assigneePerformanceQuery = useDashboardAssigneePerformance();
  const { checklist } = useOnboarding();

  const hoursUnit = t('dashboard:units.hours');

  const slaLabelMap = {
    Met: t('dashboard:slaStatus.met'),
    Warning: t('dashboard:slaStatus.warning'),
    Breached: t('dashboard:slaStatus.breached'),
    Active: t('dashboard:slaStatus.active'),
    Paused: t('dashboard:slaStatus.paused'),
  };

  const statusLabelMap = useMemo(
    () => buildLabelMap(data?.charts.tickets_by_status.labels ?? [], t),
    [data?.charts.tickets_by_status.labels, t],
  );
  const priorityLabelMap = useMemo(
    () => buildLabelMap(data?.charts.tickets_by_priority.labels ?? [], t),
    [data?.charts.tickets_by_priority.labels, t],
  );
  const categoryLabelMap = useMemo(
    () => buildLabelMap(data?.charts.tickets_by_category.labels ?? [], t),
    [data?.charts.tickets_by_category.labels, t],
  );

  if (isLoading) {
    return (
      <AppLayout>
        <PageHeader title={t('dashboard:title')} subtitle={t('dashboard:states.loading')} />
        <div role="status" aria-live="polite">
          <DashboardSkeleton />
        </div>
      </AppLayout>
    );
  }

  if (isError || !data) {
    return (
      <AppLayout>
        <PageHeader title={t('dashboard:title')} />
        <Card variant="elevated" padding="none">
          <PanelError
            message={error instanceof Error ? error.message : t('dashboard:states.error')}
            retryLabel={t('dashboard:states.retry')}
            onRetry={() => refetch()}
            loading={isFetching}
          />
        </Card>
      </AppLayout>
    );
  }

  const { stats, charts, recent_tickets: recentTickets, recent_projects: recentProjects = [] } = data;
  const isEmpty =
    stats.total_tickets === 0 &&
    recentTickets.length === 0 &&
    recentProjects.length === 0 &&
    charts.tickets_by_status.labels.length === 0;

  const assignees = assigneePerformanceQuery.data?.assignees ?? [];
  const showAssigneeChart =
    !assigneePerformanceQuery.isError && assignees.some((assignee) => assignee.tickets_handled > 0);

  return (
    <AppLayout>
      <PageHeader
        title={t('dashboard:title')}
        subtitle={t('dashboard:subtitle', { defaultValue: 'Your support operations at a glance.' })}
      />
      <OperationsIntro>
        {t('dashboard:operationsIntro', {
          defaultValue: 'Track volume, SLA health, and team momentum in one calm workspace.',
        })}
      </OperationsIntro>

      <PageStack $gap="dashboard">
      {checklist && checklist.total > 0 && (
        <PageSection>
          <ChecklistCard
            completed={checklist.completed}
            total={checklist.total}
            items={checklist.items}
          />
        </PageSection>
      )}

      {isEmpty && (
        <PageSection>
          <Card variant="muted" padding="lg" data-tour="dashboard-stats">
            <EmptyStateCard
              icon="📈"
              title={t('dashboard:states.empty')}
              description={t('dashboard:states.emptyHint', {
                defaultValue: 'Create your first ticket to see trends and activity appear here.',
              })}
            />
          </Card>
        </PageSection>
      )}

      <PageSection title={t('dashboard:sections.overview', { defaultValue: 'Overview' })}>
        <StatsGrid data-tour="dashboard-stats">
          <StatCard
            label={t('dashboard:stats.totalTickets')}
            value={formatCount(stats.total_tickets, locale)}
            icon={HiTicket}
            featured
          />
          <StatCard
            label={t('dashboard:stats.openTickets')}
            value={formatCount(stats.open_tickets, locale)}
            icon={HiInbox}
            featured
          />
          <StatCard
            label={t('dashboard:stats.closedTickets')}
            value={formatCount(stats.closed_tickets, locale)}
            icon={HiCheckCircle}
            accent="success"
          />
          <StatCard
            label={t('dashboard:stats.overdueTickets')}
            value={formatCount(stats.overdue_tickets, locale)}
            icon={HiExclamation}
            accent={stats.overdue_tickets > 0 ? 'error' : 'default'}
            featured
          />
          <StatCard
            label={t('dashboard:stats.ticketsToday')}
            value={formatCount(stats.tickets_today, locale)}
            icon={HiCalendar}
            accent={stats.tickets_today > 0 ? 'warning' : 'default'}
          />
          <StatCard
            label={t('dashboard:stats.slaCompliance')}
            value={formatPercent(stats.sla_compliance_rate, locale)}
            icon={HiShieldCheck}
          />
          <StatCard
            label={t('dashboard:stats.avgResponseTime')}
            value={`${formatHours(stats.avg_response_time_hours, locale)} ${hoursUnit}`}
            icon={HiClock}
          />
          <StatCard
            label={t('dashboard:stats.avgResolutionTime')}
            value={`${formatHours(stats.avg_resolution_time_hours, locale)} ${hoursUnit}`}
            icon={HiClock}
          />
        </StatsGrid>
      </PageSection>

      <PageSection
        title={t('dashboard:sections.trends', { defaultValue: 'Trends' })}
        description={t('dashboard:sections.trendsHint', {
          defaultValue: 'Created vs closed volume over time.',
        })}
      >
        {ticketTrendsQuery.isLoading ? (
          <Card variant="elevated" padding="lg" header={t('dashboard:widgets.ticketTrends')}>
            <PanelLoadingState />
          </Card>
        ) : ticketTrendsQuery.data ? (
          <TicketTrendsChart
            title={t('dashboard:widgets.ticketTrends')}
            trends={ticketTrendsQuery.data}
            emptyLabel={t('dashboard:states.emptyCharts')}
            emptyHint={t('dashboard:states.emptyChartsHint')}
            seriesLabels={{
              created: t('dashboard:chartSeries.created'),
              closed: t('dashboard:chartSeries.closed'),
            }}
          />
        ) : null}
      </PageSection>

      <PageSection
        title={t('dashboard:sections.distribution', { defaultValue: 'Distribution' })}
        description={t('dashboard:sections.distributionHint', {
          defaultValue: 'How work is spread across status, priority, and categories.',
        })}
      >
        <ChartsGrid key="dashboard-charts">
          <HorizontalBarChart
            title={t('dashboard:widgets.ticketsByStatus')}
            dataset={charts.tickets_by_status}
            emptyLabel={t('dashboard:states.emptyCharts')}
            emptyHint={t('dashboard:states.emptyChartsHint')}
            labelMap={statusLabelMap}
          />
          <HorizontalBarChart
            title={t('dashboard:widgets.ticketsByPriority')}
            dataset={charts.tickets_by_priority}
            emptyLabel={t('dashboard:states.emptyCharts')}
            emptyHint={t('dashboard:states.emptyChartsHint')}
            labelMap={priorityLabelMap}
          />
          <HorizontalBarChart
            title={t('dashboard:widgets.categoryDistribution')}
            dataset={charts.tickets_by_category}
            emptyLabel={t('dashboard:states.emptyCharts')}
            emptyHint={t('dashboard:states.emptyChartsHint')}
            labelMap={categoryLabelMap}
          />
          <DistributionDonutChart
            title={t('dashboard:widgets.slaStatus')}
            dataset={charts.sla_status}
            emptyLabel={t('dashboard:states.emptyCharts')}
            emptyHint={t('dashboard:states.emptyChartsHint')}
            labelMap={slaLabelMap}
          />
        </ChartsGrid>
      </PageSection>

      {showAssigneeChart && (
        <PageSection title={t('dashboard:sections.team', { defaultValue: 'Team performance' })}>
          <AssigneePerformanceChart
            title={t('dashboard:widgets.assigneePerformance')}
            assignees={assignees}
            emptyLabel={t('dashboard:states.emptyCharts')}
            emptyHint={t('dashboard:states.emptyChartsHint')}
            seriesLabel={t('dashboard:chartSeries.ticketsHandled')}
          />
        </PageSection>
      )}

      <PageSection title={t('dashboard:sections.activity', { defaultValue: 'Recent activity' })}>
        <div data-tour="dashboard-recent">
        <RecentActivityFeed
          tickets={recentTickets}
          projects={recentProjects}
          emptyLabel={t('dashboard:states.emptyRecent')}
        />
        </div>
      </PageSection>
      </PageStack>
    </AppLayout>
  );
};

export default DashboardPage;
