"use client";

import { useEffect, useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useTranslations, useLocale } from "next-intl";
import { apiGet, apiPost } from "@/lib/api/client";
import { useAuthStore } from "@/lib/stores/auth.store";
import { useBranchStore } from "@/lib/stores/branch.store";
import { formatCurrency, formatNumber } from "@/lib/format";
import { PageHeader } from "@/components/layout/page-header";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { LabeledField } from "@/components/ui/labeled-field";
import { notify } from "@/lib/notify";

type ShiftDto = {
  id: string;
  branchId: string;
  openingCash: number;
  closingCash?: number | null;
  expectedCash: number;
  discrepancy?: number | null;
  status: string;
  openedAt: string;
  closedAt?: string | null;
};

export function ShiftsScreen() {
  const t = useTranslations("shifts");
  const tCommon = useTranslations("common");
  const locale = useLocale();
  const numberLocale = locale === "en" ? "en-US" : "fa-IR";
  const cafeId = useAuthStore((s) => s.user?.cafeId);
  const branchId = useBranchStore((s) => s.branchId);
  const setBranchId = useBranchStore((s) => s.setBranchId);
  const qc = useQueryClient();
  const [openCash, setOpenCash] = useState("0");
  const [closeCash, setCloseCash] = useState("");
  const [showClose, setShowClose] = useState(false);

  const { data: branches = [] } = useQuery({
    queryKey: ["branches", cafeId],
    queryFn: () => apiGet<{ id: string; name: string }[]>(`/api/cafes/${cafeId}/branches`),
    enabled: !!cafeId,
  });

  useEffect(() => {
    if (!branchId && branches.length > 0) setBranchId(branches[0]!.id);
  }, [branchId, branches, setBranchId]);

  const { data: current, isLoading } = useQuery({
    queryKey: ["shift-current", cafeId, branchId],
    queryFn: async () => {
      try {
        return await apiGet<ShiftDto>(
          `/api/cafes/${cafeId}/branches/${branchId}/shifts/current`
        );
      } catch {
        return null;
      }
    },
    enabled: !!cafeId && !!branchId,
    retry: false,
  });

  const openShift = useMutation({
    mutationFn: () =>
      apiPost<ShiftDto>(`/api/cafes/${cafeId}/branches/${branchId}/shifts/open`, {
        openingCash: Number(openCash) || 0,
      }),
    onSuccess: () => {
      void qc.invalidateQueries({ queryKey: ["shift-current", cafeId, branchId] });
      notify.success(t("opened"));
    },
  });

  const closeShift = useMutation({
    mutationFn: () =>
      apiPost<ShiftDto>(`/api/cafes/${cafeId}/branches/${branchId}/shifts/${current!.id}/close`, {
        closingCash: Number(closeCash) || 0,
      }),
    onSuccess: () => {
      setShowClose(false);
      setCloseCash("");
      void qc.invalidateQueries({ queryKey: ["shift-current", cafeId, branchId] });
      notify.success(t("closed"));
    },
  });

  if (!cafeId) return null;

  return (
    <div className="space-y-6">
      <PageHeader title={t("title")} subtitle={t("subtitle")} />

      {branches.length > 1 ? (
        <LabeledField label={t("branch")}>
          <select
            className="flex h-10 max-w-xs rounded-md border border-input bg-background px-3 text-sm"
            value={branchId ?? ""}
            onChange={(e) => setBranchId(e.target.value || null)}
          >
            {branches.map((b) => (
              <option key={b.id} value={b.id}>
                {b.name}
              </option>
            ))}
          </select>
        </LabeledField>
      ) : null}

      {isLoading ? (
        <p className="text-sm text-muted-foreground">{tCommon("loading")}</p>
      ) : current?.status === "Open" ? (
        <Card className="rounded-xl border border-[#0F6E56]/30">
          <CardHeader>
            <CardTitle className="text-base text-[#0F6E56]">{t("shiftOpen")}</CardTitle>
          </CardHeader>
          <CardContent className="space-y-3 text-sm">
            <p>
              {t("openingCash")}: {formatCurrency(current.openingCash, numberLocale)}
            </p>
            <p>
              {t("expectedCash")}: {formatCurrency(current.expectedCash, numberLocale)}
            </p>
            {!showClose ? (
              <Button
                className="bg-[#0F6E56] hover:bg-[#0c5a46]"
                onClick={() => {
                  setCloseCash(String(Math.round(current.expectedCash)));
                  setShowClose(true);
                }}
              >
                {t("closeShift")}
              </Button>
            ) : (
              <div className="space-y-2 rounded-lg border border-border p-3">
                <LabeledField label={t("countedCash")}>
                  <Input
                    value={closeCash}
                    onChange={(e) => setCloseCash(e.target.value)}
                    dir="ltr"
                    className="text-end"
                  />
                </LabeledField>
                <div className="flex gap-2">
                  <Button
                    className="bg-[#0F6E56]"
                    disabled={closeShift.isPending}
                    onClick={() => closeShift.mutate()}
                  >
                    {t("confirmClose")}
                  </Button>
                  <Button variant="outline" onClick={() => setShowClose(false)}>
                    {tCommon("cancel")}
                  </Button>
                </div>
              </div>
            )}
          </CardContent>
        </Card>
      ) : (
        <Card className="rounded-xl border border-border/80">
          <CardHeader>
            <CardTitle className="text-base">{t("openShift")}</CardTitle>
          </CardHeader>
          <CardContent className="flex flex-wrap items-end gap-3">
            <LabeledField label={t("openingCash")}>
              <Input
                value={openCash}
                onChange={(e) => setOpenCash(e.target.value)}
                dir="ltr"
                className="w-40 text-end"
              />
            </LabeledField>
            <Button
              className="bg-[#0F6E56] hover:bg-[#0c5a46]"
              disabled={!branchId || openShift.isPending}
              onClick={() => openShift.mutate()}
            >
              {t("startShift")}
            </Button>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
