/**
 * Vendor Detail Page
 * View vendor 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,
} from '@/components/ui';
import { formatDateTime } from '@/lib/utils/format';
import { ArrowLeft, Edit } from 'lucide-react';

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

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

  if (isLoading) {
    return <LoadingPage message="Loading vendor 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 (!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>
    );
  }

  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 Vendors
        </Button>
        <div className="flex gap-2">
          <Button
            variant="outline"
            onClick={() => router.push(`/procurement/vendors/${vendorId}/reports`)}
          >
            View Reports
          </Button>
          <Button variant="primary" onClick={() => router.push(`/procurement/vendors/${vendorId}/edit`)}>
            <Edit className="w-4 h-4 mr-2" /> Edit Vendor
          </Button>
        </div>
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center justify-between">
            <span>{vendor.name}</span>
            <Badge variant={(vendor.type || vendor.vendor_type) === 'REGISTERED' ? 'primary' : 'secondary'}>
              {(vendor.type || vendor.vendor_type) === 'REGISTERED' ? 'Registered' : 'Open Market'}
            </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">Contact Information</h3>
              {vendor.contact_person && (
                <p className="text-gray-600 mb-2">
                  <span className="font-medium">Contact Person:</span> {vendor.contact_person}
                </p>
              )}
              {vendor.email && (
                <p className="text-gray-600 mb-2">
                  <span className="font-medium">Email:</span> {vendor.email}
                </p>
              )}
              {vendor.phone && (
                <p className="text-gray-600 mb-2">
                  <span className="font-medium">Phone:</span> {vendor.phone}
                </p>
              )}
              {vendor.address && (
                <p className="text-gray-600 mb-2">
                  <span className="font-medium">Address:</span> {vendor.address}
                </p>
              )}
            </div>
            <div>
              <h3 className="font-semibold text-gray-700 mb-3">Business Information</h3>
              {vendor.kra_pin && (
                <p className="text-gray-600 mb-2">
                  <span className="font-medium">KRA PIN:</span> {vendor.kra_pin}
                </p>
              )}
              {vendor.payment_terms && (
                <p className="text-gray-600 mb-2">
                  <span className="font-medium">Payment Terms:</span> {vendor.payment_terms}
                </p>
              )}
              <p className="text-gray-600 mb-2">
                <span className="font-medium">Status:</span>{' '}
                <Badge variant={vendor.active !== false ? 'success' : 'default'}>
                  {vendor.active !== false ? 'Active' : 'Inactive'}
                </Badge>
              </p>
              <p className="text-gray-600 mb-2">
                <span className="font-medium">Created:</span> {formatDateTime(vendor.created_at)}
              </p>
            </div>
          </div>
          {vendor.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">{vendor.notes}</p>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}

