'use client'

import Link from 'next/link'
import { useParams } from 'next/navigation'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { ArrowLeft } from 'lucide-react'
import { toast } from 'sonner'
import { api, type Order } from '@/lib/api'
import { Button } from '@/components/ui/Button'
import { Card } from '@/components/ui/Card'
import { Badge } from '@/components/ui/Badge'

export function OrderDetailPage() {
  const { t } = useTranslation()
  const params = useParams()
  const id = params?.id as string
  const queryClient = useQueryClient()

  const { data, refetch, isLoading } = useQuery({
    queryKey: ['order', id],
    queryFn: () => api.get<{ data: Order }>(`/orders/${id}`),
    enabled: Boolean(id),
  })

  const transition = useMutation({
    mutationFn: (action: string) => api.post(`/orders/${id}/${action}`),
    onSuccess: () => {
      toast.success(t('orders.messages.statusUpdated'))
      refetch()
      queryClient.invalidateQueries({ queryKey: ['orders'] })
    },
    onError: (err: { response?: { data?: { message?: string } } }) => {
      toast.error(err?.response?.data?.message || t('common.somethingWentWrong'))
    },
  })

  const order = data?.data?.data

  if (isLoading || !order) {
    return <div className="p-6 text-sm text-[var(--text-muted)]">{t('common.loading')}</div>
  }

  const actions: Array<{ status: string; action: string; label: string }> = [
    { status: 'draft', action: 'submit', label: t('orders.submit') },
    { status: 'submitted', action: 'approve', label: t('orders.approve') },
    { status: 'approved', action: 'process', label: t('orders.process') },
    { status: 'processing', action: 'deliver', label: t('orders.deliver') },
    { status: 'approved', action: 'deliver', label: t('orders.deliver') },
  ]

  return (
    <div className="space-y-5">
      <div className="animate-fade-in-up flex flex-wrap items-center justify-between gap-3">
        <div className="flex flex-wrap items-center gap-3">
          <Link href="/orders">
            <button
              type="button"
              className="premium-chip press-btn flex items-center gap-1.5 rounded-xl px-3 py-2 text-sm"
            >
              <ArrowLeft size={15} />
              {t('common.back')}
            </button>
          </Link>
          <h1 className="premium-heading text-2xl font-bold">{order.order_number}</h1>
          <Badge variant="muted">{t(`orders.status.${order.status}`, order.status)}</Badge>
        </div>
        <div className="flex flex-wrap gap-2">
          {actions
            .filter((a) => a.status === order.status)
            .map((a) => (
              <Button key={a.action} size="sm" onClick={() => transition.mutate(a.action)}>
                {a.label}
              </Button>
            ))}
          {!['delivered', 'cancelled'].includes(order.status) && (
            <Button size="sm" variant="secondary" onClick={() => transition.mutate('cancel')}>
              {t('orders.cancel')}
            </Button>
          )}
          {!['delivered', 'cancelled'].includes(order.status) && (
            <Link href={`/orders/${id}/edit`}>
              <Button size="sm" variant="secondary">
                {t('common.edit')}
              </Button>
            </Link>
          )}
        </div>
      </div>

      <Card elevated>
        <div className="grid gap-3 sm:grid-cols-3 text-sm">
          <div>
            <div className="text-xs text-[var(--text-muted)]">{t('orders.titleField')}</div>
            <div className="font-medium">{order.title}</div>
          </div>
          <div>
            <div className="text-xs text-[var(--text-muted)]">{t('orders.type')}</div>
            <div className="font-medium">
              {t(`orders.type_options.${order.order_type}`, order.order_type)}
            </div>
          </div>
          <div>
            <div className="text-xs text-[var(--text-muted)]">{t('orders.partner')}</div>
            <div className="font-medium">{order.partner?.name ?? '—'}</div>
          </div>
          <div>
            <div className="text-xs text-[var(--text-muted)]">{t('orders.project')}</div>
            <div className="font-medium">{order.project?.name ?? '—'}</div>
          </div>
          <div>
            <div className="text-xs text-[var(--text-muted)]">{t('orders.site')}</div>
            <div className="font-medium">{order.site?.name ?? '—'}</div>
          </div>
          <div>
            <div className="text-xs text-[var(--text-muted)]">{t('orders.total')}</div>
            <div className="font-medium">
              {Number(order.total).toLocaleString()} {order.currency}
            </div>
          </div>
        </div>
      </Card>

      <Card elevated>
        <h3 className="mb-3 text-sm font-semibold">{t('orders.lines')}</h3>
        <table className="min-w-full text-left text-sm">
          <thead className="text-xs text-[var(--text-muted)]">
            <tr>
              <th className="px-2 py-2">{t('orders.lineDescription')}</th>
              <th className="px-2 py-2">{t('orders.quantity')}</th>
              <th className="px-2 py-2">{t('orders.unitPrice')}</th>
              <th className="px-2 py-2">{t('orders.lineTotal')}</th>
            </tr>
          </thead>
          <tbody>
            {(order.lines ?? []).map((l) => (
              <tr key={l.id} className="border-t border-[var(--premium-divider)]">
                <td className="px-2 py-2">{l.description}</td>
                <td className="px-2 py-2">{l.quantity}</td>
                <td className="px-2 py-2">{l.unit_price}</td>
                <td className="px-2 py-2">{l.line_total}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  )
}
