'use client';

import { useState } from 'react';
import { useMutation, useQuery, useSuspenseQuery } from '@tanstack/react-query';
import { toast } from 'sonner';
import { Icons } from '@/components/icons';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Textarea } from '@/components/ui/textarea';
import {
  approvalByIdOptions,
  approvalsQueryOptions
} from '@/features/foundation/approval/queries';
import { submitQuotationApprovalMutation } from '@/features/foundation/approval/mutations';
import { ApprovalRequestPanel } from '@/features/foundation/approval/components/approval-request-panel';
import { ApprovalStatusBadge } from '@/features/foundation/approval/components/approval-status-badge';

export function QuotationApprovalTab({
  quotationId,
  quotationStatusCode,
  canSubmitApproval,
  canApproveApproval,
  canRejectApproval,
  canReturnApproval,
  activeBusinessRole,
  isOrgAdmin,
  currentUserId
}: {
  quotationId: string;
  quotationStatusCode: string | null;
  canSubmitApproval: boolean;
  canApproveApproval: boolean;
  canRejectApproval: boolean;
  canReturnApproval: boolean;
  activeBusinessRole: string | null;
  isOrgAdmin: boolean;
  currentUserId: string;
}) {
  const [remark, setRemark] = useState('');
  const { data: requestsData } = useSuspenseQuery(
    approvalsQueryOptions({
      entityType: 'quotation',
      entityId: quotationId,
      limit: 20
    })
  );
  const latestRequest = requestsData.items[0] ?? null;
  const { data: approvalDetailData } = useQuery({
    ...approvalByIdOptions(latestRequest?.id ?? ''),
    enabled: !!latestRequest
  });

  const submitApproval = useMutation({
    ...submitQuotationApprovalMutation,
    onSuccess: () => {
      toast.success('Quotation submitted for approval');
      setRemark('');
    },
    onError: (error) =>
      toast.error(error instanceof Error ? error.message : 'Unable to submit quotation')
  });
  const canSubmitNow = canSubmitApproval && ['draft', 'revised'].includes(quotationStatusCode ?? '');

  return (
    <div className='space-y-6'>
      <Card>
        <CardHeader>
          <CardTitle>Current Status</CardTitle>
          <CardDescription>Submission readiness and latest approval request state.</CardDescription>
        </CardHeader>
        <CardContent className='space-y-4'>
          <div className='flex flex-wrap items-center gap-3'>
            <ApprovalStatusBadge status={latestRequest?.status ?? quotationStatusCode ?? 'draft'} />
            <span className='text-muted-foreground text-sm'>
              {latestRequest
                ? `Latest request: ${latestRequest.workflowName}`
                : 'No approval request has been submitted yet.'}
            </span>
          </div>
          {canSubmitNow ? (
            <div className='space-y-3 rounded-lg border p-4'>
              <div className='text-sm font-medium'>Submit quotation into approval flow</div>
              <Textarea
                value={remark}
                onChange={(event) => setRemark(event.target.value)}
                placeholder='Optional remark for approvers'
                rows={3}
              />
              <Button
                isLoading={submitApproval.isPending}
                onClick={() => submitApproval.mutate({ id: quotationId, remark })}
              >
                <Icons.send className='mr-2 h-4 w-4' />
                Submit for Approval
              </Button>
            </div>
          ) : null}
        </CardContent>
      </Card>

      {approvalDetailData?.approval ? (
        <ApprovalRequestPanel
          approval={approvalDetailData.approval}
          canApprove={canApproveApproval}
          canReject={canRejectApproval}
          canReturn={canReturnApproval}
          canCancel={canSubmitApproval}
          activeBusinessRole={activeBusinessRole}
          isOrgAdmin={isOrgAdmin}
          currentUserId={currentUserId}
        />
      ) : (
        <Card>
          <CardHeader>
            <CardTitle>Approval Timeline</CardTitle>
            <CardDescription>Submission and approver history will appear here.</CardDescription>
          </CardHeader>
          <CardContent>
            <div className='text-muted-foreground rounded-lg border border-dashed p-8 text-center text-sm'>
              No approval activity recorded yet.
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
