'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { getCustomers, getProducts } from '@/lib/api/agent'
import { createOrder, triggerOrderCreated } from '@/lib/api/agent'
import { Customer, Product } from '@/lib/api/agent'
import { Button } from '@/components/ui/Button'
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/Card'
import { Input } from '@/components/ui/Input'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/Select'
import { Spinner } from '@/components/ui/Spinner'
import { Skeleton } from '@/components/ui/Skeleton'
import { ErrorState } from '@/components/ui/ErrorState'
import { Package, User, CreditCard, AlertCircle, CheckCircle, Zap, ArrowRight } from 'lucide-react'
import { cn } from '@/lib/utils'
import { formatCurrency } from '@/lib/types'

interface FormItem {
  productId: string
  quantity: number
}

export default function NewOrderPage() {
  const router = useRouter()
  const [customers, setCustomers] = useState<Customer[]>([])
  const [products, setProducts] = useState<Product[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [submitting, setSubmitting] = useState(false)

  const [form, setForm] = useState({
    customer_id: '',
    priority: 'normal',
    items: [{ productId: '', quantity: 1 }] as FormItem[],
  })

  useEffect(() => {
    async function load() {
      try {
        const [custRes, prodRes] = await Promise.all([getCustomers(), getProducts()])
        if (!custRes.success) throw new Error(custRes.message)
        if (!prodRes.success) throw new Error(prodRes.message)
        setCustomers(custRes.data.customers)
        setProducts(prodRes.data.products.filter(p => p.active))
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Failed to load data')
      } finally {
        setLoading(false)
      }
    }
    load()
  }, [])

  function addItem() {
    setForm(prev => ({ ...prev, items: [...prev.items, { productId: '', quantity: 1 }] }))
  }

  function removeItem(index: number) {
    if (form.items.length <= 1) return
    setForm(prev => ({ ...prev, items: prev.items.filter((_, i) => i !== index) }))
  }

  function updateItem(index: number, field: 'productId' | 'quantity', value: string | number) {
    setForm(prev => {
      const newItems = [...prev.items]
      newItems[index] = { ...newItems[index], [field]: value }
      return { ...prev, items: newItems }
    })
  }

  function calculateTotal(): number {
    return form.items.reduce((sum, item) => {
      const product = products.find(p => p.id === item.productId)
      return sum + (product?.unit_price || 0) * item.quantity
    }, 0)
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    setError('')
    setSubmitting(true)

    const itemsPayload = form.items.map(item => {
      const product = products.find(p => p.id === item.productId)
      return {
        product_id: item.productId,
        quantity: item.quantity,
        unit_price: product?.unit_price || 0,
      }
    })

    const createRes = await createOrder({
      customer_id: form.customer_id,
      status: 'pending',
      priority: form.priority,
      total_amount: calculateTotal(),
      items: itemsPayload,
    })

    if (!createRes.success) {
      setError(createRes.message)
      setSubmitting(false)
      return
    }

    const orderId = createRes.data.order.id

    // Trigger agent analysis
    const triggerRes = await triggerOrderCreated(orderId)
    if (!triggerRes.success) {
      console.warn('Failed to trigger agent:', triggerRes.message)
    }

    router.push(`/dashboard/orders/${orderId}`)
    router.refresh()
  }

  if (loading) {
    return (
      <div className="space-y-6">
        <div><h1 className="text-2xl font-bold">Create Order</h1></div>
        <Card><CardContent className="p-6"><Skeleton className="h-10 w-full" /><div className="space-y-3 mt-4">{Array.from({length:5}).map((_,i)=>(<Skeleton key={i} className="h-4 w-full" />))}</div></CardContent></Card>
      </div>
    )
  }

  if (error && !submitting) {
    return <ErrorState message={error} onRetry={() => window.location.reload()} />
  }

  return (
    <div className="space-y-6 max-w-3xl">
      <div>
        <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Create New Order</h1>
        <p className="text-gray-500 dark:text-gray-400">Fill in the details below to create an order and trigger IMBARAGA</p>
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2"><Package className="h-5 w-5" /> Order Details</CardTitle>
          <CardDescription>Customer and priority information</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Customer *</label>
            <Select value={form.customer_id} onValueChange={v => setForm({ ...form, customer_id: v })} required>
              <SelectTrigger className="w-full">
                <SelectValue placeholder="Select a customer" />
              </SelectTrigger>
              <SelectContent>
                {customers.map(c => (
                  <SelectItem key={c.id} value={c.id}>{c.name} ({c.email})</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Priority *</label>
            <Select value={form.priority} onValueChange={v => setForm({ ...form, priority: v })} required>
              <SelectTrigger className="w-full max-w-xs">
                <SelectValue placeholder="Select priority" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="low">Low</SelectItem>
                <SelectItem value="normal">Normal</SelectItem>
                <SelectItem value="high">High</SelectItem>
                <SelectItem value="urgent">Urgent</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="flex flex-row items-center justify-between">
          <div>
            <CardTitle className="flex items-center gap-2"><Package className="h-5 w-5" /> Order Items</CardTitle>
            <CardDescription>Add products to this order</CardDescription>
          </div>
          <Button variant="outline" size="sm" onClick={addItem} disabled={submitting}>
            <Package className="h-4 w-4 mr-2" /> Add Item
          </Button>
        </CardHeader>
        <CardContent className="space-y-4">
          {form.items.map((item, index) => (
            <div key={index} className="flex flex-col sm:flex-row gap-4 p-4 rounded-lg border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50">
              <div className="flex-1">
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Product *</label>
                <Select value={item.productId} onValueChange={v => updateItem(index, 'productId', v)} required>
                  <SelectTrigger className="w-full">
                    <SelectValue placeholder="Select product" />
                  </SelectTrigger>
                  <SelectContent>
                    {products.map(p => (
                      <SelectItem key={p.id} value={p.id}>{p.name} (${p.unit_price}) - SKU: {p.sku}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="w-32">
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Quantity *</label>
                <Input
                  type="number"
                  min="1"
                  value={item.quantity}
                  onChange={e => updateItem(index, 'quantity', parseInt(e.target.value) || 1)}
                  required
                  className="w-full"
                />
              </div>
              <div className="flex items-end">
                <div className="w-32">
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Line Total</label>
                  <div className="text-lg font-semibold text-gray-900 dark:text-white">
                    {(() => {
                      const product = products.find(p => p.id === item.productId)
                      return formatCurrency((product?.unit_price || 0) * item.quantity)
                    })()}
                  </div>
                </div>
                {form.items.length > 1 && (
                  <Button variant="ghost" size="sm" className="text-red-600 hover:text-red-700" onClick={() => removeItem(index)} disabled={submitting}>
                    <AlertCircle className="h-4 w-4" />
                  </Button>
                )}
              </div>
            </div>
          ))}
        </CardContent>
      </Card>

      {/* Order Summary */}
      <Card className="bg-indigo-50 dark:bg-indigo-900/20 border-indigo-200 dark:border-indigo-800">
        <CardContent className="p-6">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-lg font-semibold text-indigo-900 dark:text-indigo-100">Order Summary</h3>
            <div className="text-2xl font-bold text-indigo-600 dark:text-indigo-400">{formatCurrency(calculateTotal())}</div>
          </div>
          <div className="text-sm text-indigo-700 dark:text-indigo-300">
            {form.items.length} item(s) • {form.items.reduce((sum, i) => sum + i.quantity, 0)} total units
          </div>
        </CardContent>
      </Card>

      {error && (
        <div className="flex items-center gap-2 p-3 rounded-lg bg-red-50 text-red-700 dark:bg-red-900/30 dark:text-red-300 text-sm">
          <AlertCircle className="h-4 w-4 flex-shrink-0" />
          <span>{error}</span>
        </div>
      )}

      <div className="flex gap-4">
        <Button type="submit" form="order-form" className="flex-1" size="lg" loading={submitting}>
          {submitting ? (
            <><Spinner className="mr-2" /> Creating order & triggering IMBARAGA...</>
          ) : (
            <>
              <Zap className="h-4 w-4 mr-2" />
              Create Order & Trigger Agent
            </>
          )}
        </Button>
        <Button type="button" variant="outline" onClick={() => router.back()} disabled={submitting} className="px-6">
          Cancel
        </Button>
      </div>

      <form id="order-form" onSubmit={handleSubmit} className="hidden" />
    </div>
  )
}