/**
 * Customer Detail Page
 * View customer details and sales history
 */

'use client';

import { useQuery } from '@tanstack/react-query';
import { useRouter, useParams } from 'next/navigation';
import { customersAPI } from '@/lib/api/customers';
import { salesAPI } from '@/lib/api/sales';
import { Button, Card, CardHeader, CardTitle, CardContent, Badge, LoadingSpinner } from '@/components/ui';
import { CUSTOMER_TYPES } from '@/lib/utils/constants';
import { formatCurrency, formatDate, formatPhone } from '@/lib/utils/format';
import { ArrowLeft, User } from 'lucide-react';
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from '@/components/ui';

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

  // Fetch customer details
  const { data: customer, isLoading, error } = useQuery({
    queryKey: ['customer', customerId],
    queryFn: async () => {
      const response = await customersAPI.getById(customerId);
      // API returns { success: true, message: "...", data: { customer object } }
      // axios interceptor already extracts response.data, so response is the JSON object
      return response?.data || response;
    },
  });

  // Fetch customer sales
  const { data: salesData } = useQuery({
    queryKey: ['customer-sales', customerId],
    queryFn: async () => {
      const response = await salesAPI.list({ customer_id: customerId, limit: 20 });
      return response.data || response;
    },
    enabled: !!customer,
  });

  if (isLoading) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-950">
        <div className="flex justify-center py-12">
          <LoadingSpinner size="lg" />
        </div>
      </div>
    );
  }

  if (error || !customer) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-950">
        <Card>
          <CardContent className="pt-6">
            <div className="text-center py-12">
              <p className="text-red-600 dark:text-red-400 mb-4">
                {error?.response?.data?.message || 'Customer not found'}
              </p>
              <Button onClick={() => router.push('/customers')} variant="outline">
                Back to Customers
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  const sales = salesData?.sales || [];

  return (
    <div className="p-6 bg-gray-50 dark:bg-gray-950 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Button
            variant="outline"
            onClick={() => router.push('/customers')}
            className="flex items-center gap-2"
          >
            <ArrowLeft className="w-4 h-4" />
            Back
          </Button>
          <div>
            <h1 className="text-3xl font-bold text-gray-900 dark:text-white">{customer.name}</h1>
            <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
              Customer Details
            </p>
          </div>
        </div>
        {/* Edit button removed - customer registration disabled, walk-in customers only */}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Main Content */}
        <div className="lg:col-span-2 space-y-6">
          {/* Customer Information */}
          <Card>
            <CardHeader>
              <CardTitle>Customer Information</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="text-sm font-medium text-gray-500">Customer Type</label>
                  <div className="mt-1">
                    <Badge variant={customer.customer_type === 'B2B' ? 'primary' : 'info'}>
                      {customer.customer_type}
                    </Badge>
                  </div>
                </div>
                <div>
                  <label className="text-sm font-medium text-gray-500">Status</label>
                  <div className="mt-1">
                    {customer.active ? (
                      <Badge variant="success">Active</Badge>
                    ) : (
                      <Badge variant="default">Inactive</Badge>
                    )}
                  </div>
                </div>
                {customer.email && (
                  <div>
                    <label className="text-sm font-medium text-gray-500">Email</label>
                    <p className="mt-1">{customer.email}</p>
                  </div>
                )}
                {customer.phone && (
                  <div>
                    <label className="text-sm font-medium text-gray-500">Phone</label>
                    <p className="mt-1">{formatPhone(customer.phone)}</p>
                  </div>
                )}
                {customer.kra_pin && (
                  <div>
                    <label className="text-sm font-medium text-gray-500">KRA PIN</label>
                    <p className="mt-1 font-mono">{customer.kra_pin}</p>
                  </div>
                )}
                {customer.customer_type === 'B2B' && (
                  <div>
                    <label className="text-sm font-medium text-gray-500">Credit Limit</label>
                    <p className="mt-1 font-medium">{formatCurrency(customer.credit_limit || 0)}</p>
                  </div>
                )}
              </div>

              <div className="grid grid-cols-2 gap-4 pt-4 border-t">
                <div>
                  <label className="text-sm font-medium text-gray-500">Created</label>
                  <p className="mt-1 text-sm text-gray-600">{formatDate(customer.created_at)}</p>
                </div>
                <div>
                  <label className="text-sm font-medium text-gray-500">Last Updated</label>
                  <p className="mt-1 text-sm text-gray-600">{formatDate(customer.updated_at)}</p>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Sales History */}
          <Card>
            <CardHeader>
              <CardTitle>Recent Sales</CardTitle>
            </CardHeader>
            <CardContent>
              {sales.length === 0 ? (
                <div className="text-center py-8 text-gray-500">
                  <p>No sales found for this customer</p>
                </div>
              ) : (
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Invoice #</TableHead>
                      <TableHead>Date</TableHead>
                      <TableHead>Status</TableHead>
                      <TableHead align="right">Total</TableHead>
                      <TableHead align="right">Actions</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {sales.map((sale) => (
                      <TableRow key={sale.id}>
                        <TableCell>
                          <span className="font-mono font-medium">{sale.invoice_no || `#${sale.id}`}</span>
                        </TableCell>
                        <TableCell>
                          {formatDate(sale.created_at)}
                        </TableCell>
                        <TableCell>
                          <Badge variant={
                            sale.status === 'PAID' ? 'success' :
                            sale.status === 'DRAFT' ? 'warning' : 'danger'
                          }>
                            {sale.status}
                          </Badge>
                        </TableCell>
                        <TableCell align="right">
                          <span className="font-medium">{formatCurrency(sale.total)}</span>
                        </TableCell>
                        <TableCell align="right">
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => router.push(`/sales/${sale.id}`)}
                          >
                            View
                          </Button>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              )}
            </CardContent>
          </Card>
        </div>

        {/* Sidebar */}
        <div className="space-y-6">
          {/* Quick Info */}
          <Card>
            <CardHeader>
              <CardTitle>Quick Info</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="flex items-center gap-3">
                <User className="w-5 h-5 text-gray-400" />
                <div>
                  <p className="text-sm text-gray-500">Customer ID</p>
                  <p className="font-medium">{customer.id}</p>
                </div>
              </div>
              {salesData?.pagination?.total > 0 && (
                <div>
                  <p className="text-sm text-gray-500">Total Sales</p>
                  <p className="font-medium text-lg">{salesData.pagination.total}</p>
                </div>
              )}
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}

