"use client";

import { useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { Plus, Pencil, Search } from "lucide-react";
import { 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 { 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 { CustomerWizard, type CustomerWizardMode } from "@/components/crm/customer-wizard";

export function CrmScreen() {
  const t = useTranslations("crm");
  const tCommon = useTranslations("common");
  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 { 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] });
  };

  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>
                <Button
                  size="sm"
                  variant="outline"
                  className="w-full"
                  onClick={() => openWizard("edit", c)}
                >
                  <Pencil className="me-1 h-3.5 w-3.5" />
                  {tCommon("edit")}
                </Button>
              </CardContent>
            </Card>
          ))}
        </div>
      )}

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