import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { PageLayout } from "@/components/PageLayout";
import { useLanguage } from "@/hooks/use-language";
import { supabase } from "@/integrations/supabase/client";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { toast } from "sonner";
import { Loader2 } from "lucide-react";

export const Route = createFileRoute("/_authenticated/suppliers/add")({
  head: () => ({
    meta: [{ title: "Add Supplier — Niyamah ERP" }],
  }),
  component: AddSupplierPage,
});

function AddSupplierPage() {
  const { tr } = useLanguage();
  const navigate = useNavigate();
  const queryClient = useQueryClient();

  const [form, setForm] = useState({
    name: "",
    mobile: "",
    email: "",
    address: "",
    company_name: "",
    opening_balance: 0,
    status: "active",
  });

  const set = (key: string, value: any) => setForm((p) => ({ ...p, [key]: value }));

  const saveMutation = useMutation({
    mutationFn: async () => {
      if (!form.name.trim()) throw new Error("Name required");
      if (!form.mobile.trim()) throw new Error("Mobile required");

      const { error } = await supabase.from("suppliers").insert({
        name: form.name.trim(),
        mobile: form.mobile.trim(),
        email: form.email.trim(),
        address: form.address.trim(),
        company_name: form.company_name.trim(),
        opening_balance: form.opening_balance,
        current_due: form.opening_balance,
        status: form.status,
      });
      if (error) throw error;
    },
    onSuccess: () => {
      toast.success(tr("supplierSaved"));
      queryClient.invalidateQueries({ queryKey: ["suppliers"] });
      navigate({ to: "/suppliers" });
    },
    onError: (err: any) => toast.error(err.message),
  });

  const inputCls = "w-full rounded-lg border border-border bg-card px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/40";

  return (
    <PageLayout>
      <div className="mb-6">
        <h1 className="text-xl font-bold text-foreground">{tr("addSupplier")}</h1>
      </div>

      <div className="max-w-2xl rounded-xl border border-border bg-card p-6 space-y-4">
        <div className="grid gap-4 sm:grid-cols-2">
          <div>
            <label className="text-xs font-medium text-muted-foreground">{tr("supplierName")} *</label>
            <input className={inputCls} value={form.name} onChange={(e) => set("name", e.target.value)} />
          </div>
          <div>
            <label className="text-xs font-medium text-muted-foreground">{tr("mobile")} *</label>
            <input className={inputCls} value={form.mobile} onChange={(e) => set("mobile", e.target.value)} />
          </div>
          <div>
            <label className="text-xs font-medium text-muted-foreground">{tr("email")}</label>
            <input className={inputCls} value={form.email} onChange={(e) => set("email", e.target.value)} />
          </div>
          <div>
            <label className="text-xs font-medium text-muted-foreground">{tr("companyName")}</label>
            <input className={inputCls} value={form.company_name} onChange={(e) => set("company_name", e.target.value)} />
          </div>
          <div className="sm:col-span-2">
            <label className="text-xs font-medium text-muted-foreground">{tr("address")}</label>
            <input className={inputCls} value={form.address} onChange={(e) => set("address", e.target.value)} />
          </div>
          <div>
            <label className="text-xs font-medium text-muted-foreground">{tr("openingBalance")}</label>
            <input type="number" className={inputCls} value={form.opening_balance} onChange={(e) => set("opening_balance", Number(e.target.value) || 0)} />
          </div>
          <div>
            <label className="text-xs font-medium text-muted-foreground">{tr("status")}</label>
            <select className={inputCls} value={form.status} onChange={(e) => set("status", e.target.value)}>
              <option value="active">{tr("active")}</option>
              <option value="inactive">{tr("inactive")}</option>
            </select>
          </div>
        </div>

        <button
          onClick={() => saveMutation.mutate()}
          disabled={saveMutation.isPending}
          className="mt-4 rounded-lg bg-primary px-6 py-2.5 text-sm font-semibold text-primary-foreground hover:bg-primary/90 disabled:opacity-50 flex items-center gap-2"
        >
          {saveMutation.isPending && <Loader2 className="h-4 w-4 animate-spin" />}
          {tr("save")}
        </button>
      </div>
    </PageLayout>
  );
}
