"use client";

import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { Plus, Pencil, Search, Trash2 } from "lucide-react";
import { apiDelete, apiGet } from "@/lib/api/client";
import type { Customer } from "@/lib/api/types";
import { useAuthStore } from "@/lib/stores/auth.store";
import { formatNumber } from "@/lib/format";
import { notify } from "@/lib/notify";
import { useApiError } from "@/lib/use-api-error";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { LabeledField } from "@/components/ui/labeled-field";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { ConfirmDialog } from "@/components/ui/confirm-dialog";
import { CustomerWizard, type CustomerWizardMode } from "@/components/crm/customer-wizard";

export function CrmScreen() {
  const t = useTranslations("crm");
  const tCommon = useTranslations("common");
  const apiError = useApiError();
  const cafeId = useAuthStore((s) => s.user?.cafeId);
  const queryClient = useQueryClient();

  const [search, setSearch] = useState("");
  const [debouncedSearch, setDebouncedSearch] = useState("");
  const [wizardOpen, setWizardOpen] = useState(false);
  const [wizardMode, setWizardMode] = useState<CustomerWizardMode>("create");
  const [editingCustomer, setEditingCustomer] = useState<Customer | null>(null);
  const [deleteTarget, setDeleteTarget] = useState<Customer | null>(null);

  const { data: customers = [], isLoading } = useQuery({
    queryKey: ["customers", cafeId, debouncedSearch],
    queryFn: () =>
      apiGet<Customer[]>(
        `/api/cafes/${cafeId}/customers${debouncedSearch ? `?q=${encodeURIComponent(debouncedSearch)}` : ""}`
      ),
    enabled: !!cafeId,
  });

  const openWizard = (mode: CustomerWizardMode, customer?: Customer) => {
    setWizardMode(mode);
    setEditingCustomer(customer ?? null);
    setWizardOpen(true);
  };

  const refreshCustomers = () => {
    queryClient.invalidateQueries({ queryKey: ["customers", cafeId] });
  };

  const deleteCustomer = useMutation({
    mutationFn: (id: string) => apiDelete(`/api/cafes/${cafeId}/customers/${id}`),
    onSuccess: () => {
      refreshCustomers();
      setDeleteTarget(null);
      notify.success(t("deleted"));
    },
    onError: (err) => notify.error(apiError(err)),
  });

  if (!cafeId) return null;

  return (
    <div className="space-y-4">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <h2 className="text-xl font-bold">{t("title")}</h2>
        <Button
          className="bg-[#0F6E56] hover:bg-[#0c5a46]"
          onClick={() => openWizard("create")}
        >
          <Plus className="me-2 h-4 w-4" />
          {t("addCustomer")}
        </Button>
      </div>

      <div className="flex flex-wrap items-end gap-2">
        <LabeledField label={tCommon("search")} htmlFor="crm-search" className="min-w-[12rem] flex-1">
          <Input
            id="crm-search"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && setDebouncedSearch(search)}
          />
        </LabeledField>
        <Button variant="outline" onClick={() => setDebouncedSearch(search)}>
          <Search className="h-4 w-4" />
          {tCommon("search")}
        </Button>
      </div>

      {isLoading ? (
        <p className="text-muted-foreground">{tCommon("loading")}</p>
      ) : customers.length === 0 ? (
        <p className="text-muted-foreground">{t("noCustomers")}</p>
      ) : (
        <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
          {customers.map((c) => (
            <Card key={c.id} className="rounded-xl border border-border/80 shadow-sm">
              <CardHeader className="pb-2">
                <div className="flex items-start justify-between gap-2">
                  <CardTitle className="text-base">{c.name}</CardTitle>
                  <Badge variant="secondary">{t(`groups.${c.group}`)}</Badge>
                </div>
              </CardHeader>
              <CardContent className="space-y-3">
                <div className="space-y-1 text-sm text-muted-foreground">
                  <p dir="ltr" className="text-end font-mono">
                    {c.phone}
                  </p>
                  {c.nationalId ? (
                    <p>
                      {t("nationalId")}: {c.nationalId}
                    </p>
                  ) : null}
                  <p>
                    {t("loyaltyPoints")}: {formatNumber(c.loyaltyPoints)}
                  </p>
                </div>
                <div className="flex gap-2">
                  <Button
                    size="sm"
                    variant="outline"
                    className="flex-1"
                    onClick={() => openWizard("edit", c)}
                  >
                    <Pencil className="me-1 h-3.5 w-3.5" />
                    {tCommon("edit")}
                  </Button>
                  <Button
                    size="sm"
                    variant="outline"
                    className="text-red-600 hover:bg-red-50 hover:text-red-700"
                    aria-label={tCommon("delete")}
                    onClick={() => setDeleteTarget(c)}
                  >
                    <Trash2 className="h-3.5 w-3.5" />
                  </Button>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      <ConfirmDialog
        open={!!deleteTarget}
        onOpenChange={(o) => {
          if (!o) setDeleteTarget(null);
        }}
        title={t("deleteConfirmTitle")}
        description={deleteTarget ? t("deleteConfirmDesc", { name: deleteTarget.name }) : undefined}
        busy={deleteCustomer.isPending}
        onConfirm={() => deleteTarget && deleteCustomer.mutate(deleteTarget.id)}
      />

      <CustomerWizard
        open={wizardOpen}
        mode={wizardMode}
        cafeId={cafeId}
        customer={editingCustomer}
        onClose={() => setWizardOpen(false)}
        onSaved={refreshCustomers}
      />
    </div>
  );
}
