"use client";

import { useState } from "react";
import { PageLayout } from "@/components/design-system/page-layout";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { FilterSelect } from "@/components/ui/filter-select";
import { ListPagination } from "@/components/ui/list-pagination";
import { useLocale } from "@/components/providers/locale-provider";
import { ACTIVITY_FILTER_CATEGORIES } from "@/lib/activity-config";
import { ActivityTimeline } from "@/components/timeline/activity-timeline";

export function ActivitiesFeed() {
  const { locale } = useLocale();
  const isAr = locale === "ar";
  const [q, setQ] = useState("");
  const [category, setCategory] = useState("");
  const [dateFrom, setDateFrom] = useState("");
  const [dateTo, setDateTo] = useState("");
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [refreshKey, setRefreshKey] = useState(0);

  const categoryOptions = Object.entries(ACTIVITY_FILTER_CATEGORIES).map(([key, v]) => ({
    value: key,
    label: isAr ? v.ar : v.en,
  }));

  return (
    <PageLayout
      title={isAr ? "سجل النشاط" : "Activity feed"}
      description={
        isAr
          ? "مركز موحد لجميع تفاعلات العملاء عبر الحملات والسلاسل والصندوق والمهام"
          : "Unified hub for all customer interactions across campaigns, sequences, inbox, and tasks"
      }
    >
      <div className="mb-4 flex flex-wrap gap-2">
        <Input
          placeholder={isAr ? "بحث بالعنوان أو الوصف" : "Search title or description"}
          value={q}
          onChange={(e) => setQ(e.target.value)}
          className="min-w-[200px] flex-1"
        />
        <FilterSelect
          value={category}
          onChange={setCategory}
          options={categoryOptions.map((o) => o.value)}
          allLabel={isAr ? "كل الأنواع" : "All types"}
          labels={Object.fromEntries(categoryOptions.map((o) => [o.value, o.label]))}
        />
        <Input type="date" value={dateFrom} onChange={(e) => setDateFrom(e.target.value)} />
        <Input type="date" value={dateTo} onChange={(e) => setDateTo(e.target.value)} />
        <Button
          type="button"
          onClick={() => {
            setPage(1);
            setRefreshKey((n) => n + 1);
          }}
        >
          {isAr ? "بحث" : "Search"}
        </Button>
      </div>

      <ActivityTimeline
        showFilters={false}
        limit={25}
        page={page}
        q={q}
        category={category}
        dateFrom={dateFrom}
        dateTo={dateTo}
        refreshKey={refreshKey}
        onLoaded={(p) => setTotalPages(p?.totalPages ?? 1)}
      />

      <ListPagination page={page} totalPages={totalPages} onPageChange={setPage} />
    </PageLayout>
  );
}
