import { createFileRoute, Link } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";
import { useLanguage } from "@/hooks/use-language";
import { PageLayout } from "@/components/PageLayout";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import { Pencil, Package, Warehouse } from "lucide-react";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";

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

function GodownDetailPage() {
  const { godownId } = Route.useParams();
  const { tr } = useLanguage();

  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;
    },
  });

  const { data: stocks = [] } = useQuery({
    queryKey: ["godown-stocks", godownId],
    queryFn: async () => {
      const { data, error } = await supabase.from("godown_stocks").select("*, products:product_id(name, sku, unit)").eq("godown_id", godownId);
      if (error) throw error;
      return data;
    },
  });

  const { data: transfers = [] } = useQuery({
    queryKey: ["godown-transfers", godownId],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("stock_transfers")
        .select("*, from_godown:from_godown_id(name), to_godown:to_godown_id(name), products:product_id(name)")
        .or(`from_godown_id.eq.${godownId},to_godown_id.eq.${godownId}`)
        .order("created_at", { ascending: false })
        .limit(50);
      if (error) throw error;
      return data;
    },
  });

  if (!godown) return null;

  const totalStock = stocks.reduce((s: number, i: any) => s + Number(i.quantity), 0);

  return (
    <PageLayout title={godown.name} subtitle={tr("godownProfile")}>
      <div className="grid gap-4 md:grid-cols-4 mb-6">
        <Card><CardHeader className="pb-2"><CardTitle className="text-sm text-muted-foreground">{tr("code")}</CardTitle></CardHeader><CardContent className="text-lg font-bold">{godown.code || "—"}</CardContent></Card>
        <Card><CardHeader className="pb-2"><CardTitle className="text-sm text-muted-foreground">{tr("totalStock")}</CardTitle></CardHeader><CardContent className="text-lg font-bold">{totalStock}</CardContent></Card>
        <Card><CardHeader className="pb-2"><CardTitle className="text-sm text-muted-foreground">{tr("managerName")}</CardTitle></CardHeader><CardContent className="text-lg font-bold">{godown.manager_name || "—"}</CardContent></Card>
        <Card><CardHeader className="pb-2"><CardTitle className="text-sm text-muted-foreground">{tr("status")}</CardTitle></CardHeader><CardContent><Badge variant={godown.status === "active" ? "default" : "secondary"}>{godown.status === "active" ? tr("active") : tr("inactive")}</Badge></CardContent></Card>
      </div>

      <div className="flex gap-2 mb-4">
        <Link to="/godowns/$godownId/edit" params={{ godownId }}>
          <Button variant="outline" size="sm"><Pencil className="mr-2 h-4 w-4" />{tr("edit")}</Button>
        </Link>
      </div>

      <Tabs defaultValue="stocks">
        <TabsList>
          <TabsTrigger value="stocks"><Package className="mr-1 h-4 w-4" />{tr("stockList")}</TabsTrigger>
          <TabsTrigger value="transfers"><Warehouse className="mr-1 h-4 w-4" />{tr("transferHistory")}</TabsTrigger>
        </TabsList>

        <TabsContent value="stocks">
          <div className="rounded-lg border bg-card">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>{tr("productName")}</TableHead>
                  <TableHead>{tr("sku")}</TableHead>
                  <TableHead>{tr("unit")}</TableHead>
                  <TableHead>{tr("quantity")}</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {stocks.length === 0 ? (
                  <TableRow><TableCell colSpan={4} className="text-center py-6 text-muted-foreground">{tr("noData")}</TableCell></TableRow>
                ) : stocks.map((s: any) => (
                  <TableRow key={s.id}>
                    <TableCell>{(s.products as any)?.name || "—"}</TableCell>
                    <TableCell>{(s.products as any)?.sku || "—"}</TableCell>
                    <TableCell>{(s.products as any)?.unit || "—"}</TableCell>
                    <TableCell>{s.quantity}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
        </TabsContent>

        <TabsContent value="transfers">
          <div className="rounded-lg border bg-card">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>{tr("date")}</TableHead>
                  <TableHead>{tr("productName")}</TableHead>
                  <TableHead>{tr("fromGodown")}</TableHead>
                  <TableHead>{tr("toGodown")}</TableHead>
                  <TableHead>{tr("quantity")}</TableHead>
                  <TableHead>{tr("note")}</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {transfers.length === 0 ? (
                  <TableRow><TableCell colSpan={6} className="text-center py-6 text-muted-foreground">{tr("noData")}</TableCell></TableRow>
                ) : transfers.map((t: any) => (
                  <TableRow key={t.id}>
                    <TableCell>{new Date(t.transfer_date).toLocaleDateString()}</TableCell>
                    <TableCell>{(t.products as any)?.name || "—"}</TableCell>
                    <TableCell>{(t.from_godown as any)?.name || "—"}</TableCell>
                    <TableCell>{(t.to_godown as any)?.name || "—"}</TableCell>
                    <TableCell>{t.quantity}</TableCell>
                    <TableCell>{t.note || "—"}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
        </TabsContent>
      </Tabs>
    </PageLayout>
  );
}
