'use client'

import { useEffect, useState } from 'react'
import Link from 'next/link'
import { useRouter, useParams } from 'next/navigation'
import { useForm } from 'react-hook-form'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { ArrowLeft, Save, Plus, Trash2 } from 'lucide-react'
import { toast } from 'sonner'
import {
  api,
  type Offer,
  type PaginatedResponse,
  type Project,
  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 LineDraft = { description: string; quantity: string; unit_price: string }

type FormValues = {
  title: string
  partner_id: string
  project_id: string
  valid_until: string
  currency: string
  tax_amount: string
  notes: string
}

export function OfferFormPage() {
  const { t } = useTranslation()
  const params = useParams()
  const id = params?.id as string | undefined
  const isEdit = Boolean(id)
  const router = useRouter()
  const queryClient = useQueryClient()
  const [lines, setLines] = useState<LineDraft[]>([
    { description: '', quantity: '1', unit_price: '0' },
  ])

  const { register, handleSubmit, reset } = useForm<FormValues>({
    defaultValues: {
      title: '',
      partner_id: '',
      project_id: '',
      valid_until: '',
      currency: 'EUR',
      tax_amount: '0',
      notes: '',
    },
  })

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

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

  const { data: projectsData } = useQuery({
    queryKey: ['projects-options'],
    queryFn: () => api.get<PaginatedResponse<Project>>('/projects', { params: { per_page: 200 } }),
  })

  useEffect(() => {
    const o = offerData?.data?.data
    if (!o) return
    reset({
      title: o.title,
      partner_id: String(o.partner_id ?? ''),
      project_id: o.project_id ? String(o.project_id) : '',
      valid_until: o.valid_until?.slice(0, 10) ?? '',
      currency: o.currency || 'EUR',
      tax_amount: String(o.tax_amount ?? 0),
      notes: o.notes ?? '',
    })
    if (o.lines?.length) {
      setLines(
        o.lines.map((l) => ({
          description: l.description,
          quantity: String(l.quantity),
          unit_price: String(l.unit_price),
        })),
      )
    }
  }, [offerData, reset])

  const save = useMutation({
    mutationFn: (payload: Record<string, unknown>) =>
      isEdit ? api.put(`/offers/${id}`, payload) : api.post('/offers', payload),
    onSuccess: (res) => {
      toast.success(isEdit ? t('offers.messages.updated') : t('offers.messages.created'))
      queryClient.invalidateQueries({ queryKey: ['offers'] })
      const newId = (res.data as { data: Offer }).data?.id
      router.push(newId ? `/offers/${newId}` : '/offers')
    },
    onError: (err: { response?: { data?: { message?: string } } }) => {
      toast.error(err?.response?.data?.message || t('common.somethingWentWrong'))
    },
  })

  const onSubmit = (values: FormValues) => {
    save.mutate({
      ...values,
      partner_id: Number(values.partner_id),
      project_id: values.project_id ? Number(values.project_id) : null,
      tax_amount: Number(values.tax_amount || 0),
      lines: lines
        .filter((l) => l.description.trim())
        .map((l, i) => ({
          description: l.description,
          quantity: Number(l.quantity || 0),
          unit_price: Number(l.unit_price || 0),
          sort_order: i,
        })),
    })
  }

  const partners = partnersData?.data.data ?? []
  const projects = projectsData?.data.data ?? []

  return (
    <div className="space-y-5">
      <div className="animate-fade-in-up flex 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">
          {isEdit ? t('offers.edit') : t('offers.create')}
        </h1>
      </div>

      <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
        <Card elevated>
          <div className="grid gap-4 sm:grid-cols-2">
            <Input label={t('offers.titleField')} {...register('title', { required: true })} />
            <Select
              label={t('offers.partner')}
              {...register('partner_id', { required: true })}
              options={[
                { value: '', label: t('offers.selectPartner') },
                ...partners.map((p) => ({ value: String(p.id), label: p.name })),
              ]}
            />
            <Select
              label={t('offers.project')}
              {...register('project_id')}
              options={[
                { value: '', label: t('offers.selectProject') },
                ...projects.map((p) => ({ value: String(p.id), label: p.name })),
              ]}
            />
            <Input type="date" label={t('offers.validUntil')} {...register('valid_until')} />
            <Input label={t('offers.currency')} {...register('currency')} />
            <Input type="number" step="0.01" label={t('offers.tax')} {...register('tax_amount')} />
            <div className="sm:col-span-2">
              <Input label={t('offers.notes')} {...register('notes')} />
            </div>
          </div>
        </Card>

        <Card elevated>
          <div className="mb-3 flex items-center justify-between">
            <h3 className="text-sm font-semibold">{t('offers.lines')}</h3>
            <Button
              type="button"
              size="sm"
              variant="secondary"
              onClick={() =>
                setLines((prev) => [...prev, { description: '', quantity: '1', unit_price: '0' }])
              }
            >
              <Plus size={14} />
              {t('offers.addLine')}
            </Button>
          </div>
          <div className="space-y-2">
            {lines.map((line, idx) => (
              <div key={idx} className="grid gap-2 sm:grid-cols-12">
                <div className="sm:col-span-6">
                  <Input
                    placeholder={t('offers.lineDescription')}
                    value={line.description}
                    onChange={(e) =>
                      setLines((prev) =>
                        prev.map((l, i) => (i === idx ? { ...l, description: e.target.value } : l)),
                      )
                    }
                  />
                </div>
                <div className="sm:col-span-2">
                  <Input
                    type="number"
                    value={line.quantity}
                    onChange={(e) =>
                      setLines((prev) =>
                        prev.map((l, i) => (i === idx ? { ...l, quantity: e.target.value } : l)),
                      )
                    }
                  />
                </div>
                <div className="sm:col-span-3">
                  <Input
                    type="number"
                    step="0.01"
                    value={line.unit_price}
                    onChange={(e) =>
                      setLines((prev) =>
                        prev.map((l, i) => (i === idx ? { ...l, unit_price: e.target.value } : l)),
                      )
                    }
                  />
                </div>
                <div className="sm:col-span-1 flex items-center">
                  <button
                    type="button"
                    className="text-red-600"
                    onClick={() => setLines((prev) => prev.filter((_, i) => i !== idx))}
                  >
                    <Trash2 size={16} />
                  </button>
                </div>
              </div>
            ))}
          </div>
        </Card>

        <Button type="submit" disabled={save.isPending}>
          <Save size={14} />
          {t('common.save')}
        </Button>
      </form>
    </div>
  )
}
