import { useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Link, useNavigate } from 'react-router-dom';
import {
  PencilIcon, EyeIcon, ExclamationCircleIcon, IdentificationIcon,
  UserIcon, EllipsisHorizontalIcon,
} from '@heroicons/react/24/outline';
import { api } from '../lib/api';
import { useUrlState, pageOf } from '../hooks/useUrlState';
import type { ApiResponse } from '../lib/api';
import type { PatientRecord } from '../types';
import { formatNumber, toDate } from '../lib/utils';
import Pagination from '../components/ui/Pagination';
import PatientTagsCell from '../components/PatientTagsCell';
import PatientsFilterModal, { type PatientFilters } from '../components/PatientsFilterModal';
import { usePermissions } from '../hooks/usePermissions';
import {
  SearchHeaderP, TurnsFilter, PatientsGridView, PatientsCategoryView, AddTurn,
} from '../components/icons/FilesToolbarIcons';

// tauri /files paginates card view by 16 and table view by 12.
const CARD_PAGE_SIZE = 16;
const TABLE_PAGE_SIZE = 12;
const EMPTY: PatientRecord[] = [];

/** unix start-of-day for `from`, end-of-day for `to`, from a gregorian Y-m-d. */
function dayBound(value: string | undefined, end: boolean): number | undefined {
  if (!value) return undefined;
  const d = toDate(value);
  if (!d) return undefined;
  const secs = Math.floor(d.setHours(0, 0, 0, 0) / 1000);
  return end ? secs + 86399 : secs;
}

/** Number of filters currently applied (for the button badge). */
function countFilters(f: PatientFilters): number {
  return [f.gender, f.insurance_id, f.admitted_from, f.admitted_to, f.service_status, f.has_debt || undefined, f.tags?.length ? '1' : undefined]
    .filter(Boolean).length;
}

/**
 * A single patient card — mirrors tauri `files/list/CardView` pixel-for-pixel
 * (avatar + name + ⋮ menu header, file-number/mobile rows, tags footer).
 */
