'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { createClientComponentClient } from '@supabase/auth-helpers-nextjs';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';

export default function Cadastro_fornecedor() {
  const supabase = createClientComponentClient();
  const router = useRouter();

  const [form, setForm] = useState({
    nome: '',
    cnpj_cpf: '',
    inscricao_estadual: '',
    email: '',
    telefone: '',
    observacoes: ''
  });

  const handleChange = (e: any) =>
    setForm(prev => ({ ...prev, [e.target.name]: e.target.value }));

  const handleSubmit = async (e: any) => {
    e.preventDefault();
    await supabase.from('suppliers').insert([{
      nome: form.nome,
      cnpj_cpf: form.cnpj_cpf,
      inscricao_estadual: form.inscricao_estadual,
      email: form.email,
      telefone: form.telefone,
      observacoes: form.observacoes
    }]);
    router.push('/fornecedores/Listagem_fornecedores');
  };

  return (
    <div className="p-6 max-w-2xl mx-auto">
      <Card>
        <CardHeader>
          <CardTitle>Novo Fornecedor</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <Label>Nome</Label>
              <Input name="nome" value={form.nome} onChange={handleChange} required />
            </div>
            <div>
              <Label>CNPJ/CPF</Label>
              <Input name="cnpj_cpf" value={form.cnpj_cpf} onChange={handleChange} required />
            </div>
            <div>
              <Label>Inscrição Estadual</Label>
              <Input name="inscricao_estadual" value={form.inscricao_estadual} onChange={handleChange} />
            </div>
            <div>
              <Label>Email</Label>
              <Input name="email" type="email" value={form.email} onChange={handleChange} />
            </div>
            <div>
              <Label>Telefone</Label>
              <Input name="telefone" value={form.telefone} onChange={handleChange} />
            </div>
            <div>
              <Label>Observações</Label>
              <Input name="observacoes" value={form.observacoes} onChange={handleChange} />
            </div>
            <Button type="submit" className="w-full bg-green-600 text-white">
              Salvar Fornecedor
            </Button>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}
