import React, { useMemo, useState } from 'react';
import { useParams } from 'react-router-dom';
import styled from 'styled-components';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { HiExclamation, HiPlus, HiShieldCheck } from 'react-icons/hi';
import { Button, Input, Modal, Select, StatusBadge, Card } from '@/shared/components/ui';
import { ReportChart } from '@/features/projects/components/ReportChart';
import { EmptyStateCard } from '@/features/onboarding/components/EmptyStateCard';
import { PageSection } from '@/shared/components/layout/PageSection';
import { PanelLoadingState, PanelEmpty } from '@/shared/components/ui/PageState';
import { StatCard } from '@/features/dashboard/components/StatCard';
import { useLocale } from '@/app/providers/LocaleProvider';
import { ProjectPageShell } from '@/features/projects/components/ProjectPageShell';
import { useProject } from '@/features/projects/hooks/useProject';
import { useProjectPermissions } from '@/features/projects/hooks/useProjectPermissions';
import {
  AgileActionsSection,
  AgileContentSection,
  AgileMetricsSection,
  InlineActions,
  ProjectsStatsGrid,
  WorkItemsList,
} from '@/features/projects/components/projectsLayout';
import { risksQueryKey, useProjectRisks } from '@/features/projects/hooks/useProjectRisks';
import { createRisk, fetchRiskMatrix, updateRisk } from '@/features/projects/services/projectService';
import { FormActions, FormStack } from '@/shared/components/ui/FormStack';
import { RiskMatrixChart } from '@/features/projects/components/risks/RiskMatrixChart';
import { RiskHeatmap } from '@/features/projects/components/risks/RiskHeatmap';
import { RiskHistoryPanel } from '@/features/projects/components/risks/RiskHistoryPanel';

const TabRow = styled.div`
  display: flex;
  gap: ${({ theme }) => theme.spacing[2]};
  margin-bottom: ${({ theme }) => theme.spacing[4]};
`;

const TabButton = styled.button<{ $active: boolean }>`
  padding: ${({ theme }) => `${theme.spacing[2]} ${theme.spacing[4]}`};
  border-radius: ${({ theme }) => theme.borderRadius.md};
  border: 1px solid ${({ theme, $active }) => ($active ? theme.colors.primary : theme.colors.borderSoft)};
  background: ${({ theme, $active }) => ($active ? theme.colors.primaryLight : theme.colors.surface)};
  color: ${({ theme, $active }) => ($active ? theme.colors.primary : theme.colors.text.secondary)};
  font-weight: ${({ theme }) => theme.typography.fontWeight.medium};
  cursor: pointer;
`;

const RiskMeta = styled.p`
  margin: ${({ theme }) => `${theme.spacing[2]} 0`};
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  color: ${({ theme }) => theme.colors.text.secondary};
  display: flex;
  flex-wrap: wrap;
  gap: ${({ theme }) => theme.spacing[2]};
`;

const RISK_CATEGORIES = [
  { value: 'Technical', label: 'Technical' },
  { value: 'Schedule', label: 'Schedule' },
  { value: 'Resource', label: 'Resource' },
  { value: 'External', label: 'External' },
  { value: 'Scope', label: 'Scope' },
];

const RISK_STATUSES = [
  { value: 'open', label: 'Open' },
  { value: 'mitigating', label: 'Mitigating' },
  { value: 'monitoring', label: 'Monitoring' },
  { value: 'mitigated', label: 'Mitigated' },
  { value: 'closed', label: 'Closed' },
];

type RiskView = 'matrix' | 'heatmap' | 'distribution' | 'list';

const CriticalBanner = styled.div`
  display: flex;
  align-items: center;
  gap: ${({ theme }) => theme.spacing[3]};
  padding: ${({ theme }) => theme.spacing[4]};
  border-radius: ${({ theme }) => theme.borderRadius.md};
  background: ${({ theme }) => `${theme.colors.error}12`};
  border-inline-start: 4px solid ${({ theme }) => theme.colors.error};
  color: ${({ theme }) => theme.colors.error};
  font-weight: ${({ theme }) => theme.typography.fontWeight.semibold};
  margin-bottom: ${({ theme }) => theme.spacing[4]};
`;

