/**
 * Vendor Reports Page
 * View vendor performance and analytics
 */

'use client';

import { useParams, useRouter } from 'next/navigation';
import { useQuery } from '@tanstack/react-query';
import { procurementAPI, salesAPI } from '@/lib/api';
import {
  Button,
  Card,
  CardHeader,
  CardTitle,
  CardContent,
  LoadingPage,
  Table,
  TableHeader,
  TableBody,
  TableRow,
  TableHead,
  TableCell,
  Badge,
} from '@/components/ui';
import { formatCurrency, formatDateTime } from '@/lib/utils/format';
import { ArrowLeft, TrendingUp, Package, FileText } from 'lucide-react';

export default function VendorReportsPage() {
  const router = useRouter();
  const params = useParams();
  const vendorId = parseInt(params.id);

  // Fetch vendor
  const { data: vendor, isLoading: isLoadingVendor } = useQuery({
    queryKey: ['vendor', vendorId],
    queryFn: async () => {
      const response = await procurementAPI.getVendor(vendorId);
      return response?.data || response;
    },
  });

  // Fetch purchase orders for this vendor
  const { data: posData, isLoading: isLoadingPOs } = useQuery({
    queryKey: ['vendor-pos', vendorId],
    queryFn: async () => {
      const response = await procurementAPI.listPurchaseOrders({ vendor_id: vendorId, limit: 100 });
      return response.data || response;
    },
    enabled: !!vendor,
  });

  // Fetch GRNs for this vendor
  const { data: grnsData, isLoading: isLoadingGRNs } = useQuery({
    queryKey: ['vendor-grns', vendorId],
    queryFn: async () => {
      const response = await procurementAPI.listGRNs({ vendor_id: vendorId, limit: 100 });
      return response.data || response;
    },
    enabled: !!vendor,
  });

  if (isLoadingVendor) {
    return <LoadingPage message="Loading vendor reports..." />;
  }

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

  const purchaseOrders = posData?.purchaseOrders || posData?.purchase_orders || [];
  const grns = grnsData?.grns || [];

  // Calculate statistics
  const totalPOs = purchaseOrders.length;
  const confirmedPOs = purchaseOrders.filter((po) => po.status === 'CONFIRMED').length;
  const closedPOs = purchaseOrders.filter((po) => po.status === 'CLOSED').length;
  const totalPOValue = purchaseOrders.reduce((sum, po) => sum + (po.total_amount || 0), 0);

  const totalGRNs = grns.length;
  const processedGRNs = grns.filter((grn) => grn.processed_at).length;
  const totalGRNValue = grns.reduce((sum, grn) => sum + (grn.total_amount || 0), 0);

  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 Vendor
        </Button>
        <Button variant="outline" onClick={() => router.push(`/procurement/vendors/${vendorId}`)}>
          View Vendor Details
        </Button>
      </div>

      <div className="mb-6">
        <h1 className="text-3xl font-bold text-gray-900 dark:text-white">Vendor Reports</h1>
        <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">{vendor.name}</p>
      </div>

      {/* Statistics Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
        <Card>
          <CardContent className="p-6 bg-gray-50 dark:bg-gray-950">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600">Total POs</p>
                <p className="text-2xl font-bold text-gray-900">{totalPOs}</p>
              </div>
              <FileText className="w-8 h-8 text-blue-500" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-6 bg-gray-50 dark:bg-gray-950">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600">PO Value</p>
                <p className="text-2xl font-bold text-gray-900">{formatCurrency(totalPOValue)}</p>
              </div>
              <TrendingUp className="w-8 h-8 text-green-500" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-6 bg-gray-50 dark:bg-gray-950">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600">Total GRNs</p>
                <p className="text-2xl font-bold text-gray-900">{totalGRNs}</p>
              </div>
              <Package className="w-8 h-8 text-purple-500" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-6 bg-gray-50 dark:bg-gray-950">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600">GRN Value</p>
                <p className="text-2xl font-bold text-gray-900">{formatCurrency(totalGRNValue)}</p>
              </div>
              <TrendingUp className="w-8 h-8 text-orange-500" />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Purchase Orders */}
      <Card className="mb-6">
        <CardHeader>
          <CardTitle>Purchase Orders ({totalPOs})</CardTitle>
        </CardHeader>
        <CardContent>
          {isLoadingPOs ? (
            <div className="text-center py-8">Loading...</div>
          ) : purchaseOrders.length === 0 ? (
            <div className="text-center py-8 text-gray-500">No purchase orders found.</div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>PO Number</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Date</TableHead>
                  <TableHead align="right">Amount</TableHead>
                  <TableHead>Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {purchaseOrders.map((po) => (
                  <TableRow key={po.id}>
                    <TableCell className="font-medium">
                      {po.po_number || `PO-${po.id}`}
                    </TableCell>
                    <TableCell>
                      <Badge
                        variant={
                          po.status === 'CLOSED'
                            ? 'success'
                            : po.status === 'CONFIRMED'
                            ? 'primary'
                            : 'warning'
                        }
                      >
                        {po.status}
                      </Badge>
                    </TableCell>
                    <TableCell>{formatDateTime(po.created_at)}</TableCell>
                    <TableCell align="right">{formatCurrency(po.total_amount || 0)}</TableCell>
                    <TableCell>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => router.push(`/procurement/purchase-orders/${po.id}`)}
                      >
                        View
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      {/* GRNs */}
      <Card>
        <CardHeader>
          <CardTitle>Goods Received Notes ({totalGRNs})</CardTitle>
        </CardHeader>
        <CardContent>
          {isLoadingGRNs ? (
            <div className="text-center py-8">Loading...</div>
          ) : grns.length === 0 ? (
            <div className="text-center py-8 text-gray-500">No GRNs found.</div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>GRN Number</TableHead>
                  <TableHead>Received Date</TableHead>
                  <TableHead align="right">Amount</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {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>
                      {grn.processed_at ? (
                        <Badge variant="success">Processed</Badge>
                      ) : (
                        <Badge variant="warning">Pending</Badge>
                      )}
                    </TableCell>
                    <TableCell>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => router.push(`/procurement/grns/${grn.id}`)}
                      >
                        View
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>
    </div>
  );
}

