import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { useQuery, useMutation, useQueryClient } 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, useEffect } from "react";

export const Route = createFileRoute("/_authenticated/godowns/$godownId/edit")({
  component: EditGodownPage,
});

function EditGodownPage() {
  const { godownId } = Route.useParams();
  const { tr } = useLanguage();
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const [form, setForm] = useState({ name: "", code: "", address: "", manager_name: "", mobile: "", status: "active" });

  const { data: godown } = useQuery({
    queryKey: ["godown", godownId],
    queryFn: async () => {
      const { data, error } = await supabase.from("godowns").select("*").eq("id", godownId).single();
      if (error) throw error;
      return data;
    },
  });

  useEffect(() => {
    if (godown) {
      setForm({ name: godown.name, code: godown.code || "", address: godown.address || "", manager_name: godown.manager_name || "", mobile: godown.mobile || "", status: godown.status });
    }
  }, [godown]);

  const mutation = useMutation({
    mutationFn: async () => {
      const { error } = await supabase.from("godowns").update(form).eq("id", godownId);
      if (error) throw error;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["godowns"] });
      queryClient.invalidateQueries({ queryKey: ["godown", godownId] });
      toast.success(tr("godownUpdated"));
      navigate({ to: "/godowns/$godownId", params: { godownId } });
    },
    onError: (e: any) => toast.error(e.message),
  });

  return (
    <PageLayout title={tr("editGodown")}>
      <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 })} /></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("update")}
        </Button>
      </div>
    </PageLayout>
  );
}
