"use client";

import { useMemo, useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { Building2, RotateCcw, Trash2, Eye } from "lucide-react";
import { apiDelete, apiGet, apiPost } from "@/lib/api/client";
import { isCafeOwner } from "@/lib/auth-permissions";
import { useAuthStore } from "@/lib/stores/auth.store";
import { useBranchStore } from "@/lib/stores/branch.store";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { LabeledField } from "@/components/ui/labeled-field";
import { PageHeader } from "@/components/layout/page-header";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { cn } from "@/lib/utils";

type Branch = {
  id: string;
  name: string;
  address?: string;
  city?: string;
  phone?: string;
  loginPhone?: string;
  managerName?: string;
  isPendingDeletion?: boolean;
  deletedAt?: string | null;
  scheduledPermanentDeleteAt?: string | null;
  daysUntilPermanentDelete?: number | null;
};

function purgeCountdownLabel(
  branch: Branch,
  t: (key: string, values?: Record<string, number | string>) => string
): string {
  const days = branch.daysUntilPermanentDelete ?? 0;
  if (days <= 0) return t("purgeToday");
  if (days === 1) return t("purgeInOneDay");
  return t("purgeInDays", { days });
}

export function BranchesScreen() {
  const t = useTranslations("branchesPage");
  const tCommon = useTranslations("common");
  const cafeId = useAuthStore((s) => s.user?.cafeId);
  const role = useAuthStore((s) => s.user?.role);
  const setBranchId = useBranchStore((s) => s.setBranchId);
  const queryClient = useQueryClient();

  const [newBranchName, setNewBranchName] = useState("");
  const [loginPhone, setLoginPhone] = useState("");
  const [managerName, setManagerName] = useState("");
  const [message, setMessage] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [deleteTarget, setDeleteTarget] = useState<Branch | null>(null);
  const [reviewBranch, setReviewBranch] = useState<Branch | null>(null);

  const { data: branches = [], isLoading } = useQuery({
    queryKey: ["branches", cafeId, "manage"],
    queryFn: () =>
      apiGet<Branch[]>(
        `/api/cafes/${cafeId}/branches?includePendingDeletion=true`
      ),
    enabled: !!cafeId && isCafeOwner(role),
  });

  const activeBranches = useMemo(
    () => branches.filter((b) => !b.isPendingDeletion),
    [branches]
  );
  const pendingBranches = useMemo(
    () => branches.filter((b) => b.isPendingDeletion),
    [branches]
  );

  const invalidate = () => {
    void queryClient.invalidateQueries({ queryKey: ["branches", cafeId] });
  };

  const createBranch = useMutation({
    mutationFn: () =>
      apiPost(`/api/cafes/${cafeId}/branches`, {
        name: newBranchName.trim(),
        loginPhone: loginPhone.trim(),
        managerName: managerName.trim() || undefined,
      }),
    onSuccess: () => {
      setNewBranchName("");
      setLoginPhone("");
      setManagerName("");
      setError(null);
      setMessage(t("created"));
      invalidate();
    },
    onError: () => setError(t("createError")),
  });

  const deleteBranch = useMutation({
    mutationFn: (id: string) =>
      apiDelete(`/api/cafes/${cafeId}/branches/${id}`),
    onSuccess: (_, id) => {
      setDeleteTarget(null);
      setMessage(t("deleteScheduled"));
      setError(null);
      const current = useBranchStore.getState().branchId;
      if (current === id) setBranchId(null);
      invalidate();
    },
    onError: () => {
      setDeleteTarget(null);
      setError(t("deleteError"));
    },
  });

  const restoreBranch = useMutation({
    mutationFn: (id: string) =>
      apiPost<Branch>(`/api/cafes/${cafeId}/branches/${id}/restore`, {}),
    onSuccess: () => {
      setMessage(t("restored"));
      setError(null);
      invalidate();
    },
    onError: () => setError(t("restoreError")),
  });

  if (!cafeId) return null;

  if (!isCafeOwner(role)) {
    return (
      <div className="space-y-6">
        <PageHeader title={t("title")} subtitle={t("subtitle")} />
        <p className="text-sm text-muted-foreground">{t("ownerOnly")}</p>
      </div>
    );
  }

  const canSubmit =
    newBranchName.trim().length > 0 &&
    loginPhone.trim().length >= 10 &&
    !createBranch.isPending;

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

      {message ? (
        <p className="rounded-xl border border-[#0F6E56]/30 bg-[#E1F5EE] px-4 py-3 text-sm text-[#0F6E56]">
          {message}
        </p>
      ) : null}
      {error ? (
        <p className="rounded-xl border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive">
          {error}
        </p>
      ) : null}

      {pendingBranches.length > 0 ? (
        <Card className="rounded-xl border border-border/60 bg-muted/30">
          <CardHeader>
            <CardTitle className="text-base text-muted-foreground">
              {t("pendingTitle")}
            </CardTitle>
            <p className="text-xs text-muted-foreground">{t("pendingHint")}</p>
          </CardHeader>
          <CardContent>
            <ul className="divide-y divide-border rounded-lg border border-dashed border-border">
              {pendingBranches.map((b) => (
                <li
                  key={b.id}
                  className="flex flex-col gap-3 px-4 py-3 sm:flex-row sm:items-center sm:justify-between"
                >
                  <div className="flex items-start gap-3">
                    <Building2
                      className="mt-0.5 h-8 w-8 shrink-0 text-muted-foreground/50"
                      aria-hidden
                    />
                    <div>
                      <p className="font-medium text-muted-foreground">{b.name}</p>
                      <p className="mt-1 text-xs font-medium text-amber-800">
                        {purgeCountdownLabel(b, t)}
                      </p>
                      {b.scheduledPermanentDeleteAt ? (
                        <p className="text-[10px] text-muted-foreground" dir="ltr">
                          {new Date(b.scheduledPermanentDeleteAt).toLocaleString()}
                        </p>
                      ) : null}
                    </div>
                  </div>
                  <div className="flex flex-wrap gap-2">
                    <Button
                      type="button"
                      size="sm"
                      variant="outline"
                      onClick={() => setReviewBranch(b)}
                    >
                      <Eye className="h-3.5 w-3.5 me-1.5" />
                      {t("review")}
                    </Button>
                    <Button
                      type="button"
                      size="sm"
                      className="bg-[#0F6E56] hover:bg-[#0c5a46]"
                      disabled={restoreBranch.isPending}
                      onClick={() => restoreBranch.mutate(b.id)}
                    >
                      <RotateCcw className="h-3.5 w-3.5 me-1.5" />
                      {t("restore")}
                    </Button>
                  </div>
                </li>
              ))}
            </ul>
          </CardContent>
        </Card>
      ) : null}

      <Card className="rounded-xl border border-border/80 shadow-sm">
        <CardHeader>
          <CardTitle className="text-base">{t("listTitle")}</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          {isLoading ? (
            <p className="text-sm text-muted-foreground">{tCommon("loading")}</p>
          ) : activeBranches.length === 0 ? (
            <p className="text-sm text-muted-foreground">{t("empty")}</p>
          ) : (
            <ul className="divide-y divide-border rounded-lg border border-border">
              {activeBranches.map((b) => (
                <li
                  key={b.id}
                  className="flex flex-col gap-2 px-4 py-3 text-start sm:flex-row sm:items-center sm:justify-between"
                >
                  <div>
                    <span className="font-medium">{b.name}</span>
                    {b.managerName ? (
                      <p className="text-xs text-muted-foreground">{b.managerName}</p>
                    ) : null}
                  </div>
                  <div className="flex flex-wrap items-center gap-2">
                    <div className="text-xs text-muted-foreground">
                      {b.loginPhone ? (
                        <span dir="ltr" className="font-medium text-foreground">
                          {t("loginPhone")}: {b.loginPhone}
                        </span>
                      ) : null}
                      {(b.city || b.address) && (
                        <p>{[b.city, b.address].filter(Boolean).join(" · ")}</p>
                      )}
                    </div>
                    <Button
                      type="button"
                      size="sm"
                      variant="outline"
                      onClick={() => setReviewBranch(b)}
                    >
                      <Eye className="h-3.5 w-3.5 me-1.5" />
                      {t("review")}
                    </Button>
                    <Button
                      type="button"
                      size="sm"
                      variant="outline"
                      className={cn(
                        "border-destructive/40 text-destructive hover:bg-destructive/10"
                      )}
                      disabled={activeBranches.length <= 1}
                      onClick={() => setDeleteTarget(b)}
                    >
                      <Trash2 className="h-3.5 w-3.5 me-1.5" />
                      {t("delete")}
                    </Button>
                  </div>
                </li>
              ))}
            </ul>
          )}

          <form
            className="space-y-3 border-t border-border pt-4"
            onSubmit={(e) => {
              e.preventDefault();
              if (canSubmit) createBranch.mutate();
            }}
          >
            <p className="text-xs uppercase tracking-wide text-muted-foreground">
              {t("addSection")}
            </p>
            <div className="grid gap-3 sm:grid-cols-2">
              <LabeledField label={t("newName")} htmlFor="new-branch-name">
                <Input
                  id="new-branch-name"
                  value={newBranchName}
                  onChange={(e) => setNewBranchName(e.target.value)}
                />
              </LabeledField>
              <LabeledField label={t("loginPhone")} htmlFor="branch-login-phone">
                <Input
                  id="branch-login-phone"
                  value={loginPhone}
                  onChange={(e) => setLoginPhone(e.target.value)}
                  placeholder="09121234567"
                  dir="ltr"
                  className="text-end"
                  autoComplete="tel"
                />
              </LabeledField>
              <LabeledField
                label={t("managerName")}
                htmlFor="branch-manager-name"
                className="sm:col-span-2"
              >
                <Input
                  id="branch-manager-name"
                  value={managerName}
                  onChange={(e) => setManagerName(e.target.value)}
                  placeholder={t("managerNamePlaceholder")}
                />
              </LabeledField>
            </div>
            <Button
              type="submit"
              className="bg-[#0F6E56] hover:bg-[#0c5a46]"
              disabled={!canSubmit}
            >
              {createBranch.isPending ? "..." : t("add")}
            </Button>
            <p className="text-xs text-muted-foreground">{t("masterPlanHint")}</p>
          </form>
          <p className="text-xs text-muted-foreground">{t("branchSelectHint")}</p>
        </CardContent>
      </Card>

      <AlertDialog
        open={!!deleteTarget}
        onOpenChange={(open) => !open && setDeleteTarget(null)}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{t("deleteTitle")}</AlertDialogTitle>
            <AlertDialogDescription>{t("deleteWarning")}</AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>{tCommon("cancel")}</AlertDialogCancel>
            <AlertDialogAction
              className="bg-destructive hover:bg-destructive/90"
              onClick={() => deleteTarget && deleteBranch.mutate(deleteTarget.id)}
            >
              {t("deleteConfirm")}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      <AlertDialog
        open={!!reviewBranch}
        onOpenChange={(open) => !open && setReviewBranch(null)}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{t("reviewTitle")}</AlertDialogTitle>
            <AlertDialogDescription asChild>
              <div>
                {reviewBranch ? (
                  <dl className="mt-2 space-y-2 text-start text-sm text-foreground">
                    <div>
                      <dt className="text-xs text-muted-foreground">{t("newName")}</dt>
                      <dd className="font-medium">{reviewBranch.name}</dd>
                    </div>
                    {reviewBranch.managerName ? (
                      <div>
                        <dt className="text-xs text-muted-foreground">{t("managerName")}</dt>
                        <dd>{reviewBranch.managerName}</dd>
                      </div>
                    ) : null}
                    {reviewBranch.loginPhone ? (
                      <div>
                        <dt className="text-xs text-muted-foreground">{t("loginPhone")}</dt>
                        <dd dir="ltr">{reviewBranch.loginPhone}</dd>
                      </div>
                    ) : null}
                    {(reviewBranch.city || reviewBranch.address) && (
                      <div>
                        <dt className="text-xs text-muted-foreground">{t("location")}</dt>
                        <dd>
                          {[reviewBranch.city, reviewBranch.address]
                            .filter(Boolean)
                            .join(" · ")}
                        </dd>
                      </div>
                    )}
                    {reviewBranch.isPendingDeletion ? (
                      <p className="rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-900">
                        {purgeCountdownLabel(reviewBranch, t)}
                      </p>
                    ) : null}
                  </dl>
                ) : null}
              </div>
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogAction onClick={() => setReviewBranch(null)}>
              {tCommon("confirm")}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
