import { useEffect, useMemo, useState } from 'react';
import { useQuery } from 'urql';
import type { AnnualAuditStepStatus } from '@/gql/graphql.js';
import { Step05PrevYearTemplateDocument } from '@/gql/graphql.js';
import type { TimelessDateString } from '@/helpers/index.js';
import { ROUTES } from '@/router/routes.js';
// import { CardContent } from '../../../../ui/card.js';
import { Collapsible, CollapsibleContent } from '../../../../ui/collapsible.js';
import { ApprovalControl, gqlStatusToStepStatus } from '../approval-control.js';
import {
  BaseStepCard,
  type BaseStepProps,
  type StepAction,
  type StepStatus,
} from '../step-base.js';

// eslint-disable-next-line @typescript-eslint/no-unused-expressions -- used by codegen
/* GraphQL */ `
  query Step05PrevYearTemplate($ownerId: UUID!, $year: Int!) {
    annualAuditStepStatuses(ownerId: $ownerId, year: $year) {
      id
      stepId
      status
      evidence
    }
  }
`;

interface Step05Props extends BaseStepProps {
  year: number;
  adminBusinessId?: string;
}

export function Step05MainProcess(props: Step05Props) {
  const [status, setStatus] = useState<StepStatus>('pending');
  const [isExpanded, setIsExpanded] = useState(false);
  const { adminBusinessId, id, onStatusChange } = props;

  const [{ data: prevYearData }] = useQuery({
    query: Step05PrevYearTemplateDocument,
    variables: { ownerId: adminBusinessId ?? '', year: props.year - 1 },
    pause: !adminBusinessId,
  });

  const prevYearLockedTemplateName = useMemo<string | null>(() => {
    const step09 = prevYearData?.annualAuditStepStatuses?.find(s => s.stepId === '9');
    if (!step09?.evidence) return null;
    try {
      const parsed = JSON.parse(step09.evidence) as { lockedTemplateName?: string };
      return parsed.lockedTemplateName ?? null;
    } catch {
      return null;
    }
  }, [prevYearData]);

  const persistedStepRecord = useMemo(() => {
    if (!Array.isArray(props.manualData)) return undefined;
    return props.manualData.find(record => record.stepId === id);
  }, [props.manualData, id]);

  const persistedManualStatus = useMemo<StepStatus | undefined>(() => {
    const persistedStatus = persistedStepRecord?.status;
    if (!persistedStatus) {
      return undefined;
    }
    return gqlStatusToStepStatus(persistedStatus as AnnualAuditStepStatus);
  }, [persistedStepRecord]);

  const persistedManualNotes = persistedStepRecord?.notes ?? null;

  // Apply persisted override if it exists
  useEffect(() => {
    if (persistedManualStatus) {
      setStatus(persistedManualStatus);
    }
  }, [persistedManualStatus]);

  // Report status changes to parent
  useEffect(() => onStatusChange?.(id, status), [status, onStatusChange, id]);

  const actions = useMemo((): StepAction[] => {
    const dynamicReportActions: StepAction[] = prevYearLockedTemplateName
      ? [
          {
            label: 'Balance Sheet',
            href: ROUTES.REPORTS.DYNAMIC_REPORT({
              ownerIds: adminBusinessId ? [adminBusinessId] : undefined,
              fromDate: '1900-01-01' as TimelessDateString,
              toDate: `${props.year}-12-31` as TimelessDateString,
              templateName: prevYearLockedTemplateName,
            }),
          },
          {
            label: 'Profit and Loss',
            href: ROUTES.REPORTS.DYNAMIC_REPORT({
              ownerIds: adminBusinessId ? [adminBusinessId] : undefined,
              fromDate: `${props.year}-01-01` as TimelessDateString,
              toDate: `${props.year}-12-31` as TimelessDateString,
              templateName: prevYearLockedTemplateName,
            }),
          },
        ]
      : [
          {
            label: 'Create Dynamic Report Template',
            href: ROUTES.REPORTS.DYNAMIC_REPORT(),
          },
        ];

    return [
      ...dynamicReportActions,
      // { label: 'Open Checklist', href: '/validations/checklist' },
      // { label: 'Compare VAT', href: '/vat/comparison' },
      // { label: 'Generate Draft', href: '/depreciation/draft' },
      // { label: 'Manage Audit Checks', href: '/audit/checks' },
      {
        label: 'Trial Balance',
        href: ROUTES.REPORTS.TRIAL_BALANCE({
          ownerIds: adminBusinessId ? [adminBusinessId] : undefined,
          fromDate: '1900-01-01' as TimelessDateString,
          toDate: `${props.year}-12-31` as TimelessDateString,
          isShowZeroedAccounts: true,
        }),
      },
      { label: 'Review Tax Report', href: ROUTES.REPORTS.TAX(props.year) },
      // { label: 'Cash Flow Analysis', href: '/cashflow/analysis' },
    ];
  }, [props.year, adminBusinessId, prevYearLockedTemplateName]);

  return (
    <BaseStepCard
      {...props}
      status={status}
      isExpanded={isExpanded}
      onToggleExpanded={() => setIsExpanded(prev => !prev)}
      actions={actions}
    >
      {adminBusinessId && (
        <Collapsible open={isExpanded}>
          <CollapsibleContent>
            {/* <CardContent className="pt-0 border-t">
              <div className="space-y-2 mt-3" />
            </CardContent> */}
            <div className="px-6 pb-4 pt-2 border-t">
              <ApprovalControl
                ownerId={adminBusinessId}
                year={props.year}
                stepId={id}
                initialStatus={
                  (persistedStepRecord?.status as AnnualAuditStepStatus | undefined) ?? undefined
                }
                initialNotes={persistedManualNotes}
                onSaved={status => setStatus(status)}
              />
            </div>
          </CollapsibleContent>
        </Collapsible>
      )}
    </BaseStepCard>
  );
}
