'use client';

import { useState, useEffect, useCallback } from 'react';
import { Package, CheckCircle, XCircle } from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';

const ORANGE_BTN = 'bg-gradient-to-r from-orange-600 to-amber-500 shadow-sm';
const statusColors: Record<string, string> = {
  pending: 'bg-amber-50 text-amber-700 dark:bg-amber-950/30 dark:text-amber-400',
  confirmed: 'bg-orange-50 text-orange-700 dark:bg-orange-950/30 dark:text-orange-400',
  shipped: 'bg-amber-50 text-amber-700 dark:bg-amber-950/30 dark:text-amber-400',
  delivered: 'bg-emerald-50 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-400',
  cancelled: 'bg-red-50 text-red-700 dark:bg-red-950/30 dark:text-red-400'
};

export function AdminOrders() {
  const [orders, setOrders] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [filterStatus, setFilterStatus] = useState('all');

  const fetchOrders = useCallback(async () => {
    try { const r = await fetch('/api/admin/orders'); const d = await r.json(); if (d.success) setOrders(d.orders); } catch { }
    finally { setLoading(false); }
  }, []);
  useEffect(() => { fetchOrders(); }, [fetchOrders]);

  const updateStatus = async (orderId: string, status: string) => {
    try { const r = await fetch('/api/admin/orders', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ orderId, status }) }); const d = await r.json(); if (d.success) fetchOrders(); } catch { }
  };

  const filtered = filterStatus === 'all' ? orders : orders.filter((o) => o.status === filterStatus);
  if (loading) return <div className="flex items-center justify-center py-20"><span className="h-8 w-8 animate-spin rounded-full border-4 border-orange-500 border-t-transparent" /></div>;

  return (
    <div className="space-y-4">
      <div className="flex gap-2 overflow-x-auto pb-1">
        {['all', 'pending', 'confirmed', 'shipped', 'delivered', 'cancelled'].map((s) => (
          <Button key={s} variant={filterStatus === s ? 'default' : 'outline'} size="sm" className={`shrink-0 text-xs ${filterStatus === s ? ORANGE_BTN : ''}`} onClick={() => setFilterStatus(s)}>
            {s === 'all' ? 'All' : s.charAt(0).toUpperCase() + s.slice(1)}
          </Button>
        ))}
      </div>
      <div className="grid gap-4 sm:grid-cols-2">
        {filtered.map((o) => (
          <Card key={o.id} className="border-0 shadow-sm hover:shadow-md transition-shadow">
            <CardContent className="p-5">
              <div className="flex items-start justify-between">
                <div><p className="text-xs font-mono text-muted-foreground">#{o.id.slice(0, 10)}</p><p className="mt-1 text-lg font-bold">৳{o.totalAmount?.toLocaleString()}</p><p className="text-xs text-muted-foreground">{o.user?.name || 'Unknown'}</p></div>
                <Badge className={`text-[10px] border-0 ${statusColors[o.status] || ''}`}>{o.status.charAt(0).toUpperCase() + o.status.slice(1)}</Badge>
              </div>
              <Separator className="my-3" />
              <p className="text-xs text-muted-foreground line-clamp-1">{o.address}</p>
              <div className="mt-3 flex items-center gap-2">
                {o.status === 'pending' && <>
                  <Button size="sm" className="flex-1 text-xs bg-emerald-600 hover:bg-emerald-700" onClick={() => updateStatus(o.id, 'confirmed')}><CheckCircle className="mr-1 h-3 w-3" />Confirm</Button>
                  <Button size="sm" variant="outline" className="flex-1 text-xs text-red-600 hover:bg-red-50" onClick={() => updateStatus(o.id, 'cancelled')}><XCircle className="mr-1 h-3 w-3" />Cancel</Button>
                </>}
                {o.status === 'confirmed' && <Button size="sm" className="flex-1 text-xs bg-amber-600 hover:bg-amber-700" onClick={() => updateStatus(o.id, 'shipped')}><Package className="mr-1 h-3 w-3" />Ship Order</Button>}
                {o.status === 'shipped' && <Button size="sm" className="flex-1 text-xs bg-emerald-600 hover:bg-emerald-700" onClick={() => updateStatus(o.id, 'delivered')}><CheckCircle className="mr-1 h-3 w-3" />Delivered</Button>}
              </div>
            </CardContent>
          </Card>
        ))}
        {filtered.length === 0 && <div className="col-span-full py-16 text-center"><Package className="mx-auto h-12 w-12 text-slate-300" strokeWidth={1.5} /><p className="mt-3 text-sm text-muted-foreground">No orders found</p></div>}
      </div>
    </div>
  );
}
