import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Link, useNavigate } from 'react-router-dom';
import {
  PlusIcon, PencilIcon, EyeIcon, MagnifyingGlassIcon, AdjustmentsHorizontalIcon,
  Squares2X2Icon, TableCellsIcon, ExclamationCircleIcon, IdentificationIcon,
} from '@heroicons/react/24/outline';
import { api } from '../lib/api';
import type { ApiResponse } from '../lib/api';
import type { PatientRecord } from '../types';
import { formatNumber } from '../lib/utils';
import Pagination from '../components/ui/Pagination';

const LIMIT = 20;
const EMPTY: PatientRecord[] = [];

function TagDots({ tags }: { tags?: PatientRecord['tags'] }) {
  if (!tags || tags.length === 0) return null;
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center' }}>
      {tags.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,
        }} />
      ))}
      {tags.length > 3 && <span style={{ fontSize: 11, color: 'var(--text-3)', marginInlineStart: 4 }}>+{formatNumber(tags.length - 3)}</span>}
    </span>
  );
}

/** پرونده‌ها — patient records list (table + card views) matching the Figma design. */
export default function PatientsListPage() {
  const navigate = useNavigate();
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState('');
  const [view, setView] = useState<'table' | 'card'>('table');

  const { data, isLoading } = useQuery<ApiResponse<PatientRecord[]> & { meta?: { totalRecords: number } }>({
    queryKey: ['patients', page, search],
    queryFn: () => api.get(`/api/v1/patients?page=${page}&limit=${LIMIT}&search=${encodeURIComponent(search)}`),
  });

  const records = data?.data ?? EMPTY;
  const total   = data?.meta?.totalRecords ?? 0;

  const editHref = (r: PatientRecord) => `/admin/patients/${r.uuid}/edit`;
  // detail page arrives in phase B; view currently opens the edit form
  const viewHref = editHref;

  return (
    <div className="fade-in" style={{ maxWidth: 1160, margin: '0 auto' }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap', marginBottom: 20 }}>
        <h1 className="section-title">پرونده‌ها</h1>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
          <div style={{ position: 'relative' }}>
            <MagnifyingGlassIcon style={{ width: 16, position: 'absolute', insetInlineStart: 10, top: '50%', transform: 'translateY(-50%)', color: 'var(--text-3)', pointerEvents: 'none' }} />
            <input
              className="cp-input" placeholder="کد ملی، شماره پرونده یا نام مراجعه کننده را وارد کنید..."
              value={search} onChange={(e) => { setSearch(e.target.value); setPage(1); }}
              style={{ width: 320, maxWidth: '60vw', height: 40, paddingInlineStart: 34 }}
            />
          </div>
          {/* view toggle */}
          <div style={{ display: 'flex', border: '1px solid var(--border)', borderRadius: 'var(--r-sm)', overflow: 'hidden' }}>
            <button aria-label="نمایش کارتی" onClick={() => setView('card')} style={{ padding: '8px 10px', border: 'none', cursor: 'pointer', background: view === 'card' ? 'var(--primary-soft)' : 'var(--surface)', color: view === 'card' ? 'var(--primary)' : 'var(--text-3)' }}>
              <Squares2X2Icon style={{ width: 18 }} />
            </button>
            <button aria-label="نمایش جدولی" onClick={() => setView('table')} style={{ padding: '8px 10px', border: 'none', cursor: 'pointer', background: view === 'table' ? 'var(--primary-soft)' : 'var(--surface)', color: view === 'table' ? 'var(--primary)' : 'var(--text-3)' }}>
              <TableCellsIcon style={{ width: 18 }} />
            </button>
          </div>
          <button className="btn" aria-label="فیلترها" style={{ height: 40, width: 44, padding: 0, display: 'grid', placeItems: 'center' }}>
            <AdjustmentsHorizontalIcon style={{ width: 18 }} />
          </button>
          <button className="btn primary" style={{ height: 40 }} onClick={() => navigate('/admin/patients/new')}>
            <PlusIcon style={{ width: 16 }} /> تشکیل پرونده
          </button>
        </div>
      </div>

      {isLoading ? (
        <div style={{ padding: 24, color: 'var(--text-3)', fontSize: 13 }}>در حال بارگذاری...</div>
      ) : records.length === 0 ? (
        <div className="card" style={{ padding: '60px 0', textAlign: 'center', color: 'var(--text-3)' }}>
          <IdentificationIcon style={{ width: 52, margin: '0 auto 14px', display: 'block', opacity: 0.3 }} />
          <div style={{ fontSize: 14, color: 'var(--text-2)' }}>پرونده‌ای یافت نشد.</div>
        </div>
      ) : view === 'table' ? (
        <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', overflow: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 760 }}>
            <thead>
              <tr style={{ background: 'var(--surface-2)', color: 'var(--text-2)', fontSize: 13 }}>
                {['ردیف', 'مراجعه کننده', 'برچسب ها', 'شماره پرونده', 'شماره تماس', 'کد ملی', 'عملیات'].map((h) => (
                  <th key={h} style={{ padding: '12px 14px', textAlign: 'center', fontWeight: 600, whiteSpace: 'nowrap' }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {records.map((r, i) => (
                <tr key={r.uuid} style={{ borderTop: '1px solid var(--border)', fontSize: 13.5, textAlign: 'center' }}>
                  <td style={{ padding: '12px 14px', color: 'var(--text-3)' }}>{formatNumber((page - 1) * LIMIT + i + 1)}</td>
                  <td style={{ padding: '12px 14px' }}>
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontWeight: 600 }}>
                      {r.user_name || '—'}
                      {!r.user_national_code && <ExclamationCircleIcon style={{ width: 16, color: 'var(--danger)' }} />}
                    </span>
                  </td>
                  <td style={{ padding: '12px 14px' }}>
                    {r.tags && r.tags.length > 0 ? <TagDots tags={r.tags} /> : <Link to={editHref(r)} style={{ color: 'var(--primary)', fontSize: 12.5, textDecoration: 'none' }}>+ اضافه کردن</Link>}
                  </td>
                  <td style={{ padding: '12px 14px' }}>{r.record_number || '—'}</td>
                  <td style={{ padding: '12px 14px', direction: 'ltr' }}>{r.user_mobile || '—'}</td>
                  <td style={{ padding: '12px 14px', direction: 'ltr' }}>{r.user_national_code || '—'}</td>
                  <td style={{ padding: '12px 14px' }}>
                    <span style={{ display: 'inline-flex', gap: 8, justifyContent: 'center' }}>
                      <Link to={viewHref(r)} aria-label="مشاهده" style={{ color: 'var(--primary)' }}><EyeIcon style={{ width: 18 }} /></Link>
                      <Link to={editHref(r)} aria-label="ویرایش" style={{ color: 'var(--accent)' }}><PencilIcon style={{ width: 18 }} /></Link>
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 14 }}>
          {records.map((r) => (
            <div key={r.uuid} style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', padding: 16 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 10 }}>
                <span style={{ fontWeight: 700, fontSize: 15 }}>{r.user_name || '—'}</span>
                <TagDots tags={r.tags} />
              </div>
              <div style={{ fontSize: 12.5, color: 'var(--text-3)', display: 'flex', flexDirection: 'column', gap: 4 }}>
                <span>شماره پرونده: {r.record_number || '—'}</span>
                <span style={{ direction: 'ltr', textAlign: 'right' }}>تماس: {r.user_mobile || '—'}</span>
                <span style={{ direction: 'ltr', textAlign: 'right' }}>کد ملی: {r.user_national_code || '—'}</span>
              </div>
              <div style={{ display: 'flex', gap: 8, marginTop: 12, borderTop: '1px solid var(--border)', paddingTop: 10 }}>
                <Link to={viewHref(r)} className="btn sm ghost" style={{ flex: 1, justifyContent: 'center', color: 'var(--primary)' }}><EyeIcon style={{ width: 15 }} /> مشاهده</Link>
                <Link to={editHref(r)} className="btn sm ghost" style={{ flex: 1, justifyContent: 'center', color: 'var(--accent)' }}><PencilIcon style={{ width: 15 }} /> ویرایش</Link>
              </div>
            </div>
          ))}
        </div>
      )}

      <div style={{ marginTop: 20, display: 'flex', justifyContent: 'center' }}>
        <Pagination page={page} total={total} limit={LIMIT} onPageChange={setPage} />
      </div>
    </div>
  );
}
