'use client'

import { useMemo, useState } from 'react'
import Link from 'next/link'
import { useRouter, useSearchParams } from 'next/navigation'
import { useMutation, useQuery } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { ArrowLeft, Plus, Trash2 } from 'lucide-react'
import { toast } from 'sonner'
import { api, type PaginatedResponse, type Partner } from '@/lib/api'
import { Button } from '@/components/ui/Button'
import { Input } from '@/components/ui/Input'
import { Select } from '@/components/ui/Select'
import { Card } from '@/components/ui/Card'

type Line = {
  description: string
  quantity: string
  unit_price: string
  tax_rate: string
  agreed_unit_price: string
}

const emptyLine = (): Line => ({
  description: '',
  quantity: '1',
  unit_price: '0',
  tax_rate: '0',
  agreed_unit_price: '',
})

export function InvoiceFormPage() {
  const { t } = useTranslation()
  const router = useRouter()
  const searchParams = useSearchParams()
  const defaultType = searchParams.get('type') === 'purchase' ? 'purchase' : 'sales'

  const [invoiceType, setInvoiceType] = useState(defaultType)
  const [partnerId, setPartnerId] = useState('')
  const [issueDate, setIssueDate] = useState('')
  const [dueDate, setDueDate] = useState('')
  const [currency, setCurrency] = useState('EUR')
  const [notes, setNotes] = useState('')
  const [lines, setLines] = useState<Line[]>([emptyLine()])

  const { data: partnersData } = useQuery({
    queryKey: ['partners-all'],
    queryFn: () => api.get<PaginatedResponse<Partner>>('/partners', { params: { per_page: 'all' } }),
  })

  const partnerOptions = useMemo(
    () => [
      { value: '', label: t('finance.selectPartner') },
      ...(partnersData?.data.data ?? []).map((p) => ({
        value: String(p.id),
        label: `${p.client_code} — ${p.name}`,
      })),
    ],
    [partnersData, t],
  )

  const create = useMutation({
    mutationFn: () =>
      api.post('/invoices', {
        invoice_type: invoiceType,
        partner_id: Number(partnerId),
        issue_date: issueDate || undefined,
        due_date: dueDate || undefined,
        currency,
        notes: notes || undefined,
        lines: lines.map((l) => ({
          description: l.description,
          quantity: Number(l.quantity || 0),
          unit_price: Number(l.unit_price || 0),
          tax_rate: Number(l.tax_rate || 0),
          agreed_unit_price: l.agreed_unit_price === '' ? undefined : Number(l.agreed_unit_price),
        })),
      }),
    onSuccess: (res) => {
      toast.success(t('finance.messages.created'))
      const id = (res.data as { data?: { id?: number } })?.data?.id
      router.push(id ? `/finance/invoices/${id}` : '/finance/invoices')
    },
    onError: (err: { response?: { data?: { message?: string | string[] } } }) => {
      const raw = err?.response?.data?.message
      const msg = Array.isArray(raw) ? raw.join(', ') : raw
      toast.error(msg || t('common.somethingWentWrong'))
    },
  })

  const updateLine = (idx: number, patch: Partial<Line>) => {
    setLines((prev) => prev.map((l, i) => (i === idx ? { ...l, ...patch } : l)))
  }

  return (
    <div className="space-y-5">
      <div className="animate-fade-in-up flex items-center gap-3">
        <Link href={invoiceType === 'purchase' ? '/finance/purchases' : '/finance/invoices'}>
          <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">{t('finance.createInvoice')}</h1>
      </div>

      <Card elevated className="animate-fade-in-up stagger-1 space-y-4">
        <div className="grid gap-4 sm:grid-cols-2">
          <Select
            label={t('finance.type')}
            value={invoiceType}
            onChange={(e) => setInvoiceType(e.target.value as 'sales' | 'purchase')}
            options={[
              { value: 'sales', label: t('finance.typeSales') },
              { value: 'purchase', label: t('finance.typePurchase') },
            ]}
          />
          <Select
            label={t('finance.partner')}
            value={partnerId}
            onChange={(e) => setPartnerId(e.target.value)}
            options={partnerOptions}
          />
          <Input
            label={t('finance.issueDate')}
            type="date"
            value={issueDate}
            onChange={(e) => setIssueDate(e.target.value)}
            autoComplete="off"
          />
          <Input
            label={t('finance.dueDate')}
            type="date"
            value={dueDate}
            onChange={(e) => setDueDate(e.target.value)}
            autoComplete="off"
          />
          <Input
            label={t('finance.currency')}
            value={currency}
            maxLength={3}
            placeholder="EUR"
            autoComplete="off"
            onChange={(e) => setCurrency(e.target.value.toUpperCase().replace(/[^A-Z]/g, '').slice(0, 3))}
          />
          <Input
            label={t('finance.notes')}
            value={notes}
            autoComplete="off"
            onChange={(e) => setNotes(e.target.value)}
          />
        </div>

        <div className="space-y-3">
          <div className="flex items-center justify-between">
            <h2 className="font-semibold">{t('finance.lines')}</h2>
            <Button size="sm" variant="secondary" onClick={() => setLines((prev) => [...prev, emptyLine()])}>
              <Plus size={14} />
              {t('finance.addLine')}
            </Button>
          </div>
          {lines.map((line, idx) => (
            <div key={idx} className="grid gap-2 rounded-xl border border-[var(--premium-border)] p-3 sm:grid-cols-6">
              <div className="sm:col-span-2">
                <Input
                  label={t('finance.description')}
                  value={line.description}
                  autoComplete="off"
                  onChange={(e) => updateLine(idx, { description: e.target.value })}
                />
              </div>
              <Input
                label={t('finance.qty')}
                value={line.quantity}
                autoComplete="off"
                onChange={(e) => updateLine(idx, { quantity: e.target.value })}
              />
              <Input
                label={t('finance.unitPrice')}
                value={line.unit_price}
                autoComplete="off"
                onChange={(e) => updateLine(idx, { unit_price: e.target.value })}
              />
              <Input
                label={t('finance.taxRate')}
                value={line.tax_rate}
                autoComplete="off"
                onChange={(e) => updateLine(idx, { tax_rate: e.target.value })}
              />
              <div className="flex items-end gap-2">
                <Input
                  label={t('finance.agreedPrice')}
                  value={line.agreed_unit_price}
                  autoComplete="off"
                  onChange={(e) => updateLine(idx, { agreed_unit_price: e.target.value })}
                />
                {lines.length > 1 && (
                  <button
                    type="button"
                    className="mb-1 rounded-lg p-2 text-red-600 hover:bg-red-50"
                    onClick={() => setLines((prev) => prev.filter((_, i) => i !== idx))}
                  >
                    <Trash2 size={16} />
                  </button>
                )}
              </div>
            </div>
          ))}
        </div>

        <div className="flex justify-end gap-2">
          <Button
            onClick={() => create.mutate()}
            disabled={
              !partnerId ||
              create.isPending ||
              currency.length !== 3 ||
              lines.some((l) => !l.description)
            }
          >
            {create.isPending ? t('common.saving') : t('common.save')}
          </Button>
        </div>
      </Card>
    </div>
  )
}
