// pages/admin/rateMatrix/RateMatrixApproval.tsx
import React from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { LoadingScreen } from '@/ui/LoadingScreen';
import { useRateMatrixAuth } from '@/auth/hooks/useAuth';
import { queryKeys } from '../../../constants/QUERY_KEYS';
import { API_URLS } from '@/constants/URL_CONSTANTS';
//import { MATRIX_STATUS } from '@/constants/rateMatrixConstants';
import { toast } from 'sonner';
import { Navigate } from 'react-router-dom';

export default function RateMatrixApprovalPage() {
  const { isChiefExecutive } = useRateMatrixAuth();
  const queryClient = useQueryClient();
  const pendingMatricesQueryKey = [...queryKeys.rateMatrix.all, 'pending-approval'];

  const { data: pendingMatrices, isLoading } = useQuery({
    queryKey: pendingMatricesQueryKey,
    queryFn: async () => {
      const response = await fetch(`${API_URLS.RATE_MATRIX.LIST}?status=pending_approval`);
      return response.json();
    },
  });

  const authorizeMutation = useMutation({
    mutationFn: async ({ matrixId, signature }: { matrixId: string; signature: string }) => {
      const response = await fetch(API_URLS.RATE_MATRIX.AUTHORIZE(matrixId), {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ digitalSignature: signature }),
      });
      if (!response.ok) throw new Error('Authorization failed');
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: pendingMatricesQueryKey });
      toast.success('Rate matrix authorized successfully!');
    },
    onError: () => {
      toast.error('Failed to authorize rate matrix');
    },
  });

  if (!isChiefExecutive) {
    return <Navigate to="/unauthorized" replace />;
  }

  if (isLoading) return <LoadingScreen />;

  return (
    <div className="container mx-auto py-8">
      <h1 className="text-3xl font-bold mb-8">Pending Rate Matrix Approvals</h1>
      
      <div className="space-y-6">
        {pendingMatrices?.map((matrix: any) => (
          <Card key={matrix.id}>
            <CardHeader>
              <CardTitle className="flex items-center justify-between">
                <span>{matrix.matrixName}</span>
                <Badge variant="secondary">{matrix.status}</Badge>
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <p className="text-sm font-semibold">Effective Date</p>
                    <p>{matrix.effectiveDate}</p>
                  </div>
                  <div>
                    <p className="text-sm font-semibold">Submitted By</p>
                    <p>{matrix.createdBy}</p>
                  </div>
                </div>
                
                <div>
                  <p className="text-sm font-semibold mb-2">Rate Types Included:</p>
                  <div className="flex flex-wrap gap-2">
                    {matrix.rateEntries?.map((entry: any) => (
                      <Badge key={entry.id} variant="outline">
                        {entry.rateType}
                      </Badge>
                    ))}
                  </div>
                </div>

                <div className="flex gap-4">
                  <Button
                    onClick={() => {
                      // Implement digital signature collection
                      const signature = prompt('Enter digital signature:');
                      if (signature) {
                        authorizeMutation.mutate({ 
                          matrixId: matrix.id, 
                          signature 
                        });
                      }
                    }}
                    disabled={authorizeMutation.isPending}
                  >
                    Authorize & Release
                  </Button>
                  <Button variant="outline">
                    Request Changes
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  );
}