'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { ChevronDown, ChevronUp } from 'lucide-react';
import { toast } from 'sonner';
import { updateOrderAction } from '@/app/admin/orders/actions';
import { formatPrice } from '@/lib/utils';
import type { Order } from '@/types';

export function OrdersClient({ initialOrders }: { initialOrders: Order[] }) {
  const router = useRouter();
  const [expanded, setExpanded] = useState<Record<string, boolean>>({});

  async function handleUpdate(formData: FormData) {
    const result = await updateOrderAction(formData);
    if (result?.error) {
      toast.error(result.error);
    } else {
      toast.success('Order updated');
      router.refresh();
    }
  }

  function toggle(id: string) {
    setExpanded((prev) => ({ ...prev, [id]: !prev[id] }));
  }

  return (
    <div className="space-y-6">
      <h1 className="text-2xl font-bold">Orders</h1>

      <div className="overflow-hidden rounded-xl border bg-card">
        <table className="w-full text-left text-sm">
          <thead className="border-b bg-muted/50 text-muted-foreground">
            <tr>
              <th className="px-4 py-3 font-medium">Order #</th>
              <th className="px-4 py-3 font-medium">Customer</th>
              <th className="px-4 py-3 font-medium">Phone</th>
              <th className="px-4 py-3 font-medium">Total</th>
              <th className="px-4 py-3 font-medium">Method</th>
              <th className="px-4 py-3 font-medium">Status</th>
              <th className="px-4 py-3 font-medium">Payment</th>
              <th className="px-4 py-3 font-medium"></th>
            </tr>
          </thead>
          <tbody>
            {initialOrders.map((order) => (
              <>
                <tr key={order.id} className="border-b last:border-0">
                  <td className="px-4 py-3 font-mono">{order.orderNumber}</td>
                  <td className="px-4 py-3">{order.customerName}</td>
                  <td className="px-4 py-3">{order.customerPhone}</td>
                  <td className="px-4 py-3 font-medium">
                    {formatPrice(order.total)}
                  </td>
                  <td className="px-4 py-3 capitalize">{order.paymentMethod}</td>
                  <td className="px-4 py-3 capitalize">{order.status}</td>
                  <td className="px-4 py-3 capitalize">{order.paymentStatus}</td>
                  <td className="px-4 py-3">
                    <button
                      onClick={() => toggle(order.id)}
                      className="inline-flex items-center gap-1 rounded-lg border px-3 py-1 text-xs"
                    >
                      {expanded[order.id] ? (
                        <>
                          Hide <ChevronUp className="h-3 w-3" />
                        </>
                      ) : (
                        <>
                          Manage <ChevronDown className="h-3 w-3" />
                        </>
                      )}
                    </button>
                  </td>
                </tr>

                {expanded[order.id] && (
                  <tr className="border-b bg-muted/30 last:border-0">
                    <td colSpan={8} className="px-4 py-4">
                      <div className="grid gap-4 md:grid-cols-3">
                        <div>
                          <p className="text-sm font-medium">Items</p>
                          <ul className="mt-2 space-y-1 text-sm text-muted-foreground">
                            {order.items.map((item) => (
                              <li key={item.id}>
                                {item.name} x {item.quantity} —{' '}
                                {formatPrice(item.price * item.quantity)}
                              </li>
                            ))}
                          </ul>
                        </div>

                        <div>
                          <p className="text-sm font-medium">Delivery address</p>
                          <p className="mt-2 text-sm text-muted-foreground whitespace-pre-wrap">
                            {order.customerAddress}
                          </p>
                          {order.customerEmail && (
                            <p className="text-sm text-muted-foreground">
                              {order.customerEmail}
                            </p>
                          )}
                          {order.customerNotes && (
                            <p className="mt-2 text-sm text-muted-foreground">
                              Note: {order.customerNotes}
                            </p>
                          )}
                        </div>

                        <form
                          onSubmit={(e) => {
                            e.preventDefault();
                            handleUpdate(new FormData(e.currentTarget));
                          }}
                          className="space-y-2"
                        >
                          <input type="hidden" name="id" value={order.id} />
                          <div>
                            <label className="text-xs font-medium">Status</label>
                            <select
                              name="status"
                              defaultValue={order.status}
                              className="w-full rounded-lg border bg-background px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-ring"
                            >
                              <option value="pending">Pending</option>
                              <option value="paid">Paid</option>
                              <option value="processing">Processing</option>
                              <option value="shipped">Shipped</option>
                              <option value="delivered">Delivered</option>
                              <option value="cancelled">Cancelled</option>
                            </select>
                          </div>
                          <div>
                            <label className="text-xs font-medium">Payment</label>
                            <select
                              name="paymentStatus"
                              defaultValue={order.paymentStatus}
                              className="w-full rounded-lg border bg-background px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-ring"
                            >
                              <option value="pending">Pending</option>
                              <option value="paid">Paid</option>
                              <option value="failed">Failed</option>
                              <option value="refunded">Refunded</option>
                            </select>
                          </div>
                          <button
                            type="submit"
                            className="rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground"
                          >
                            Update
                          </button>
                        </form>
                      </div>
                    </td>
                  </tr>
                )}
              </>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
