/**
 * Purchase Order Detail Page
 * View purchase order details
 */

'use client';

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

export default function PurchaseOrderDetailPage() {
  const router = useRouter();
  const params = useParams();
  const poId = parseInt(params.id);
  const queryClient = useQueryClient();
  const [showStatusModal, setShowStatusModal] = useState(false);
  const [newStatus, setNewStatus] = useState('');

  // Fetch purchase order details
  const { data: purchaseOrder, isLoading, error, refetch } = useQuery({
    queryKey: ['purchase-order', poId],
    queryFn: async () => {
      if (isNaN(poId)) {
        throw new Error('Invalid Purchase Order ID');
      }
      const response = await procurementAPI.getPurchaseOrder(poId);
      return response?.data || response;
    },
    enabled: !isNaN(poId),
  });

  // Update status mutation
  const updateStatusMutation = useMutation({
    mutationFn: async (status) => {
      return await procurementAPI.updatePurchaseOrderStatus(poId, status);
    },
    onSuccess: () => {
      queryClient.invalidateQueries(['purchase-order', poId]);
      queryClient.invalidateQueries(['purchase-orders']);
      toast.success(`Purchase order status updated to ${newStatus}`);
      setShowStatusModal(false);
      refetch();
    },
    onError: (error) => {
      const message = error?.response?.data?.message || error.message || 'Failed to update status';
      toast.error(message);
    },
  });

  const handleStatusChange = (status) => {
    setNewStatus(status);
    setShowStatusModal(true);
  };

  const confirmStatusChange = () => {
    updateStatusMutation.mutate(newStatus);
  };

  if (isLoading) {
    return <LoadingPage message="Loading purchase order 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 (!purchaseOrder) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-950 text-center text-gray-600">
        <p>Purchase order not found.</p>
        <Button onClick={() => router.back()} className="mt-4">
          Go Back
        </Button>
      </div>
    );
  }

  const getStatusVariant = (status) => {
    switch (status) {
      case 'COMPLETED':
      case 'CLOSED':
        return 'success';
      case 'CONFIRMED':
        return 'primary';
      case 'DRAFT':
        return 'warning';
      case 'CANCELLED':
        return 'danger';
      default:
        return 'default';
    }
  };

  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 Purchase Orders
        </Button>
        <div className="flex gap-2">
          {purchaseOrder.status === 'DRAFT' && (
            <>
              <Button
                variant="primary"
                onClick={() => handleStatusChange('CONFIRMED')}
                disabled={updateStatusMutation.isLoading}
                loading={updateStatusMutation.isLoading}
              >
                <CheckCircle className="w-4 h-4 mr-2" /> Confirm PO
              </Button>
            </>
          )}
          {purchaseOrder.status === 'CONFIRMED' && (
            <Button
              variant="secondary"
              onClick={() => handleStatusChange('CLOSED')}
              disabled={updateStatusMutation.isLoading}
              loading={updateStatusMutation.isLoading}
            >
              <XCircle className="w-4 h-4 mr-2" /> Close PO
            </Button>
          )}
          <Button
            variant="outline"
            onClick={() => router.push(`/procurement/purchase-orders/${poId}/edit`)}
          >
            <Edit className="w-4 h-4 mr-2" /> Edit
          </Button>
        </div>
      </div>

      <Card className="mb-6">
        <CardHeader>
          <CardTitle className="flex items-center justify-between">
            <span>Purchase Order #{purchaseOrder.po_number || purchaseOrder.id}</span>
            <Badge variant={getStatusVariant(purchaseOrder.status)}>
              {purchaseOrder.status || 'DRAFT'}
            </Badge>
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <h3 className="font-semibold text-gray-700 mb-3">Order Information</h3>
              <p className="text-gray-600 mb-2">
                <span className="font-medium">Vendor:</span>{' '}
                {purchaseOrder.vendor?.name || 'N/A'}
              </p>
              <p className="text-gray-600 mb-2">
                <span className="font-medium">Order Date:</span>{' '}
                {formatDateTime(purchaseOrder.order_date || purchaseOrder.created_at)}
              </p>
              {purchaseOrder.expected_delivery_date && (
                <p className="text-gray-600 mb-2">
                  <span className="font-medium">Expected Delivery:</span>{' '}
                  {formatDateTime(purchaseOrder.expected_delivery_date)}
                </p>
              )}
            </div>
            <div>
              <h3 className="font-semibold text-gray-700 mb-3">Summary</h3>
              <p className="text-gray-600 mb-2">
                <span className="font-medium">Subtotal:</span>{' '}
                {formatCurrency(purchaseOrder.subtotal || 0)}
              </p>
              <p className="text-gray-600 mb-2">
                <span className="font-medium">Tax:</span>{' '}
                {formatCurrency(purchaseOrder.tax_amount || 0)}
              </p>
              <p className="text-lg font-bold text-gray-900">
                <span className="font-medium">Total:</span>{' '}
                {formatCurrency(purchaseOrder.total_amount || 0)}
              </p>
            </div>
          </div>
          {purchaseOrder.notes && (
            <div className="mt-6 pt-6 border-t">
              <h3 className="font-semibold text-gray-700 mb-2">Notes</h3>
              <p className="text-gray-600">{purchaseOrder.notes}</p>
            </div>
          )}
        </CardContent>
      </Card>

      {purchaseOrder.items && purchaseOrder.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>
                {purchaseOrder.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>
      )}

      {/* Related GRNs */}
      {purchaseOrder.grns && purchaseOrder.grns.length > 0 && (
        <Card className="mb-6">
          <CardHeader>
            <CardTitle>Related GRNs</CardTitle>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>GRN Number</TableHead>
                  <TableHead>Received Date</TableHead>
                  <TableHead align="right">Total Amount</TableHead>
                  <TableHead>Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {purchaseOrder.grns.map((grn) => (
                  <TableRow key={grn.id}>
                    <TableCell className="font-medium">
                      {grn.grn_number || `GRN-${grn.id}`}
                    </TableCell>
                    <TableCell>{formatDateTime(grn.received_at || grn.created_at)}</TableCell>
                    <TableCell align="right">{formatCurrency(grn.total_amount || 0)}</TableCell>
                    <TableCell>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => router.push(`/procurement/grns/${grn.id}`)}
                      >
                        View
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}

      {/* Create GRN from PO */}
      {purchaseOrder.status === 'CONFIRMED' && (
        <Card>
          <CardHeader>
            <CardTitle>Quick Actions</CardTitle>
          </CardHeader>
          <CardContent>
            <Button
              variant="primary"
              onClick={() => router.push(`/procurement/grns/new?purchase_order_id=${poId}`)}
              className="flex items-center gap-2"
            >
              <FileText className="w-4 h-4" />
              Create GRN from this PO
            </Button>
          </CardContent>
        </Card>
      )}

      {/* Status Change Modal */}
      <Modal
        isOpen={showStatusModal}
        onClose={() => setShowStatusModal(false)}
        title={`Change Status to ${newStatus}`}
        description={`Are you sure you want to change this purchase order status to ${newStatus}?`}
      >
        <div className="flex justify-end gap-4 mt-6">
          <Button variant="outline" onClick={() => setShowStatusModal(false)}>
            Cancel
          </Button>
          <Button
            variant="primary"
            onClick={confirmStatusChange}
            disabled={updateStatusMutation.isLoading}
            loading={updateStatusMutation.isLoading}
          >
            Confirm
          </Button>
        </div>
      </Modal>
    </div>
  );
}


