/**
 * Form 16 submission result screen.
 * Shown after dealer submits Form 16A. Status: success | mismatch | duplicate | error (request received).
 * State is passed via navigate state; fallback from sessionStorage for refresh.
 */

import { useNavigate, useLocation } from 'react-router-dom';
import { useEffect, useCallback } from 'react';
import { RequestSubmissionSuccess, type SubmissionResultStatus } from './components/RequestSubmissionSuccess';

const RESULT_STATE_KEY = 'form16_submission_result';

export interface Form16ResultState {
  status: SubmissionResultStatus;
  requestId: string;
  requestNumber?: string;
  creditNoteNumber?: string | null;
  message?: string | null;
}

export function Form16SubmissionResult() {
  const navigate = useNavigate();
  const location = useLocation();
  const state = location.state as Form16ResultState | null;

  const stored = (() => {
    try {
      const raw = sessionStorage.getItem(RESULT_STATE_KEY);
      if (!raw) return null;
      return JSON.parse(raw) as Form16ResultState;
    } catch {
      return null;
    }
  })();

  const result = (state?.status || state?.requestId) ? state : stored;
  const hasValidResult = !!result?.status;

  useEffect(() => {
    if (!hasValidResult) return;
    sessionStorage.setItem(RESULT_STATE_KEY, JSON.stringify(result));
  }, [hasValidResult, result]);

  const onComplete = useCallback(() => {
    sessionStorage.removeItem(RESULT_STATE_KEY);
    navigate('/my-requests', { replace: true });
  }, [navigate]);

  const onResubmit = useCallback(() => {
    sessionStorage.removeItem(RESULT_STATE_KEY);
    navigate('/form16/submit', { replace: true });
  }, [navigate]);

  const onViewRequest = useCallback(() => {
    if (!result?.requestNumber) return;
    sessionStorage.removeItem(RESULT_STATE_KEY);
    navigate(`/request/${result.requestNumber}`, { replace: true });
  }, [navigate, result?.requestNumber]);

  if (!hasValidResult) {
    navigate('/form16/submit', { replace: true });
    return null;
  }

  return (
    <RequestSubmissionSuccess
      status={result.status}
      requestId={result.requestId}
      requestDisplayId={result.requestNumber ?? result.requestId}
      creditNoteNumber={result.creditNoteNumber}
      message={result.message}
      onComplete={onComplete}
      onResubmit={onResubmit}
      onViewRequest={result.requestNumber ? onViewRequest : undefined}
    />
  );
}
