import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { useMutation, useQuery } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";
import { useLanguage } from "@/hooks/use-language";
import { PageLayout } from "@/components/PageLayout";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { toast } from "sonner";
import { useState } from "react";

export const Route = createFileRoute("/_authenticated/godowns/add")({
  component: AddGodownPage,
});

function AddGodownPage() {
  const { tr, lang } = useLanguage();
  const navigate = useNavigate();
  const [form, setForm] = useState({ name: "", code: "", address: "", manager_name: "", mobile: "", status: "active", branch_id: "" });

  const { data: branches = [] } = useQuery({
    queryKey: ["branches-active"],
    queryFn: async () => {
      const { data } = await supabase.from("branches").select("id, name").is("deleted_at", null).eq("status", "active").order("name");
      return data || [];
    },
  });

  const mutation = useMutation({
    mutationFn: async () => {
      const payload = { ...form, branch_id: form.branch_id || null };
      const { error } = await supabase.from("godowns").insert(payload);
      if (error) throw error;
    },
    onSuccess: () => {
      toast.success(tr("godownSaved"));
      navigate({ to: "/godowns" });
    },
    onError: (e: any) => toast.error(e.message),
  });

  return (
    <PageLayout title={tr("addGodown")}>
      <div className="max-w-xl space-y-4">
        <div>
          <Label>{tr("godownName")} *</Label>
          <Input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} required />
        </div>
        <div>
          <Label>{lang === "bn" ? "শাখা" : "Branch"}</Label>
          <Select value={form.branch_id} onValueChange={(v) => setForm({ ...form, branch_id: v })}>
            <SelectTrigger><SelectValue placeholder={lang === "bn" ? "শাখা নির্বাচন করুন" : "Select branch"} /></SelectTrigger>
            <SelectContent>
              {branches.map((b: any) => <SelectItem key={b.id} value={b.id}>{b.name}</SelectItem>)}
            </SelectContent>
          </Select>
        </div>
        <div>
          <Label>{tr("code")}</Label>
          <Input value={form.code} onChange={(e) => setForm({ ...form, code: e.target.value })} />
        </div>
        <div>
          <Label>{tr("address")}</Label>
          <Input value={form.address} onChange={(e) => setForm({ ...form, address: e.target.value })} />
        </div>
        <div>
          <Label>{tr("managerName")}</Label>
          <Input value={form.manager_name} onChange={(e) => setForm({ ...form, manager_name: e.target.value })} />
        </div>
        <div>
          <Label>{tr("mobile")}</Label>
          <Input value={form.mobile} onChange={(e) => setForm({ ...form, mobile: e.target.value })} />
        </div>
        <div>
          <Label>{tr("status")}</Label>
          <Select value={form.status} onValueChange={(v) => setForm({ ...form, status: v })}>
            <SelectTrigger><SelectValue /></SelectTrigger>
            <SelectContent>
              <SelectItem value="active">{tr("active")}</SelectItem>
              <SelectItem value="inactive">{tr("inactive")}</SelectItem>
            </SelectContent>
          </Select>
        </div>
        <Button onClick={() => mutation.mutate()} disabled={!form.name || mutation.isPending}>
          {mutation.isPending ? tr("saving") : tr("save")}
        </Button>
      </div>
    </PageLayout>
  );
}
