'use client';

import { useEffect, useState } from 'react';
import { RiSearchLine, RiFilterOffLine } from '@remixicon/react';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import useInfluencerNumbers from './hooks/useInfluencerNumbers';
import useInfluencerNumberFilterOptions from './hooks/useInfluencerNumberFilterOptions';
import InfluencerNumbersTable from './components/InfluencerNumbersTable/InfluencerNumbersTable';
import UploadPhonesModal from './components/UploadPhonesModal/UploadPhonesModal';

const ALL = 'all';

export const InfluencerNumbers = () => {
  const [currentPage, setCurrentPage] = useState(1);

  // Filter state
  const [searchInput, setSearchInput] = useState('');
  const [search, setSearch] = useState('');
  const [platform, setPlatform] = useState('');
  const [sourceApp, setSourceApp] = useState('');
  const [countryCode, setCountryCode] = useState('');

  // Debounce the search input (~400ms) into the applied `search` value
  useEffect(() => {
    const handler = setTimeout(() => setSearch(searchInput.trim()), 400);
    return () => clearTimeout(handler);
  }, [searchInput]);

  // Reset to page 1 whenever any filter changes
  useEffect(() => {
    setCurrentPage(1);
  }, [search, platform, sourceApp, countryCode]);

  const { data: filterOptions } = useInfluencerNumberFilterOptions();
  const { data, isLoading } = useInfluencerNumbers({
    page: currentPage,
    search,
    platform,
    source_app: sourceApp,
    country_code: countryCode,
  });

  const hasActiveFilters = !!(search || platform || sourceApp || countryCode);

  const clearFilters = () => {
    setSearchInput('');
    setSearch('');
    setPlatform('');
    setSourceApp('');
    setCountryCode('');
  };

  const platforms = filterOptions?.platforms ?? [];
  const sources = filterOptions?.sources ?? [];
  const countryCodes = filterOptions?.country_codes ?? [];

  return (
    <div className="p-6">
      <div className="mb-4 flex items-center justify-end gap-2">
        <UploadPhonesModal />
      </div>

      <div className="mb-4 rounded-lg border bg-muted/30 p-4">
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-3">
          <div className="lg:col-span-2">
            <Label className="text-xs font-medium text-muted-foreground mb-1.5 block">
              Search
            </Label>
            <div className="relative">
              <RiSearchLine className="absolute left-2.5 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
              <Input
                placeholder="Search username, ID or phone..."
                value={searchInput}
                onChange={(e) => setSearchInput(e.target.value)}
                className="h-9 pl-8"
              />
            </div>
          </div>

          <div>
            <Label className="text-xs font-medium text-muted-foreground mb-1.5 block">
              Platform
            </Label>
            <Select
              value={platform || ALL}
              onValueChange={(value) => setPlatform(value === ALL ? '' : value)}
            >
              <SelectTrigger className="h-9">
                <SelectValue placeholder="All platforms" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value={ALL}>All platforms</SelectItem>
                {platforms.map((p) => (
                  <SelectItem key={p} value={p}>
                    {p}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div>
            <Label className="text-xs font-medium text-muted-foreground mb-1.5 block">
              Source
            </Label>
            <Select
              value={sourceApp || ALL}
              onValueChange={(value) => setSourceApp(value === ALL ? '' : value)}
            >
              <SelectTrigger className="h-9">
                <SelectValue placeholder="All sources" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value={ALL}>All sources</SelectItem>
                {sources.map((s) => (
                  <SelectItem key={s} value={s}>
                    {s}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div>
            <Label className="text-xs font-medium text-muted-foreground mb-1.5 block">
              Country Code
            </Label>
            <Select
              value={countryCode || ALL}
              onValueChange={(value) => setCountryCode(value === ALL ? '' : value)}
            >
              <SelectTrigger className="h-9">
                <SelectValue placeholder="All countries" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value={ALL}>All countries</SelectItem>
                {countryCodes.map((c) => (
                  <SelectItem key={c.code} value={c.code}>
                    +{c.code} ({c.count})
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </div>

        {hasActiveFilters && (
          <div className="mt-3 flex justify-end">
            <Button variant="outline" size="sm" className="h-9" onClick={clearFilters}>
              <RiFilterOffLine className="size-4" />
              <span className="ml-1.5">Clear filters</span>
            </Button>
          </div>
        )}
      </div>

      <InfluencerNumbersTable
        data={data?.data?.items || []}
        pagination={data?.data?.pagination}
        currentPage={currentPage}
        onPageChange={setCurrentPage}
        isLoading={isLoading}
      />
    </div>
  );
};

export default InfluencerNumbers;
