'use client'

import Link from 'next/link'
import { useParams, useRouter } from 'next/navigation'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { ArrowLeft, Download } from 'lucide-react'
import { toast } from 'sonner'
import { api, type Offer, 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 OfferDetailPage() {
  const { t } = useTranslation()
  const params = useParams()
  const router = useRouter()
  const id = params?.id as string
  const queryClient = useQueryClient()

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

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

  const convert = useMutation({
    mutationFn: () => api.post<{ data: Order }>(`/offers/${id}/convert-to-order`),
    onSuccess: (res) => {
      toast.success(t('offers.messages.converted'))
      queryClient.invalidateQueries({ queryKey: ['offers'] })
      queryClient.invalidateQueries({ queryKey: ['orders'] })
      const orderId = res.data?.data?.id
      if (orderId) router.push(`/orders/${orderId}`)
      else refetch()
    },
    onError: (err: { response?: { data?: { message?: string } } }) => {
      toast.error(err?.response?.data?.message || t('common.somethingWentWrong'))
    },
  })

  const handleExport = async () => {
    try {
      const res = await api.get(`/offers/${id}/export/pdf`, { responseType: 'blob' })
      const url = window.URL.createObjectURL(new Blob([res.data as BlobPart]))
      const a = document.createElement('a')
      a.href = url
      a.download = `offer_${id}.pdf`
      a.click()
      window.URL.revokeObjectURL(url)
    } catch {
      toast.error(t('common.somethingWentWrong'))
    }
  }

  const offer = data?.data?.data

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

  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="/offers">
            <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">{offer.offer_number}</h1>
          <Badge variant="muted">{t(`offers.status.${offer.status}`, offer.status)}</Badge>
        </div>
        <div className="flex flex-wrap gap-2">
          <Button size="sm" variant="secondary" onClick={handleExport}>
            <Download size={14} />
            PDF
          </Button>
          {offer.status === 'draft' && (
            <Button size="sm" onClick={() => transition.mutate('send')}>
              {t('offers.send')}
            </Button>
          )}
          {offer.status === 'sent' && (
            <>
              <Button size="sm" onClick={() => transition.mutate('accept')}>
                {t('offers.accept')}
              </Button>
              <Button size="sm" variant="secondary" onClick={() => transition.mutate('reject')}>
                {t('offers.reject')}
              </Button>
            </>
          )}
          {['sent', 'accepted'].includes(offer.status) && (
            <Button size="sm" onClick={() => convert.mutate()}>
              {t('offers.convertToOrder')}
            </Button>
          )}
          {offer.status !== 'converted' && (
            <Link href={`/offers/${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('offers.titleField')}</div>
            <div className="font-medium">{offer.title}</div>
          </div>
          <div>
            <div className="text-xs text-[var(--text-muted)]">{t('offers.partner')}</div>
            <div className="font-medium">{offer.partner?.name ?? '—'}</div>
          </div>
          <div>
            <div className="text-xs text-[var(--text-muted)]">{t('offers.project')}</div>
            <div className="font-medium">{offer.project?.name ?? '—'}</div>
          </div>
          <div>
            <div className="text-xs text-[var(--text-muted)]">{t('offers.validUntil')}</div>
            <div className="font-medium">{offer.valid_until?.slice(0, 10) ?? '—'}</div>
          </div>
          <div>
            <div className="text-xs text-[var(--text-muted)]">{t('offers.subtotal')}</div>
            <div className="font-medium">{Number(offer.subtotal).toLocaleString()}</div>
          </div>
          <div>
            <div className="text-xs text-[var(--text-muted)]">{t('offers.total')}</div>
            <div className="font-medium">
              {Number(offer.total).toLocaleString()} {offer.currency}
            </div>
          </div>
        </div>
      </Card>

      <Card elevated>
        <h3 className="mb-3 text-sm font-semibold">{t('offers.lines')}</h3>
        <div className="overflow-x-auto">
          <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('offers.lineDescription')}</th>
                <th className="px-2 py-2">{t('offers.quantity')}</th>
                <th className="px-2 py-2">{t('offers.unitPrice')}</th>
                <th className="px-2 py-2">{t('offers.lineTotal')}</th>
              </tr>
            </thead>
            <tbody>
              {(offer.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>
        </div>
      </Card>
    </div>
  )
}
