'use client'

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

export function AssetDetailPage() {
  const { t } = useTranslation()
  const params = useParams()
  const id = params?.id as string
  const [serviceDate, setServiceDate] = useState('')
  const [description, setDescription] = useState('')
  const [cost, setCost] = useState('')

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

  const { data: schedule } = useQuery({
    queryKey: ['asset-schedule', id],
    queryFn: () =>
      api.get<{
        data: {
          monthly_depreciation: number
          remaining_months: number
          schedule: Array<{ period_index: number; amount: number; book_value_after: number }>
        }
      }>(`/assets/${id}/depreciation-schedule`),
    enabled: Boolean(id),
    retry: false,
  })

  const addMaintenance = useMutation({
    mutationFn: () =>
      api.post(`/assets/${id}/maintenance`, {
        service_date: serviceDate,
        description,
        cost: cost === '' ? undefined : Number(cost),
      }),
    onSuccess: () => {
      toast.success(t('assets.messages.maintenanceAdded'))
      setServiceDate('')
      setDescription('')
      setCost('')
      refetch()
    },
    onError: (err: { response?: { data?: { message?: string } } }) => {
      toast.error(err?.response?.data?.message || t('common.somethingWentWrong'))
    },
  })

  const asset = data?.data?.data

  if (isLoading || !asset) {
    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 gap-3">
        <Link href="/assets">
          <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">{asset.name}</h1>
        <Badge variant="muted">{asset.asset_code}</Badge>
      </div>

      <Card elevated className="grid gap-3 sm:grid-cols-3 text-sm">
        <div>
          <div className="text-xs text-[var(--text-muted)]">{t('common.status')}</div>
          <div>{t(`assets.status.${asset.status}`, asset.status)}</div>
        </div>
        <div>
          <div className="text-xs text-[var(--text-muted)]">{t('assets.purchaseValue')}</div>
          <div>{asset.purchase_value != null ? Number(asset.purchase_value).toFixed(2) : '—'}</div>
        </div>
        <div>
          <div className="text-xs text-[var(--text-muted)]">{t('assets.bookValue')}</div>
          <div>{asset.book_value != null ? Number(asset.book_value).toFixed(2) : '—'}</div>
        </div>
      </Card>

      {schedule?.data?.data && (
        <Card elevated>
          <h2 className="mb-2 font-semibold">{t('assets.depreciationSchedule')}</h2>
          <p className="mb-3 text-sm text-[var(--text-muted)]">
            {t('assets.monthly')}: {schedule.data.data.monthly_depreciation.toFixed(2)} ·{' '}
            {t('assets.remainingMonths')}: {schedule.data.data.remaining_months}
          </p>
          <ul className="max-h-48 space-y-1 overflow-y-auto text-sm">
            {schedule.data.data.schedule.slice(0, 24).map((row) => (
              <li key={row.period_index} className="flex justify-between border-b py-1">
                <span>#{row.period_index}</span>
                <span>{row.amount.toFixed(2)}</span>
                <span>{row.book_value_after.toFixed(2)}</span>
              </li>
            ))}
          </ul>
        </Card>
      )}

      <PermissionGate permission="assets.manage">
        <Card elevated className="space-y-3">
          <h2 className="font-semibold">{t('assets.addMaintenance')}</h2>
          <div className="grid gap-3 sm:grid-cols-3">
            <Input
              label={t('assets.serviceDate')}
              type="date"
              value={serviceDate}
              onChange={(e) => setServiceDate(e.target.value)}
            />
            <Input
              label={t('finance.description')}
              value={description}
              onChange={(e) => setDescription(e.target.value)}
            />
            <Input label={t('assets.cost')} value={cost} onChange={(e) => setCost(e.target.value)} />
          </div>
          <Button
            size="sm"
            onClick={() => addMaintenance.mutate()}
            disabled={!serviceDate || !description || addMaintenance.isPending}
          >
            {t('common.save')}
          </Button>
        </Card>
      </PermissionGate>

      {(asset.maintenance ?? []).length > 0 && (
        <Card elevated>
          <h2 className="mb-3 font-semibold">{t('assets.maintenanceHistory')}</h2>
          <ul className="space-y-2 text-sm">
            {asset.maintenance!.map((m) => (
              <li key={m.id} className="flex justify-between border-b py-1">
                <span>
                  {String(m.service_date).slice(0, 10)} — {m.description}
                </span>
                <span>{m.cost != null ? Number(m.cost).toFixed(2) : '—'}</span>
              </li>
            ))}
          </ul>
        </Card>
      )}
    </div>
  )
}