function PatientCard({ r, onView, onEdit, canUpdate }: { r: PatientRecord; onView: () => void; onEdit: () => void; canUpdate: boolean }) {
  const [menu, setMenu] = useState(false);
  return (
    <div
      className="bg-[var(--surface)] rounded-[6px] p-[14px] border border-[var(--border)] shadow-sm transition-all duration-300 hover:shadow-md hover:-translate-y-1 cursor-pointer"
      onClick={(e) => { if ((e.target as HTMLElement).closest('.more-square-icon')) return; onView(); }}
    >
      <div className="flex items-center justify-between gap-[6px] mb-[12px] pb-[8px] border-b border-[var(--border-2)]">
        <div className="flex items-center gap-[6px] flex-1 min-w-0">
          <span style={{ width: 28, height: 28, borderRadius: '50%', background: 'var(--primary-soft)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
            <UserIcon style={{ width: 16, color: 'var(--primary)' }} />
          </span>
          <h3 className="text-[var(--text)] text-[14px] font-semibold truncate">{r.user_name || '—'}</h3>
        </div>
        <div className="flex-shrink-0 more-square-icon" style={{ position: 'relative' }}>
          <button
            type="button" aria-label="عملیات" onClick={(e) => { e.stopPropagation(); setMenu((v) => !v); }}
            style={{ display: 'grid', placeItems: 'center', width: 25, height: 25, border: 'none', background: 'none', cursor: 'pointer', color: 'var(--text-3)' }}
          >
            <EllipsisHorizontalIcon style={{ width: 20 }} />
          </button>
          {menu && (
            <>
              <div style={{ position: 'fixed', inset: 0, zIndex: 60 }} onClick={(e) => { e.stopPropagation(); setMenu(false); }} />
              <div style={{ position: 'absolute', top: 28, insetInlineStart: 0, zIndex: 61, minWidth: 130, background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-sm)', boxShadow: 'var(--shadow)', padding: 6, display: 'flex', flexDirection: 'column', gap: 2 }}>
                <button type="button" className="btn sm ghost" style={{ justifyContent: 'flex-start', color: 'var(--primary)' }} onClick={(e) => { e.stopPropagation(); setMenu(false); onView(); }}><EyeIcon style={{ width: 15 }} /> مشاهده</button>
                {canUpdate && (
                  <button type="button" className="btn sm ghost" style={{ justifyContent: 'flex-start', color: 'var(--accent)' }} onClick={(e) => { e.stopPropagation(); setMenu(false); onEdit(); }}><PencilIcon style={{ width: 15 }} /> ویرایش</button>
                )}
              </div>
            </>
          )}
        </div>
      </div>

      <div className="mb-[12px] my-4" style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        <div className="flex items-start justify-between text-[15px]">
          <span className="text-[var(--text-2)] font-medium min-w-[65px]">شماره پرونده:</span>
          <span className="text-[var(--text)] truncate">{r.record_number || '—'}</span>
        </div>
        <div className="flex items-start justify-between text-[15px]">
          <span className="text-[var(--text-2)] font-medium min-w-[65px]">موبایل:</span>
          <span className="text-[var(--text)] truncate" dir="ltr">{r.user_mobile || '—'}</span>
        </div>
      </div>

      <div
        className="flex items-center pt-[8px] justify-end gap-[8px] border-t border-[var(--border-2)]"
        onClick={(e) => e.stopPropagation()}
      >
        <span className="text-[var(--text-2)] text-[14px] min-w-[65px]">برچسب‌ها:</span>
        <div className="flex-1 flex justify-end"><PatientTagsCell record={r} /></div>
      </div>
    </div>
  );
}

/** پرونده‌ها — patient records list. Ported from tauri /files (default card view). */
export default function PatientsListPage() {
  const navigate = useNavigate();
  // مجوزهای منشی؛ برای owner/پزشک همیشه true (usePermissions بدون context آزاد است).
  const { can } = usePermissions();
  const canCreate = can('patients', 'create');
  const canUpdate = can('patients', 'update');
  // وضعیت لیست (جستجو، فیلترها، نما، صفحه) در URL می‌ماند تا «بازگشت» از پرونده،
  // دقیقاً همین نما را برگرداند — نه لیست خام صفحهٔ اول.
  const [urlState, setUrlState] = useUrlState({
    page: '1', search: '', view: 'card',
    gender: '', insurance_id: '', service_status: '', has_debt: '', tags: '',
    admitted_from: '', admitted_to: '',
  });
  const page = pageOf(urlState.page);
  const search = urlState.search;
  const view: 'table' | 'card' = urlState.view === 'table' ? 'table' : 'card';
  const setPage = (p: number) => setUrlState({ page: String(p) });
  const setSearch = (v: string) => setUrlState({ search: v, page: '1' });
  const [filterOpen, setFilterOpen] = useState(false);

  const filters: PatientFilters = useMemo(() => ({
    ...(urlState.gender ? { gender: urlState.gender } : {}),
    ...(urlState.insurance_id ? { insurance_id: urlState.insurance_id } : {}),
    ...(urlState.service_status ? { service_status: urlState.service_status } : {}),
    ...(urlState.has_debt ? { has_debt: true } : {}),
    ...(urlState.tags ? { tags: urlState.tags.split(',') } : {}),
    ...(urlState.admitted_from ? { admitted_from: urlState.admitted_from } : {}),
    ...(urlState.admitted_to ? { admitted_to: urlState.admitted_to } : {}),
  }), [urlState]);

  const setFilters = (f: PatientFilters) => setUrlState({
    gender: f.gender ?? '',
    insurance_id: f.insurance_id ?? '',
    service_status: f.service_status ?? '',
    has_debt: f.has_debt ? '1' : '',
    tags: f.tags?.join(',') ?? '',
    admitted_from: f.admitted_from ?? '',
    admitted_to: f.admitted_to ?? '',
    page: '1',
  });

  const pageSize = view === 'card' ? CARD_PAGE_SIZE : TABLE_PAGE_SIZE;
  const switchView = (v: 'table' | 'card') => setUrlState({ view: v, page: '1' });

  const qs = new URLSearchParams({ page: String(page), limit: String(pageSize) });
  if (search) qs.set('search', search);
  if (filters.gender)         qs.set('gender', filters.gender);
  if (filters.insurance_id)   qs.set('insurance_id', filters.insurance_id);
  if (filters.service_status) qs.set('service_status', filters.service_status);
  if (filters.has_debt)       qs.set('has_debt', '1');
  if (filters.tags?.length)   qs.set('tags', filters.tags.join(','));
  const af = dayBound(filters.admitted_from, false);
  const at = dayBound(filters.admitted_to, true);
  if (af) qs.set('admitted_from', String(af));
  if (at) qs.set('admitted_to', String(at));

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

  const activeFilters = countFilters(filters);
  const records = data?.data ?? EMPTY;
  const total   = data?.meta?.totalRecords ?? 0;

  const editHref = (r: PatientRecord) => `/admin/patients/${r.uuid}/edit`;
  const viewHref = (r: PatientRecord) => `/admin/patients/${r.uuid}`;

  // نمایش جدولی/کارتی — دو دکمه با آیکون SVG سفارشی (عین tauri ViewModeToggle).
  const viewToggle = (
    <div className="flex border border-[var(--border-2)] rounded-[4px] overflow-hidden shrink-0">
      <button type="button" aria-label="نمایش جدولی" onClick={() => switchView('table')} style={{ padding: 8, border: 'none', cursor: 'pointer', display: 'grid', placeItems: 'center', background: view === 'table' ? 'var(--primary-soft)' : 'transparent' }}>
        <PatientsGridView color={view === 'table' ? 'var(--primary)' : 'var(--text-2)'} />
      </button>
      <button type="button" aria-label="نمایش کارتی" onClick={() => switchView('card')} style={{ padding: 8, border: 'none', cursor: 'pointer', display: 'grid', placeItems: 'center', background: view === 'card' ? 'var(--primary-soft)' : 'transparent' }}>
        <PatientsCategoryView color={view === 'card' ? 'var(--primary)' : 'var(--text-2)'} />
      </button>
    </div>
  );

  return (
    <div className="fade-in">
      {/* Head — تیتر تنها (tauri files/head) */}
      <p className="text-[var(--text)] text-[16px] md:text-[18px] lg:text-[20px] font-bold">پرونده‌ها</p>

      {/* Inputs — ردیف کنترل‌ها (tauri files/inputs) */}
      <div className="my-[16px] md:my-[20px] lg:my-[24px]">
        <div className="flex flex-col lg:flex-row items-stretch lg:items-center gap-[16px] lg:gap-[20px]">
          {/* جستجو + سوییچ نما */}
          <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-3 flex-1 w-full">
            <div className="w-full md:w-[442px]">
              <div className="flex items-center rounded-[6px] border border-[var(--border)] bg-[var(--bg)]" style={{ height: 48, paddingInline: 4 }}>
                <input
                  dir="rtl"
                  value={search}
                  onChange={(e) => { setSearch(e.target.value); setPage(1); }}
                  placeholder="کد ملی، شماره پرونده یا نام مراجعه کننده را وارد کنید..."
                  className="text-[var(--text)]"
                  style={{ flex: 1, minWidth: 0, background: 'transparent', border: 'none', outline: 'none', fontSize: 13, textAlign: 'left' }}
                />
                <span style={{ width: 40, height: 40, marginInlineEnd: -4, flexShrink: 0, borderRadius: 6, background: 'var(--primary)', display: 'grid', placeItems: 'center' }}>
                  <SearchHeaderP color="white" />
                </span>
              </div>
            </div>
            {viewToggle}
          </div>

          {/* فیلتر + تشکیل پرونده */}
          <div className="flex items-center w-full lg:w-auto justify-between lg:justify-end" style={{ gap: 12 }}>
            <button
              type="button" aria-label="فیلترها" onClick={() => setFilterOpen(true)}
              className="flex items-center justify-center rounded-[4px] cursor-pointer"
              style={{ width: 62, height: 48, border: '1px solid var(--primary)', background: 'transparent', position: 'relative' }}
            >
              <TurnsFilter color="var(--primary)" />
              {activeFilters > 0 && (
                <span style={{ position: 'absolute', top: -6, insetInlineEnd: -6, minWidth: 16, height: 16, padding: '0 4px', borderRadius: 999, background: 'var(--primary)', color: 'var(--on-primary)', fontSize: 10, display: 'grid', placeItems: 'center' }}>{formatNumber(activeFilters)}</span>
              )}
            </button>
            {canCreate && (
              <button
                type="button" onClick={() => navigate('/admin/patients/new')}
                className="flex items-center justify-center gap-2 rounded-[4px] cursor-pointer"
                style={{ height: 48, minWidth: 137, background: 'var(--primary)', border: 'none', padding: '0 16px' }}
              >
                <AddTurn color="var(--on-primary)" />
                <span style={{ color: 'var(--on-primary)', fontSize: 14 }}>تشکیل پرونده</span>
              </button>
            )}
          </div>
        </div>
      </div>

      {isLoading ? (
        <div style={{ padding: 24, color: 'var(--text-3)', fontSize: 13 }}>در حال بارگذاری...</div>
      ) : error ? (
        /* «دسترسی ندارید» با «بیماری یافت نشد» یکی نیست — پیام سرور را نشان بده. */
        <div className="card" style={{ padding: '60px 0', textAlign: 'center' }}>
          <IdentificationIcon style={{ width: 52, margin: '0 auto 14px', display: 'block', opacity: 0.3, color: 'var(--danger)' }} />
          <div style={{ fontSize: 14, color: 'var(--danger)' }}>
            {(error as any)?.message || 'دسترسی به پرونده‌ها امکان‌پذیر نیست'}
          </div>
          <div style={{ fontSize: 13, color: 'var(--text-3)', marginTop: 8 }}>
            اگر به‌تازگی محیط کاری‌تان تغییر کرده، از منوی بالا محیط درست را انتخاب کنید.
          </div>
        </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) * pageSize + 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' }}>
                    <PatientTagsCell record={r} />
                  </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>
                      {canUpdate && (
                        <Link to={editHref(r)} aria-label="ویرایش" style={{ color: 'var(--accent)' }}><PencilIcon style={{ width: 18 }} /></Link>
                      )}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-[12px] mt-[16px]">
          {records.map((r) => (
            <PatientCard key={r.uuid} r={r} onView={() => navigate(viewHref(r))} onEdit={() => navigate(editHref(r))} canUpdate={canUpdate} />
          ))}
        </div>
      )}

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

      <PatientsFilterModal
        open={filterOpen}
        value={filters}
        onClose={() => setFilterOpen(false)}
        onApply={(f) => { setFilters(f); setPage(1); setFilterOpen(false); }}
      />
    </div>
  );
}
