import React from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { __ } from '@/lib/i18n';
import { CustomersApi } from '@/lib/api/customers';
import { api } from '@/lib/api';
import { OrdersApi } from '@/lib/api/orders';
import { showErrorToast, getPageLoadErrorMessage } from '@/lib/errorHandling';
import { usePageHeader } from '@/contexts/PageHeaderContext';
import { ErrorCard } from '@/components/ErrorCard';
import { Skeleton } from '@/components/ui/skeleton';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { VerticalTabForm, FormSection } from '@/components/VerticalTabForm';
import { ArrowLeft, Edit, Mail, Calendar, ShoppingBag, DollarSign, User, MapPin } from 'lucide-react';
import { formatMoney } from '@/lib/currency';

export default function CustomerDetail() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const customerId = parseInt(id || '0', 10);

  // Fetch customer data
  const customerQuery = useQuery({
    queryKey: ['customer', customerId],
    queryFn: () => CustomersApi.get(customerId),
    enabled: !!customerId,
  });

  // Fetch customer orders
  const ordersQuery = useQuery({
    queryKey: ['customer-orders', customerId],
    queryFn: () => OrdersApi.list({ customer_id: customerId, per_page: 100 }),
    enabled: !!customerId,
  });

  const customer = customerQuery.data;
  const orders = ordersQuery.data?.rows || [];
  const { setPageHeader, clearPageHeader } = usePageHeader();

  // Smart back handler: go back in history if available, otherwise fallback to /customers
  const handleBack = () => {
    if (window.history.state?.idx > 0) {
      navigate(-1); // Go back in history
    } else {
      navigate('/customers'); // Fallback to customers index
    }
  };

  // Page header
  React.useEffect(() => {
    if (!customer) {
      clearPageHeader();
      return;
    }

    const actions = (
      <div className="flex gap-2">
        <Button size="sm" variant="ghost" onClick={handleBack}>
          {__('Back')}
        </Button>
        <Button size="sm" onClick={() => navigate(`/customers/${customerId}/edit`)}>
          {__('Edit')}
        </Button>
      </div>
    );

    setPageHeader(
      customer.display_name || `${customer.first_name} ${customer.last_name}`,
      actions
    );

    return () => clearPageHeader();
  }, [customer, customerId, navigate, setPageHeader, clearPageHeader]);

  // Loading state
  if (customerQuery.isLoading) {
    return (
      <div className="space-y-4">
        <Skeleton className="h-32 w-full" />
        <Skeleton className="h-64 w-full" />
      </div>
    );
  }

  // Error state
  if (customerQuery.isError || !customer) {
    return (
      <ErrorCard
        title={__('Failed to load customer')}
        message={getPageLoadErrorMessage(customerQuery.error)}
        onRetry={() => customerQuery.refetch()}
      />
    );
  }

  // Calculate stats from orders
  const completedOrders = orders.filter((o: any) => o.status === 'completed' || o.status === 'processing');
  const totalSpent = completedOrders.reduce((sum: number, order: any) => sum + parseFloat(order.total || '0'), 0);

  return (
    <div className="space-y-6 pb-6">
      {/* Customer Info Header */}
      <Card className="p-6">
        <div className="flex items-start justify-between">
          <div className="flex items-center gap-4">
            <div className="w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center">
              <User className="w-8 h-8 text-primary" />
            </div>
            <div>
              <h2 className="text-2xl font-bold">
                {customer.display_name || `${customer.first_name} ${customer.last_name}`}
              </h2>
              <p className="text-muted-foreground">{customer.email}</p>
            </div>
          </div>
          <span className={`inline-flex items-center px-3 py-1 rounded-full text-sm font-medium ${
            customer.role === 'customer' ? 'bg-blue-100 text-blue-800' : 'bg-gray-100 text-gray-800'
          }`}>
            {customer.role === 'customer' ? __('Member') : __('Guest')}
          </span>
        </div>
      </Card>

      {/* Vertical Tabs */}
      <VerticalTabForm
        tabs={[
          { id: 'overview', label: __('Overview') },
          { id: 'orders', label: __('Orders') },
          { id: 'address', label: __('Address') },
        ]}
      >
        {/* Overview Section */}
        <FormSection id="overview">
          {/* Stats Grid */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
            <Card className="p-6">
              <div className="flex items-center gap-2 text-muted-foreground mb-2">
                <ShoppingBag className="w-5 h-5" />
                <span className="text-sm font-medium">{__('Total Orders')}</span>
              </div>
              <div className="text-3xl font-bold">{customer.stats?.total_orders || 0}</div>
            </Card>

            <Card className="p-6">
              <div className="flex items-center gap-2 text-muted-foreground mb-2">
                <DollarSign className="w-5 h-5" />
                <span className="text-sm font-medium">{__('Total Spent')}</span>
              </div>
              <div className="text-3xl font-bold">
                {customer.stats?.total_spent ? formatMoney(customer.stats.total_spent) : formatMoney(0)}
              </div>
            </Card>

            <Card className="p-6">
              <div className="flex items-center gap-2 text-muted-foreground mb-2">
                <Calendar className="w-5 h-5" />
                <span className="text-sm font-medium">{__('Registered')}</span>
              </div>
              <div className="text-xl font-bold">
                {new Date(customer.registered).toLocaleDateString('id-ID', {
                  year: 'numeric',
                  month: 'short',
                  day: 'numeric'
                })}
              </div>
            </Card>
          </div>

          {/* Contact Info */}
          <Card className="p-6">
            <h3 className="text-lg font-semibold mb-4 flex items-center gap-2">
              <Mail className="w-5 h-5" />
              {__('Contact Information')}
            </h3>
            <div className="space-y-3">
              <div>
                <div className="text-sm text-muted-foreground">{__('Email')}</div>
                <div className="font-medium">{customer.email}</div>
              </div>
              {customer.billing?.phone && (
                <div>
                  <div className="text-sm text-muted-foreground">{__('Phone')}</div>
                  <div className="font-medium">{customer.billing.phone}</div>
                </div>
              )}
            </div>
          </Card>
        </FormSection>

        {/* Orders Section */}
        <FormSection id="orders">
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-semibold">{__('Order History')}</h3>
              <div className="text-sm text-muted-foreground">
                {orders.length} {__('orders')}
              </div>
            </div>

            {ordersQuery.isLoading ? (
              <div className="space-y-2">
                <Skeleton className="h-16 w-full" />
                <Skeleton className="h-16 w-full" />
                <Skeleton className="h-16 w-full" />
              </div>
            ) : orders.length === 0 ? (
              <div className="text-center py-12 text-muted-foreground">
                <ShoppingBag className="w-16 h-16 mx-auto mb-3 opacity-50" />
                <p className="text-lg font-medium">{__('No orders yet')}</p>
                <p className="text-sm mt-1">{__('This customer hasn\'t placed any orders')}</p>
              </div>
            ) : (
              <>
                {/* Desktop: Table */}
                <div className="hidden md:block overflow-hidden rounded-lg border">
                  <table className="w-full">
                    <thead className="bg-muted/50">
                      <tr className="border-b">
                        <th className="text-left p-3 font-medium">{__('Order')}</th>
                        <th className="text-left p-3 font-medium">{__('Date')}</th>
                        <th className="text-left p-3 font-medium">{__('Status')}</th>
                        <th className="text-right p-3 font-medium">{__('Items')}</th>
                        <th className="text-right p-3 font-medium">{__('Total')}</th>
                      </tr>
                    </thead>
                    <tbody>
                      {orders.map((order: any) => (
                        <tr
                          key={order.id}
                          onClick={() => navigate(`/orders/${order.id}`)}
                          className="border-b hover:bg-muted/30 last:border-0 cursor-pointer"
                        >
                          <td className="p-3">
                            <span className="font-medium">#{order.number}</span>
                          </td>
                          <td className="p-3 text-sm text-muted-foreground">
                            {order.date ? new Date(order.date).toLocaleDateString('id-ID') : '-'}
                          </td>
                          <td className="p-3">
                            <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${
                              order.status === 'completed' ? 'bg-green-100 text-green-800' :
                              order.status === 'processing' ? 'bg-blue-100 text-blue-800' :
                              order.status === 'pending' ? 'bg-yellow-100 text-yellow-800' :
                              'bg-gray-100 text-gray-800'
                            }`}>
                              {order.status}
                            </span>
                          </td>
                          <td className="p-3 text-right text-sm">
                            {order.items_count || 0}
                          </td>
                          <td className="p-3 text-right font-medium">
                            {formatMoney(parseFloat(order.total || '0'))}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>

                {/* Mobile: Cards */}
                <div className="md:hidden space-y-2">
                  {orders.map((order: any) => (
                    <Link
                      key={order.id}
                      to={`/orders/${order.id}`}
                      className="block p-4 rounded-lg border border-border hover:bg-accent/50 transition-colors"
                    >
                      <div className="flex items-center justify-between">
                        <div className="flex-1">
                          <div className="flex items-center gap-3">
                            <span className="font-medium">#{order.number}</span>
                            <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${
                              order.status === 'completed' ? 'bg-green-100 text-green-800' :
                              order.status === 'processing' ? 'bg-blue-100 text-blue-800' :
                              order.status === 'pending' ? 'bg-yellow-100 text-yellow-800' :
                              'bg-gray-100 text-gray-800'
                            }`}>
                              {order.status}
                            </span>
                          </div>
                          <div className="text-sm text-muted-foreground mt-1">
                            {order.date ? new Date(order.date).toLocaleDateString('id-ID') : '-'}
                          </div>
                        </div>
                        <div className="text-right">
                          <div className="font-bold">{formatMoney(parseFloat(order.total || '0'))}</div>
                          <div className="text-sm text-muted-foreground">
                            {order.items_count || 0} {__('items')}
                          </div>
                        </div>
                      </div>
                    </Link>
                  ))}
                </div>
              </>
            )}
          </Card>
        </FormSection>

        {/* Address Section */}
        <FormSection id="address">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {/* Billing Address */}
            <Card className="p-6">
              <h3 className="text-lg font-semibold mb-4 flex items-center gap-2">
                <MapPin className="w-5 h-5" />
                {__('Billing Address')}
              </h3>
              {customer.billing && (customer.billing.address_1 || customer.billing.city) ? (
                <div className="space-y-1">
                  {customer.billing.first_name && customer.billing.last_name && (
                    <div className="font-medium">
                      {customer.billing.first_name} {customer.billing.last_name}
                    </div>
                  )}
                  {customer.billing.company && (
                    <div className="text-sm text-muted-foreground">{customer.billing.company}</div>
                  )}
                  {customer.billing.address_1 && <div>{customer.billing.address_1}</div>}
                  {customer.billing.address_2 && <div>{customer.billing.address_2}</div>}
                  <div>
                    {[customer.billing.city, customer.billing.state, customer.billing.postcode]
                      .filter(Boolean)
                      .join(', ')}
                  </div>
                  {customer.billing.country && <div>{customer.billing.country}</div>}
                  {customer.billing.phone && (
                    <div className="mt-3 pt-3 border-t">
                      <div className="text-sm text-muted-foreground">{__('Phone')}</div>
                      <div>{customer.billing.phone}</div>
                    </div>
                  )}
                </div>
              ) : (
                <div className="text-sm text-muted-foreground">{__('No billing address')}</div>
              )}
            </Card>

            {/* Shipping Address */}
            <Card className="p-6">
              <h3 className="text-lg font-semibold mb-4 flex items-center gap-2">
                <MapPin className="w-5 h-5" />
                {__('Shipping Address')}
              </h3>
              {customer.shipping && (customer.shipping.address_1 || customer.shipping.city) ? (
                <div className="space-y-1">
                  {customer.shipping.first_name && customer.shipping.last_name && (
                    <div className="font-medium">
                      {customer.shipping.first_name} {customer.shipping.last_name}
                    </div>
                  )}
                  {customer.shipping.company && (
                    <div className="text-sm text-muted-foreground">{customer.shipping.company}</div>
                  )}
                  {customer.shipping.address_1 && <div>{customer.shipping.address_1}</div>}
                  {customer.shipping.address_2 && <div>{customer.shipping.address_2}</div>}
                  <div>
                    {[customer.shipping.city, customer.shipping.state, customer.shipping.postcode]
                      .filter(Boolean)
                      .join(', ')}
                  </div>
                  {customer.shipping.country && <div>{customer.shipping.country}</div>}
                </div>
              ) : (
                <div className="text-sm text-muted-foreground">{__('No shipping address')}</div>
              )}
            </Card>
          </div>
        </FormSection>
      </VerticalTabForm>
    </div>
  );
}