const ProjectRisksPage: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const { t } = useLocale();
  const { data: project } = useProject(id);
  const { readOnly } = useProjectPermissions(project);
  const { data, isLoading } = useProjectRisks(id);
  const queryClient = useQueryClient();
  const [view, setView] = useState<RiskView>('matrix');
  const [historyRiskId, setHistoryRiskId] = useState<string | null>(null);
  const [modalOpen, setModalOpen] = useState(false);
  const [title, setTitle] = useState('');
  const [category, setCategory] = useState('Technical');
  const [probability, setProbability] = useState('3');
  const [impact, setImpact] = useState('3');

  const { data: matrix } = useQuery({
    queryKey: ['projects', id, 'risks', 'matrix'],
    queryFn: () => fetchRiskMatrix(id!),
    enabled: Boolean(id) && view === 'matrix',
  });

  const createMutation = useMutation({
    mutationFn: (payload: Record<string, unknown>) => createRisk(id!, payload),
    onSuccess: () => {
      setTitle('');
      setModalOpen(false);
      void queryClient.invalidateQueries({ queryKey: risksQueryKey(id!) });
      void queryClient.invalidateQueries({ queryKey: ['projects', id, 'risks', 'matrix'] });
    },
  });

  const statusMutation = useMutation({
    mutationFn: ({ riskId, status }: { riskId: string; status: string }) =>
      updateRisk(id!, riskId, { status }),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: risksQueryKey(id!) });
      void queryClient.invalidateQueries({ queryKey: ['projects', id, 'risks', 'matrix'] });
    },
  });

  const distributionChart = useMemo(() => {
    const risks = data?.risks ?? [];
    if (risks.length === 0) return null;
    const counts = new Map<string, number>();
    risks.forEach((r) => {
      const key = ('category' in r && r.category ? String(r.category) : 'Uncategorized');
      counts.set(key, (counts.get(key) ?? 0) + 1);
    });
    const entries = [...counts.entries()];
    return {
      labels: entries.map(([k]) => k),
      datasets: [
        {
          label: 'Risks',
          data: entries.map(([, v]) => v),
          backgroundColor: ['#6366f1', '#f59e0b', '#ef4444', '#10b981', '#0ea5e9', '#94a3b8'].slice(0, entries.length),
        },
      ],
    };
  }, [data]);

  const criticalCount = data?.metrics?.critical ?? 0;

  return (
    <ProjectPageShell projectId={id}>
      {() => (
        <>
          {data?.metrics && (
            <AgileMetricsSection>
              <ProjectsStatsGrid>
                <StatCard kpi label={t('projects:risks.open')} value={data.metrics.open} icon={HiExclamation} accent="warning" />
                <StatCard kpi label={t('projects:risks.critical')} value={data.metrics.critical} accent="error" />
                <StatCard kpi label={t('projects:risks.closed')} value={data.metrics.closed} icon={HiShieldCheck} accent="success" />
              </ProjectsStatsGrid>
            </AgileMetricsSection>
          )}

          {!readOnly && (
            <AgileActionsSection>
              <InlineActions>
                <Button type="button" variant="primary" size="lg" icon={<HiPlus aria-hidden />} onClick={() => setModalOpen(true)}>
                  {t('projects:risks.add')}
                </Button>
              </InlineActions>
            </AgileActionsSection>
          )}

          {criticalCount > 0 && (
            <CriticalBanner>
              <HiExclamation aria-hidden />
              {criticalCount} critical {criticalCount === 1 ? 'risk requires' : 'risks require'} immediate attention.
            </CriticalBanner>
          )}

          <AgileContentSection>
            <PageSection title={t('projects:nav.risks')}>
              <TabRow role="tablist">
                {(['matrix', 'heatmap', 'distribution', 'list'] as RiskView[]).map((tab) => (
                  <TabButton key={tab} type="button" $active={view === tab} onClick={() => setView(tab)}>
                    {tab === 'list'
                      ? 'Register'
                      : tab === 'matrix'
                        ? 'Risk Matrix'
                        : tab === 'heatmap'
                          ? 'Heatmap'
                          : 'Distribution'}
                  </TabButton>
                ))}
              </TabRow>

              {isLoading ? (
                <PanelLoadingState label={t('projects:states.loading')} />
              ) : view === 'matrix' ? (
                matrix?.cells ? (
                  <RiskMatrixChart
                    cells={matrix.cells}
                    onSelectRisk={() => setView('list')}
                  />
                ) : (
                  <PanelEmpty title="No matrix data" />
                )
              ) : view === 'heatmap' ? (
                <RiskHeatmap risks={data?.risks ?? []} />
              ) : view === 'distribution' ? (
                distributionChart ? (
                  <Card variant="elevated" padding="lg">
                    <ReportChart type="doughnut" data={distributionChart} height={300} />
                  </Card>
                ) : (
                  <PanelEmpty title={t('projects:risks.empty')} />
                )
              ) : (data?.risks ?? []).length === 0 ? (
                <EmptyStateCard
                  icon={<HiExclamation aria-hidden />}
                  title={t('projects:risks.empty')}
                  description={t('projects:risks.emptyHint')}
                  actionLabel={readOnly ? undefined : t('projects:risks.add')}
                  onAction={readOnly ? undefined : () => setModalOpen(true)}
                />
              ) : (
                <WorkItemsList>
                  {(data?.risks ?? []).map((risk) => (
                    <Card key={risk.id} variant="elevated" padding="lg">
                      <strong>{risk.title}</strong>
                      <RiskMeta>
                        <StatusBadge tone="neutral" size="sm">{risk.status}</StatusBadge>
                        <span>P{risk.probability} / I{risk.impact} = {risk.probability * risk.impact}</span>
                        {'category' in risk && risk.category ? <span>{String(risk.category)}</span> : null}
                      </RiskMeta>
                      {risk.description && <p style={{ margin: 0, fontSize: '0.875rem' }}>{risk.description}</p>}
                      {!readOnly && (
                        <div style={{ marginTop: '0.75rem', maxWidth: '220px' }}>
                          <Select
                            label="Lifecycle status"
                            value={risk.status}
                            onChange={(e) =>
                              statusMutation.mutate({ riskId: risk.id, status: e.target.value })
                            }
                            options={RISK_STATUSES}
                            disabled={statusMutation.isPending}
                          />
                        </div>
                      )}
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        style={{ marginTop: '0.75rem' }}
                        onClick={() => setHistoryRiskId(risk.id)}
                      >
                        Audit history
                      </Button>
                    </Card>
                  ))}
                </WorkItemsList>
              )}
            </PageSection>
          </AgileContentSection>

          <Modal
            isOpen={modalOpen}
            onClose={() => setModalOpen(false)}
            title={t('projects:risks.add')}
            footer={
              <FormActions>
                <Button type="button" variant="secondary" size="lg" onClick={() => setModalOpen(false)}>
                  {t('common:actions.cancel')}
                </Button>
                <Button
                  type="button"
                  variant="primary"
                  size="lg"
                  disabled={!title.trim()}
                  loading={createMutation.isPending}
                  onClick={() =>
                    title.trim() &&
                    createMutation.mutate({
                      title,
                      category,
                      probability: Number(probability),
                      impact: Number(impact),
                    })
                  }
                >
                  {t('projects:risks.add')}
                </Button>
              </FormActions>
            }
          >
            <FormStack>
              <Input label={t('projects:risks.newTitle')} value={title} onChange={(e) => setTitle(e.target.value)} fullWidth />
              <Select label="Category" value={category} onChange={(e) => setCategory(e.target.value)} options={RISK_CATEGORIES} />
              <Select
                label="Probability (1-5)"
                value={probability}
                onChange={(e) => setProbability(e.target.value)}
                options={[1, 2, 3, 4, 5].map((n) => ({ value: String(n), label: String(n) }))}
              />
              <Select
                label="Impact (1-5)"
                value={impact}
                onChange={(e) => setImpact(e.target.value)}
                options={[1, 2, 3, 4, 5].map((n) => ({ value: String(n), label: String(n) }))}
              />
            </FormStack>
          </Modal>

          <Modal
            isOpen={Boolean(historyRiskId)}
            onClose={() => setHistoryRiskId(null)}
            title="Audit history"
          >
            {historyRiskId && id && <RiskHistoryPanel projectId={id} riskId={historyRiskId} />}
          </Modal>
        </>
      )}
    </ProjectPageShell>
  );
};

export default ProjectRisksPage;
