/**
 * GRN Detail Page
 * View GRN details
 */

'use client';

import { useParams, useRouter } from 'next/navigation';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { procurementAPI } from '@/lib/api/procurement';
import {
  Button,
  Card,
  CardHeader,
  CardTitle,
  CardContent,
  Badge,
  LoadingPage,
  Table,
  TableHeader,
  TableBody,
  TableRow,
  TableHead,
  TableCell,
  Modal,
} from '@/components/ui';
import { formatCurrency, formatDateTime } from '@/lib/utils/format';
import { ArrowLeft, CheckCircle, Printer } from 'lucide-react';
import Link from 'next/link';
import toast from 'react-hot-toast';
import { useState } from 'react';

export default function GRNDetailPage() {
  const router = useRouter();
  const params = useParams();
  const grnId = parseInt(params.id);
  const queryClient = useQueryClient();
  const [showProcessModal, setShowProcessModal] = useState(false);
  const [printLabelsAfterProcess, setPrintLabelsAfterProcess] = useState(true);

  // Fetch GRN details
  const { data: grn, isLoading, error } = useQuery({
    queryKey: ['grn', grnId],
    queryFn: async () => {
      if (isNaN(grnId)) {
        throw new Error('Invalid GRN ID');
      }
      const response = await procurementAPI.getGRN(grnId);
      return response?.data || response;
    },
    enabled: !isNaN(grnId),
  });

  const processGRNMutation = useMutation({
    mutationFn: async () => {
      return await procurementAPI.processGRN(grnId);
    },
    onSuccess: () => {
      queryClient.invalidateQueries(['grn', grnId]);
      queryClient.invalidateQueries(['grns']);
      toast.success('GRN processed successfully! Inventory updated.');
      setShowProcessModal(false);
      // Redirect to reprint labels page if option is enabled
      if (printLabelsAfterProcess) {
        router.push(`/label-printing/reprint?source=GRN&reference_id=${grnId}`);
      }
    },
    onError: (error) => {
      const message = error?.response?.data?.message || error.message || 'Failed to process GRN';
      toast.error(message);
    },
  });

  const handleProcessGRN = () => {
    processGRNMutation.mutate();
  };

  if (isLoading) {
    return <LoadingPage message="Loading GRN details..." />;
  }

  if (error) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-950 text-center text-red-600">
        <p>Error: {error.message}</p>
        <Button onClick={() => router.back()} className="mt-4">
          Go Back
        </Button>
      </div>
    );
  }

  if (!grn) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-950 text-center text-gray-600">
        <p>GRN not found.</p>
        <Button onClick={() => router.back()} className="mt-4">
          Go Back
        </Button>
      </div>
    );
  }

  const isProcessed = grn.processed_at !== null && grn.processed_at !== undefined;

  return (
    <div className="container mx-auto p-6">
      <div className="flex justify-between items-center mb-6">
        <Button variant="ghost" onClick={() => router.back()} className="flex items-center">
          <ArrowLeft className="w-4 h-4 mr-2" /> Back to GRNs
        </Button>
        <div className="flex gap-2">
          {!isProcessed && (
            <Button
              variant="primary"
              onClick={() => setShowProcessModal(true)}
              disabled={processGRNMutation.isLoading}
              loading={processGRNMutation.isLoading}
            >
              <CheckCircle className="w-4 h-4 mr-2" /> Process GRN
            </Button>
          )}
          {isProcessed && (
            <Button
              variant="outline"
              onClick={() => router.push(`/label-printing/reprint?source=GRN&reference_id=${grnId}`)}
              className="flex items-center gap-2"
            >
              <Printer className="w-4 h-4" />
              Reprint Labels
            </Button>
          )}
        </div>
      </div>

      <Card className="mb-6">
        <CardHeader>
          <CardTitle className="flex items-center justify-between">
            <span>GRN #{grn.grn_number || grn.id}</span>
            {isProcessed && <Badge variant="success">Processed</Badge>}
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <h3 className="font-semibold text-gray-700 dark:text-gray-300 mb-3">GRN Information</h3>
              {grn.purchase_order && (
                <p className="text-gray-600 dark:text-gray-400 mb-2">
                  <span className="font-medium">Purchase Order:</span>{' '}
                  <Link
                    href={`/procurement/purchase-orders/${grn.purchase_order_id}`}
                    className="text-blue-600 dark:text-blue-400 hover:underline"
                  >
                    {grn.purchase_order.po_number || `PO-${grn.purchase_order_id}`}
                  </Link>
                </p>
              )}
              {grn.vendor && (
                <p className="text-gray-600 dark:text-gray-400 mb-2">
                  <span className="font-medium">Vendor:</span> {grn.vendor.name}
                </p>
              )}
              <p className="text-gray-600 dark:text-gray-400 mb-2">
                <span className="font-medium">Received Date:</span>{' '}
                {formatDateTime(grn.received_at || grn.created_at)}
              </p>
              {grn.processed_at && (
                <p className="text-gray-600 dark:text-gray-400 mb-2">
                  <span className="font-medium">Processed At:</span>{' '}
                  {formatDateTime(grn.processed_at)}
                </p>
              )}
            </div>
            <div>
              <h3 className="font-semibold text-gray-700 dark:text-gray-300 mb-3">Summary</h3>
              <p className="text-lg font-bold text-gray-900 dark:text-white">
                <span className="font-medium">Total Amount:</span>{' '}
                {formatCurrency(grn.total_amount || 0)}
              </p>
            </div>
          </div>
          {grn.notes && (
            <div className="mt-6 pt-6 border-t dark:border-gray-700">
              <h3 className="font-semibold text-gray-700 dark:text-gray-300 mb-2">Notes</h3>
              <p className="text-gray-600 dark:text-gray-400">{grn.notes}</p>
            </div>
          )}
        </CardContent>
      </Card>

      {grn.items && grn.items.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle>Items</CardTitle>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Product</TableHead>
                  <TableHead align="right">Quantity</TableHead>
                  <TableHead align="right">Unit Cost</TableHead>
                  <TableHead align="right">Total</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {grn.items.map((item) => (
                  <TableRow key={item.id}>
                    <TableCell className="font-medium">
                      {item.product?.name || 'Unknown Product'}
                    </TableCell>
                    <TableCell align="right">
                      {item.quantity} {item.product?.unit_of_measure || ''}
                    </TableCell>
                    <TableCell align="right">{formatCurrency(item.unit_cost || 0)}</TableCell>
                    <TableCell align="right">
                      {formatCurrency((item.quantity || 0) * (item.unit_cost || 0))}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}

      <Modal
        isOpen={showProcessModal}
        onClose={() => setShowProcessModal(false)}
        title="Process GRN"
        description="This will update inventory with the received items. This action cannot be undone."
      >
        <div className="space-y-4 mt-4">
          <div className="flex items-center gap-3 p-4 bg-blue-50 dark:bg-blue-950 border border-blue-200 dark:border-blue-800 rounded-lg">
            <input
              type="checkbox"
              id="print-labels-grn"
              checked={printLabelsAfterProcess}
              onChange={(e) => setPrintLabelsAfterProcess(e.target.checked)}
              className="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500 dark:border-gray-600 dark:bg-gray-700"
            />
            <label htmlFor="print-labels-grn" className="text-sm font-medium text-gray-700 dark:text-gray-300 cursor-pointer">
              Print labels for FG items after processing
            </label>
          </div>
          <p className="text-xs text-gray-500 dark:text-gray-400">
            If enabled, you'll be redirected to the label printing page to print labels for all finished goods items created from this GRN.
          </p>
        </div>
        <div className="flex justify-end gap-4 mt-6">
          <Button variant="outline" onClick={() => setShowProcessModal(false)}>
            Cancel
          </Button>
          <Button
            variant="primary"
            onClick={handleProcessGRN}
            disabled={processGRNMutation.isLoading}
            loading={processGRNMutation.isLoading}
          >
            Confirm Process
          </Button>
        </div>
      </Modal>
    </div>
  );
}

