'use client';

import { useEffect, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useQuery } from '@tanstack/react-query';
import { format } from 'date-fns';
import { Search, X } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Spinner } from '@/components/ui/spinners';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import PaginationComponent from '@/modules/client-management/components/paginationComponent/paginationComponent';
import { fetchSocialAnalysisBrands } from '@/network/apis/dashboard/social-analysis/social-analysis.apis';
import type { SocialAnalysisBrand } from '@/network/apis/dashboard/social-analysis/social-analysis.types';
import { BrandSocialAccountsSheet } from './BrandSocialAccountsSheet';

type Coverage = 'missing_own' | 'has_own' | 'all';

const COVERAGE_CHIPS: { label: string; value: Coverage }[] = [
  { label: 'Missing own accounts', value: 'missing_own' },
  { label: 'Has own accounts', value: 'has_own' },
  { label: 'All brands', value: 'all' },
];

const safeDate = (value: string | null | undefined) => {
  if (!value) return '—';
  const d = new Date(value);
  return Number.isNaN(d.getTime()) ? value : format(d, 'dd MMM yyyy');
};

/**
 * Every brand, and whether we know its social accounts.
 *
 * Opens on "Missing own accounts": most brands never gave us their handles, and
 * adding them is the work this page exists for. A brand without its own account
 * cannot be analysed, however many competitors it tracks.
 */
export function BrandSocialAccountsList() {
  const router = useRouter();
  const sp = useSearchParams();

  const coverage = (sp?.get('coverage') ?? 'missing_own') as Coverage;
  const search = sp?.get('search') ?? '';
  const page = Number(sp?.get('page') ?? 1);

  const [searchInput, setSearchInput] = useState(search);
  useEffect(() => setSearchInput(search), [search]);

  const [selected, setSelected] = useState<SocialAnalysisBrand | null>(null);

  const { data, isLoading, isError } = useQuery({
    queryKey: ['social-analysis-brands', coverage, search, page],
    queryFn: () =>
      fetchSocialAnalysisBrands({
        page,
        per_page: 25,
        coverage: coverage === 'all' ? undefined : coverage,
        search: search || undefined,
      }),
  });

  const setParams = (next: Record<string, string | undefined>) => {
    const params = new URLSearchParams(sp?.toString() ?? '');
    Object.entries(next).forEach(([k, v]) => {
      if (v === undefined || v === '') params.delete(k);
      else params.set(k, v);
    });
    if (!('page' in next)) params.delete('page');
    router.push(`?${params.toString()}`);
  };

  const summary = data?.summary;

  return (
    <div className="space-y-4">
      {summary && (
        <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
          <SummaryTile label="Brands" value={summary.brands} />
          <SummaryTile
            label="Brands with their own accounts"
            value={summary.brands_with_own}
            hint={`${summary.brands - summary.brands_with_own} still missing`}
          />
          <SummaryTile label="Accounts tracked" value={summary.accounts_tracked} />
        </div>
      )}

      <div className="flex flex-wrap items-center gap-2">
        {COVERAGE_CHIPS.map((chip) => (
          <Button
            key={chip.value}
            size="sm"
            variant={coverage === chip.value ? 'primary' : 'outline'}
            onClick={() => setParams({ coverage: chip.value })}
          >
            {chip.label}
          </Button>
        ))}

        <div className="ms-auto flex items-center gap-2">
          <Input
            className="h-9 w-[240px]"
            placeholder="Brand, name or email"
            value={searchInput}
            onChange={(e) => setSearchInput(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === 'Enter') setParams({ search: searchInput.trim() });
            }}
          />
          <Button
            size="sm"
            variant="outline"
            onClick={() => setParams({ search: searchInput.trim() })}
          >
            <Search className="h-4 w-4" />
          </Button>
          {search && (
            <Button size="sm" variant="ghost" onClick={() => setParams({ search: undefined })}>
              <X className="h-4 w-4" />
            </Button>
          )}
        </div>
      </div>

      <Card>
        <CardContent className="p-0">
          {isLoading ? (
            <div className="flex justify-center py-12">
              <Spinner className="h-6 w-6" />
            </div>
          ) : isError ? (
            <p className="py-12 text-center text-sm text-muted-foreground">
              Could not load brands.
            </p>
          ) : !data?.items?.length ? (
            <p className="py-12 text-center text-sm text-muted-foreground">
              {coverage === 'missing_own'
                ? 'Every brand has at least one of its own accounts.'
                : 'No brands match this filter.'}
            </p>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Brand</TableHead>
                  <TableHead>Own accounts</TableHead>
                  <TableHead>Competitors</TableHead>
                  <TableHead>Collected</TableHead>
                  <TableHead>Last collected</TableHead>
                  <TableHead className="text-end">Action</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {data.items.map((brand) => (
                  <TableRow
                    key={brand.id}
                    className="cursor-pointer"
                    onClick={() => setSelected(brand)}
                  >
                    <TableCell>
                      <div className="font-medium">
                        {brand.brand_name || brand.name || `Brand #${brand.id}`}
                      </div>
                      <div className="text-xs text-muted-foreground">{brand.email ?? '—'}</div>
                    </TableCell>
                    <TableCell>
                      {brand.own_count > 0 ? (
                        brand.own_count
                      ) : (
                        <Badge variant="warning" appearance="outline" size="sm">
                          None yet
                        </Badge>
                      )}
                    </TableCell>
                    <TableCell>{brand.competitor_count}</TableCell>
                    <TableCell>
                      {brand.collected_count} / {brand.own_count + brand.competitor_count}
                    </TableCell>
                    <TableCell>{safeDate(brand.last_collected_at)}</TableCell>
                    <TableCell className="text-end">
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={(e) => {
                          e.stopPropagation();
                          setSelected(brand);
                        }}
                      >
                        {brand.own_count > 0 ? 'Manage' : 'Add accounts'}
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      {data?.pagination && data.pagination.last_page > 1 && (
        <PaginationComponent
          currentPage={data.pagination.current_page}
          totalPages={data.pagination.last_page}
          onPageChange={(p: number) => setParams({ page: String(p) })}
        />
      )}

      <BrandSocialAccountsSheet
        brand={selected}
        open={!!selected}
        onClose={() => setSelected(null)}
      />
    </div>
  );
}

function SummaryTile({ label, value, hint }: { label: string; value: number; hint?: string }) {
  return (
    <Card>
      <CardContent className="p-4">
        <p className="text-xs font-medium text-muted-foreground">{label}</p>
        <p className="text-2xl font-semibold">{value.toLocaleString()}</p>
        {hint ? <p className="text-xs text-muted-foreground">{hint}</p> : null}
      </CardContent>
    </Card>
  );
}
