import type { LucideIcon } from 'lucide-react';
import type { DavCollection } from './shared';
import { Link, useSearchParams } from 'react-router';
import { CalendarDays, Contact as ContactIcon } from 'lucide-react';
import { davCollectionPath, COLLECTION_PARAM } from './shared';
import { useDavCollections } from './useDavData';

// Left panel for both /calendar and /contacts: the list of collections belonging to this user.
//
// Rows are real links carrying ?collection=<dav path>, so a calendar is a bookmarkable address and the
// right-hand panel reads the same URL rather than being told over a channel. Active state is compared
// against the URL directly instead of NavLink's isActive, because every row shares one pathname and
// differs only in the query string.

type Props = {
  kind: DavCollection['kind'];
  base: '/calendar' | '/contacts';
  title: string;
  icon: LucideIcon;
};

const ROW = 'group relative flex items-center gap-3 rounded-lg px-3 py-2 text-left text-sm transition-colors';

const CollectionNav = ({ kind, base, title, icon: Icon }: Props) => {
  const [params] = useSearchParams();
  const { collections, isLoading } = useDavCollections(kind);
  const fromUrl = params.get(COLLECTION_PARAM);
  // Nothing in the URL means the view falls back to the first collection — highlight the same one.
  const activePath = collections.some((c) => c.path === fromUrl) ? fromUrl : (collections[0]?.path ?? null);

  return (
    <div className="flex h-full flex-col overflow-y-auto bg-muted/30">
      <div className="flex items-center gap-3 px-4 py-4">
        <div className="flex h-9 w-9 items-center justify-center rounded-xl bg-sky-500/15 text-sky-500 ring-1 ring-black/5">
          <Icon className="h-5 w-5" />
        </div>
        <div className="min-w-0">
          <div className="truncate text-sm font-semibold leading-tight">{title}</div>
          <div className="text-xs text-muted-foreground">
            {isLoading
              ? 'loading…'
              : `${collections.length} ${collections.length === 1 ? 'collection' : 'collections'}`}
          </div>
        </div>
      </div>

      <nav className="flex flex-col gap-0.5 px-2 pb-3">
        {collections.map((collection) => {
          const isActive = collection.path === activePath;
          return (
            <Link
              key={collection.path}
              to={davCollectionPath(base, collection.path)}
              className={`${ROW} ${
                isActive
                  ? 'bg-primary/10 font-medium text-primary'
                  : 'text-muted-foreground hover:bg-muted hover:text-foreground'
              }`}
            >
              {isActive && (
                <span className="absolute left-0 top-1/2 h-5 w-1 -translate-y-1/2 rounded-r-full bg-primary" />
              )}
              <span
                className="h-2.5 w-2.5 shrink-0 rounded-full ring-1 ring-black/10"
                style={{ backgroundColor: collection.color || '#94a3b8' }}
              />
              <span className="flex-1 truncate">{collection.displayName}</span>
            </Link>
          );
        })}
        {!isLoading && collections.length === 0 && (
          <p className="px-3 py-2 text-xs text-muted-foreground">
            Nothing here yet. Add one from a phone or desktop client over CalDAV/CardDAV.
          </p>
        )}
      </nav>
    </div>
  );
};

export const CalendarNav = () => (
  <CollectionNav kind="calendar" base="/calendar" title="Calendar" icon={CalendarDays} />
);

export const ContactsNav = () => (
  <CollectionNav kind="addressbook" base="/contacts" title="Contacts" icon={ContactIcon} />
);
