import { useState, type ReactElement } from 'react';
import styled from '@lilith/ui-styled-components';
import { Check, Edit2, Users, X } from 'lucide-react';

import { EmptyState } from '@/components/EmptyState';
import { PageError } from '@/components/PageError';
import { useIdentities, useMergeIdentities, useRenameIdentity } from '@/hooks/usePhotos';
import type { Identity } from '@/types';

const List = styled.ul`
  list-style: none;
  margin: 0;
  padding: 8px;
  overflow-y: auto;
  flex: 1;
`;

const Row = styled.li`
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 12px;
  border-bottom: 1px solid #1c1c26;
  gap: 12px;
`;

const Identity = styled.div`
  flex: 1;
  display: flex;
  align-items: center;
  gap: 10px;
  min-width: 0;
`;

const Avatar = styled.div`
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #1c1c26;
  border: 1px solid #2a2a38;
  display: grid;
  place-items: center;
  color: #c9a84c;
  flex-shrink: 0;
`;

const NameBlock = styled.div`
  min-width: 0;
  flex: 1;
`;

const Name = styled.div`
  font-size: 13px;
  color: #e0e0f0;
  font-weight: 600;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
`;

const Sub = styled.div`
  font-size: 11px;
  color: #8a8a9a;
`;

const Actions = styled.div`
  display: flex;
  gap: 6px;
  flex-shrink: 0;
`;

const IconButton = styled.button`
  background: transparent;
  color: #8a8a9a;
  border: 1px solid #2a2a38;
  border-radius: 4px;
  padding: 4px 6px;
  display: grid;
  place-items: center;
  cursor: pointer;

  &:hover {
    color: #e0e0f0;
    border-color: rgba(201,168,76,0.4);
  }

  &:disabled {
    opacity: 0.4;
    cursor: not-allowed;
  }
`;

const Input = styled.input`
  background: #13131a;
  color: #e0e0f0;
  border: 1px solid #2a2a38;
  border-radius: 4px;
  padding: 4px 8px;
  font-size: 13px;
  flex: 1;
  min-width: 0;
`;

const SpinnerWrap = styled.div`
  padding: 20px;
  font-size: 12px;
  color: #8a8a9a;
  text-align: center;
`;

const Banner = styled.div`
  padding: 8px 16px;
  background: rgba(201,168,76,0.1);
  border-bottom: 1px solid #2a2a38;
  color: #c9a84c;
  font-size: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
`;

interface RowEditor {
  identityId: string;
  name: string;
}

export interface IdentitiesViewProps {
  deviceId: string | undefined;
}

export function IdentitiesView({ deviceId }: IdentitiesViewProps): ReactElement {
  const { data, isLoading, error } = useIdentities(deviceId);
  const renameMut = useRenameIdentity();
  const mergeMut = useMergeIdentities();
  const [editor, setEditor] = useState<RowEditor | null>(null);
  const [mergeTarget, setMergeTarget] = useState<string | null>(null);

  if (!deviceId) {
    return <EmptyState icon={<Users size={36} />} heading="No device selected" />;
  }
  if (isLoading) return <SpinnerWrap aria-live="polite">Loading identities…</SpinnerWrap>;
  if (error) return <PageError message="Failed to load identities" />;
  if (!data || data.length === 0) {
    return <EmptyState icon={<Users size={36} />} heading="No identities yet" sub="People appear here after photos finish face extraction." />;
  }

  function saveRename(id: string, name: string): void {
    renameMut.mutate({ id, name: name.trim() === '' ? null : name.trim() });
    setEditor(null);
  }

  function startMerge(id: string): void {
    setMergeTarget(id);
  }

  function completeMerge(sourceId: string): void {
    if (!mergeTarget || mergeTarget === sourceId) {
      setMergeTarget(null);
      return;
    }
    mergeMut.mutate({ targetId: mergeTarget, sourceId });
    setMergeTarget(null);
  }

  function rowFor(identity: Identity): ReactElement {
    const isEditing = editor?.identityId === identity.id;
    const isMergeTarget = mergeTarget === identity.id;
    return (
      <Row key={identity.id}>
        <Identity>
          <Avatar>
            <Users size={18} />
          </Avatar>
          <NameBlock>
            {isEditing ? (
              <Input
                autoFocus
                value={editor.name}
                onChange={(e) => setEditor({ identityId: identity.id, name: e.target.value })}
                onKeyDown={(e) => {
                  if (e.key === 'Enter') saveRename(identity.id, editor.name);
                  if (e.key === 'Escape') setEditor(null);
                }}
              />
            ) : (
              <Name>{identity.name ?? 'Unnamed person'}</Name>
            )}
            <Sub>
              {identity.faceCount} face{identity.faceCount === 1 ? '' : 's'}
              {identity.centroidUpdatedAt && ` · updated ${new Date(identity.centroidUpdatedAt).toLocaleDateString()}`}
            </Sub>
          </NameBlock>
        </Identity>
        <Actions>
          {isEditing ? (
            <>
              <IconButton aria-label="Save" onClick={() => saveRename(identity.id, editor.name)}>
                <Check size={14} />
              </IconButton>
              <IconButton aria-label="Cancel" onClick={() => setEditor(null)}>
                <X size={14} />
              </IconButton>
            </>
          ) : mergeTarget ? (
            <IconButton
              disabled={isMergeTarget}
              onClick={() => completeMerge(identity.id)}
              aria-label="Merge into target"
            >
              {isMergeTarget ? 'target' : 'merge here'}
            </IconButton>
          ) : (
            <>
              <IconButton aria-label="Rename" onClick={() => setEditor({ identityId: identity.id, name: identity.name ?? '' })}>
                <Edit2 size={14} />
              </IconButton>
              <IconButton aria-label="Merge" onClick={() => startMerge(identity.id)}>
                merge
              </IconButton>
            </>
          )}
        </Actions>
      </Row>
    );
  }

  return (
    <>
      {mergeTarget && (
        <Banner>
          <span>Merging — pick another identity whose faces will move into this one.</span>
          <IconButton onClick={() => setMergeTarget(null)} aria-label="Cancel merge">
            <X size={14} /> Cancel
          </IconButton>
        </Banner>
      )}
      <List>{data.map(rowFor)}</List>
    </>
  );
}
