import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { PlusIcon, XMarkIcon } from '@heroicons/react/24/outline';
import { toast } from 'sonner';
import { api } from '../lib/api';
import type { ApiResponse } from '../lib/api';
import { formatNumber } from '../lib/utils';
import type { PatientRecord } from '../types';

interface TenantTag { uuid: string; name: string; color: string; active: boolean }

/**
 * The برچسب‌ها cell for a patient row: shows the record's tag dots and, on click,
 * opens a popover to assign/remove tenant tags inline. Assignment PATCHes the
 * record's full `tags` array (the backend replaces the set) and refreshes the list.
 */
export default function PatientTagsCell({ record }: { record: PatientRecord }) {
  const qc = useQueryClient();
  const [open, setOpen] = useState(false);
  const current = record.tags ?? [];
  const currentUuids = current.map((t) => t.uuid);

  const { data: tagsData, isLoading } = useQuery<ApiResponse<TenantTag[]>>({
    queryKey: ['tenant-tags'],
    queryFn: () => api.get('/api/v1/tenant-tags'),
    enabled: open,
  });
  const allTags = tagsData?.data ?? [];

  const mutate = useMutation({
    mutationFn: (uuids: string[]) => api.patch(`/api/v1/patient/${record.uuid}`, { tags: uuids }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['patients'] }),
    onError: (e: any) => toast.error(e?.message || 'خطا در به‌روزرسانی برچسب‌ها'),
  });

  const toggle = (uuid: string) => {
    const next = currentUuids.includes(uuid) ? currentUuids.filter((u) => u !== uuid) : [...currentUuids, uuid];
    mutate.mutate(next);
  };

  return (
    <span style={{ position: 'relative', display: 'inline-flex' }}>
      {current.length === 0 ? (
        <button type="button" onClick={() => setOpen((v) => !v)} className="btn sm ghost" style={{ color: 'var(--primary)', fontSize: 12.5, gap: 3 }}>
          <PlusIcon style={{ width: 14 }} /> اضافه کردن
        </button>
      ) : (
        <button type="button" onClick={() => setOpen((v) => !v)} style={{ display: 'inline-flex', alignItems: 'center', background: 'none', border: 'none', cursor: 'pointer', padding: 4 }} aria-label="ویرایش برچسب‌ها">
          {current.slice(0, 3).map((t, i) => (
            <span key={t.uuid} title={t.name} style={{
              width: 16, height: 16, borderRadius: '50%', background: t.color,
              border: '2px solid var(--surface)', marginInlineStart: i === 0 ? 0 : -6,
            }} />
          ))}
          {current.length > 3 && <span style={{ fontSize: 11, color: 'var(--text-3)', marginInlineStart: 4 }}>+{formatNumber(current.length - 3)}</span>}
        </button>
      )}

      {open && (
        <>
          <div style={{ position: 'fixed', inset: 0, zIndex: 60 }} onClick={() => setOpen(false)} />
          <div style={{
            position: 'absolute', top: 'calc(100% + 6px)', insetInlineStart: 0, zIndex: 61,
            background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-sm)',
            boxShadow: 'var(--shadow)', padding: 10, minWidth: 200, maxWidth: 300,
          }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
              <span style={{ fontSize: 13, fontWeight: 600 }}>برچسب‌ها</span>
              <button type="button" onClick={() => setOpen(false)} className="mini-btn" aria-label="بستن"><XMarkIcon style={{ width: 15 }} /></button>
            </div>
            {isLoading ? (
              <div style={{ fontSize: 12.5, color: 'var(--text-3)', padding: '6px 0' }}>در حال بارگذاری…</div>
            ) : allTags.length === 0 ? (
              <div style={{ fontSize: 12, color: 'var(--text-3)' }}>برچسبی تعریف نشده است.</div>
            ) : (
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                {allTags.map((tag) => {
                  const assigned = currentUuids.includes(tag.uuid);
                  return (
                    <button
                      key={tag.uuid}
                      type="button"
                      disabled={mutate.isPending}
                      onClick={() => toggle(tag.uuid)}
                      style={{
                        display: 'inline-flex', alignItems: 'center', gap: 4, cursor: 'pointer',
                        fontSize: 12, height: 24, padding: '0 8px', borderRadius: 999,
                        border: '1px solid var(--border)',
                        background: assigned ? tag.color : 'var(--surface-2)',
                        color: assigned ? 'var(--on-primary)' : 'var(--text-2)',
                      }}
                    >
                      {assigned ? <XMarkIcon style={{ width: 12 }} /> : <PlusIcon style={{ width: 12 }} />}
                      {tag.name}
                    </button>
                  );
                })}
              </div>
            )}
          </div>
        </>
      )}
    </span>
  );
}
