'use client';
import { useState } from 'react';
import { ArrowDownCircle, ArrowUpCircle, SlidersHorizontal, AlertTriangle } from 'lucide-react';
import { useAuth } from '@/hooks/useAuth';
import { useApi } from '@/hooks/useApi';
import { productsService } from '@/services/products.service';
import { inventoryService } from '@/services/inventory.service';
import { Card, CardHeader, CardBody } from '@/components/ui/Card';
import { Select } from '@/components/ui/Select';
import { Input } from '@/components/ui/Input';
import { Button } from '@/components/ui/Button';
import { Badge } from '@/components/ui/Badge';
import { PageHeader } from '@/components/layout/PageHeader';
import { LoadingState } from '@/components/ui/States';
import { formatDateTime } from '@/utils/formatDate';
import type { MovementType } from '@/types';

export default function EstoquePage() {
  const { storeId } = useAuth();
  const [productId, setProductId] = useState('');
  const [type, setType] = useState<MovementType>('entrada');
  const [qty, setQty] = useState(1);
  const [reason, setReason] = useState('');

  const { data: products, loading: lp, refetch: rp } = useApi(
    () => (storeId ? productsService.list(storeId) : Promise.resolve([])),
    [storeId],
  );
  const { data: movements, refetch: rm } = useApi(
    () => (storeId ? inventoryService.movements(storeId) : Promise.resolve([])),
    [storeId],
  );

  async function registerMovement() {
    if (!productId || !storeId || qty <= 0) return;
    const product = (products ?? []).find((p) => p.id === productId);
    if (!product) return;
    const signed = type === 'saida' ? -Math.abs(qty) : type === 'ajuste' ? qty - product.stock : Math.abs(qty);
    const resultingStock = Math.max(0, product.stock + signed);
    await productsService.update(productId, { stock: resultingStock });
    await inventoryService.registerMovement({
      id: `mov_${Date.now()}`, storeId, productId, productName: product.name,
      type, quantity: signed, reason: reason || 'Movimentação manual', resultingStock,
      createdAt: new Date().toISOString(),
    });
    setQty(1); setReason('');
    rp(); rm();
  }

  if (lp) return <LoadingState />;
  const list = products ?? [];
  const low = list.filter((p) => p.trackStock && p.stock <= p.minStock);

  return (
    <>
      <PageHeader title="Estoque" subtitle="Controle de entradas, saídas e ajustes" />

      {low.length > 0 && (
        <div className="mb-4 flex items-start gap-3 rounded-xl border border-amber-200 bg-amber-50 p-4">
          <AlertTriangle className="mt-0.5 h-5 w-5 text-amber-600" />
          <div>
            <p className="font-medium text-amber-800">{low.length} produto(s) com estoque baixo</p>
            <p className="text-sm text-amber-700">{low.map((p) => p.name).join(', ')}</p>
          </div>
        </div>
      )}

      <div className="grid gap-4 lg:grid-cols-3">
        <Card>
          <CardHeader title="Registrar movimentação" />
          <CardBody className="space-y-3">
            <Select label="Produto" value={productId} onChange={(e) => setProductId(e.target.value)}>
              <option value="">Selecione</option>
              {list.map((p) => <option key={p.id} value={p.id}>{p.name} (estoque: {p.stock})</option>)}
            </Select>
            <Select label="Tipo" value={type} onChange={(e) => setType(e.target.value as MovementType)}>
              <option value="entrada">Entrada</option>
              <option value="saida">Saída</option>
              <option value="ajuste">Ajuste (definir total)</option>
            </Select>
            <Input label={type === 'ajuste' ? 'Novo total' : 'Quantidade'} type="number" value={qty} onChange={(e) => setQty(Number(e.target.value))} />
            <Input label="Motivo" value={reason} onChange={(e) => setReason(e.target.value)} placeholder="Ex: compra, venda, perda" />
            <Button className="w-full" onClick={registerMovement} disabled={!productId}>Registrar</Button>
          </CardBody>
        </Card>

        <div className="space-y-4 lg:col-span-2">
          <Card>
            <CardHeader title="Estoque atual" />
            <CardBody className="space-y-2">
              {list.map((p) => (
                <div key={p.id} className="flex items-center justify-between rounded-lg border border-ink-100 px-4 py-2.5">
                  <span className="text-sm text-ink-700">{p.name}</span>
                  {p.stock === 0 ? <Badge tone="red">Esgotado</Badge>
                    : p.stock <= p.minStock ? <Badge tone="amber">{p.stock} / mín {p.minStock}</Badge>
                    : <span className="text-sm font-medium text-ink-900">{p.stock} un.</span>}
                </div>
              ))}
            </CardBody>
          </Card>

          <Card>
            <CardHeader title="Histórico de movimentações" />
            <CardBody className="space-y-2">
              {(movements ?? []).length === 0 && <p className="text-sm text-ink-400">Sem movimentações ainda.</p>}
              {(movements ?? []).map((m) => (
                <div key={m.id} className="flex items-center justify-between border-b border-ink-50 py-2 last:border-0">
                  <div className="flex items-center gap-2">
                    {m.type === 'entrada' ? <ArrowUpCircle className="h-4 w-4 text-emerald-500" />
                      : m.type === 'saida' ? <ArrowDownCircle className="h-4 w-4 text-red-500" />
                      : <SlidersHorizontal className="h-4 w-4 text-violet-500" />}
                    <div>
                      <p className="text-sm text-ink-800">{m.productName}</p>
                      <p className="text-xs text-ink-400">{m.reason} · {formatDateTime(m.createdAt)}</p>
                    </div>
                  </div>
                  <div className="text-right">
                    <p className={`text-sm font-medium ${m.quantity >= 0 ? 'text-emerald-600' : 'text-red-600'}`}>
                      {m.quantity >= 0 ? '+' : ''}{m.quantity}
                    </p>
                    <p className="text-xs text-ink-400">→ {m.resultingStock}</p>
                  </div>
                </div>
              ))}
            </CardBody>
          </Card>
        </div>
      </div>
    </>
  );
}
