import { createFileRoute, Link } 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 { usePermissions } from "@/hooks/use-permissions";
import { PageLayout } from "@/components/PageLayout";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Plus, Search, Pencil, Trash2, Warehouse } from "lucide-react";
import { toast } from "sonner";
import { useState } from "react";

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

function GodownListPage() {
  const { tr } = useLanguage();
  const { isAdmin } = usePermissions();
  const queryClient = useQueryClient();
  const [search, setSearch] = useState("");

  const { data: godowns = [], isLoading } = useQuery({
    queryKey: ["godowns"],
    queryFn: async () => {
      const { data, error } = await supabase.from("godowns").select("*").order("created_at", { ascending: false });
      if (error) throw error;
      return data;
    },
  });

  const { data: stockSummary = [] } = useQuery({
    queryKey: ["godown-stock-summary"],
    queryFn: async () => {
      const { data, error } = await supabase.from("godown_stocks").select("godown_id, quantity");
      if (error) throw error;
      const map: Record<string, number> = {};
      data.forEach((s: any) => {
        map[s.godown_id] = (map[s.godown_id] || 0) + Number(s.quantity);
      });
      return map;
    },
  });

  const deleteMutation = useMutation({
    mutationFn: async (id: string) => {
      const { error } = await supabase.from("godowns").delete().eq("id", id);
      if (error) throw error;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["godowns"] });
      toast.success(tr("godownDeleted"));
    },
  });

  const filtered = godowns.filter((g: any) =>
    g.name.toLowerCase().includes(search.toLowerCase()) ||
    (g.code || "").toLowerCase().includes(search.toLowerCase())
  );

  return (
    <PageLayout title={tr("godownList")} subtitle={tr("godownSubtitle")}>
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div className="relative max-w-sm">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input placeholder={tr("search")} value={search} onChange={(e) => setSearch(e.target.value)} className="pl-9" />
        </div>
        <Link to="/godowns/add">
          <Button><Plus className="mr-2 h-4 w-4" />{tr("addGodown")}</Button>
        </Link>
      </div>

      <div className="mt-4 rounded-lg border bg-card">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>{tr("name")}</TableHead>
              <TableHead>{tr("code")}</TableHead>
              <TableHead>{tr("address")}</TableHead>
              <TableHead>{tr("managerName")}</TableHead>
              <TableHead>{tr("totalStock")}</TableHead>
              <TableHead>{tr("status")}</TableHead>
              <TableHead className="text-right">{tr("action")}</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {isLoading ? (
              <TableRow><TableCell colSpan={7} className="text-center py-8 text-muted-foreground">{tr("loading")}</TableCell></TableRow>
            ) : filtered.length === 0 ? (
              <TableRow><TableCell colSpan={7} className="text-center py-8 text-muted-foreground">{tr("noData")}</TableCell></TableRow>
            ) : (
              filtered.map((g: any) => (
                <TableRow key={g.id}>
                  <TableCell className="font-medium">
                    <Link to="/godowns/$godownId" params={{ godownId: g.id }} className="text-primary hover:underline flex items-center gap-2">
                      <Warehouse className="h-4 w-4" />{g.name}
                    </Link>
                  </TableCell>
                  <TableCell>{g.code || "—"}</TableCell>
                  <TableCell>{g.address || "—"}</TableCell>
                  <TableCell>{g.manager_name || "—"}</TableCell>
                  <TableCell>{(stockSummary as any)[g.id] || 0}</TableCell>
                  <TableCell>
                    <Badge variant={g.status === "active" ? "default" : "secondary"}>
                      {g.status === "active" ? tr("active") : tr("inactive")}
                    </Badge>
                  </TableCell>
                  <TableCell className="text-right space-x-1">
                    <Link to="/godowns/$godownId/edit" params={{ godownId: g.id }}>
                      <Button variant="ghost" size="icon"><Pencil className="h-4 w-4" /></Button>
                    </Link>
                    {isAdmin && (
                      <Button variant="ghost" size="icon" onClick={() => deleteMutation.mutate(g.id)}>
                        <Trash2 className="h-4 w-4 text-destructive" />
                      </Button>
                    )}
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>
    </PageLayout>
  );
}
