import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { TrashIcon, PencilIcon } from '@heroicons/react/24/outline';
import { useForm, Controller } from 'react-hook-form';
import { toast } from 'sonner';
import { api } from '../lib/api';
import type { ApiResponse, PaginatedResponse } from '../lib/api';
import type { Secretary, SecretaryPermissions } from '../types';
import { formatDate, maskMobile } from '../lib/utils';
import PageHeader from '../components/ui/PageHeader';
import DataTable, { Column } from '../components/ui/DataTable';
import { ActiveBadge } from '../components/ui/StatusBadge';
import Pagination from '../components/ui/Pagination';
import ConfirmDialog from '../components/ui/ConfirmDialog';
import Modal from '../components/ui/Modal';

const DEFAULT_PERMISSIONS: SecretaryPermissions = {
  appointments: { view: true, create: false, cancel: false, update_status: false },
  addresses: { view: true, create: false, update: false, delete: false },
  clinic_info: { view: true, update: false },
  insurances: { view: true, create: false, update: false, delete: false },
};

type PermSection = keyof SecretaryPermissions;
type PermAction = string;

const PERMISSION_LABELS: Record<PermSection, { label: string; actions: { key: string; label: string }[] }> = {
  appointments: {
    label: 'نوبت‌ها',
    actions: [
      { key: 'view', label: 'مشاهده' },
      { key: 'create', label: 'ایجاد' },
      { key: 'cancel', label: 'لغو' },
      { key: 'update_status', label: 'تغییر وضعیت' },
    ],
  },
  addresses: {
    label: 'آدرس‌ها',
    actions: [
      { key: 'view', label: 'مشاهده' },
      { key: 'create', label: 'ایجاد' },
      { key: 'update', label: 'ویرایش' },
      { key: 'delete', label: 'حذف' },
    ],
  },
  clinic_info: {
    label: 'اطلاعات کلینیک',
    actions: [
      { key: 'view', label: 'مشاهده' },
      { key: 'update', label: 'ویرایش' },
    ],
  },
  insurances: {
    label: 'بیمه‌ها',
    actions: [
      { key: 'view', label: 'مشاهده' },
      { key: 'create', label: 'ایجاد' },
      { key: 'update', label: 'ویرایش' },
      { key: 'delete', label: 'حذف' },
    ],
  },
};

function PermissionsMatrix({
  permissions,
  onChange,
}: {
  permissions: SecretaryPermissions;
  onChange: (p: SecretaryPermissions) => void;
}) {
  const toggle = (section: PermSection, action: string) => {
    const current = (permissions[section] as Record<string, boolean>)[action];
    onChange({
      ...permissions,
      [section]: { ...(permissions[section] as Record<string, boolean>), [action]: !current },
    });
  };

  return (
    <div className="overflow-x-auto">
      <table className="w-full text-sm">
        <thead>
          <tr className="text-right">
            <th className="pb-2 text-gray-500 font-medium">بخش</th>
            {['مشاهده', 'ایجاد', 'ویرایش', 'حذف', 'لغو', 'تغییر وضعیت'].map((h) => (
              <th key={h} className="pb-2 text-gray-500 font-medium text-center text-xs">{h}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {(Object.keys(PERMISSION_LABELS) as PermSection[]).map((section) => {
            const config = PERMISSION_LABELS[section];
            const sectionPerms = permissions[section] as Record<string, boolean>;
            const allActions = ['view', 'create', 'update', 'delete', 'cancel', 'update_status'];
            return (
              <tr key={section} className="border-t border-gray-100">
                <td className="py-3 pr-0 text-gray-700 font-medium">{config.label}</td>
                {allActions.map((action) => {
                  const actionConfig = config.actions.find((a) => a.key === action);
                  if (!actionConfig) {
                    return <td key={action} className="text-center text-gray-200">—</td>;
                  }
                  return (
                    <td key={action} className="text-center py-3">
                      <input
                        type="checkbox"
                        checked={sectionPerms[action] ?? false}
                        onChange={() => toggle(section, action)}
                        className="w-4 h-4 accent-primary-600 cursor-pointer"
                      />
                    </td>
                  );
                })}
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

export default function SecretariesPage() {
  const qc = useQueryClient();
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState('');
  const [editTarget, setEditTarget] = useState<Secretary | null>(null);
  const [editPerms, setEditPerms] = useState<SecretaryPermissions>(DEFAULT_PERMISSIONS);
  const [deleteTarget, setDeleteTarget] = useState<Secretary | null>(null);
  const limit = 15;

  const { data, isLoading } = useQuery({
    queryKey: ['secretaries', page, search],
    queryFn: () => {
      const params = new URLSearchParams({ page: String(page), limit: String(limit) });
      if (search) params.set('search', search);
      return api.get<PaginatedResponse<Secretary>>(`/api/v1/admin/secretaries?${params}`);
    },
  });

  const updatePermsMutation = useMutation({
    mutationFn: ({ uuid, permissions }: { uuid: string; permissions: SecretaryPermissions }) =>
      api.patch<ApiResponse<null>>(`/api/v1/secretary/${uuid}`, { permissions }),
    onSuccess: () => {
      toast.success('دسترسی‌ها بروزرسانی شد');
      setEditTarget(null);
      qc.invalidateQueries({ queryKey: ['secretaries'] });
    },
    onError: (err: Error) => toast.error(err.message),
  });

  const deleteMutation = useMutation({
    mutationFn: (s: Secretary) => api.delete<ApiResponse<null>>(`/api/v1/secretary/${s.uuid}`),
    onSuccess: () => {
      toast.success('منشی حذف شد');
      setDeleteTarget(null);
      qc.invalidateQueries({ queryKey: ['secretaries'] });
    },
    onError: (err: Error) => toast.error(err.message),
  });

  const openEdit = (s: Secretary) => {
    setEditTarget(s);
    setEditPerms(s.permissions ?? DEFAULT_PERMISSIONS);
  };

  const columns: Column<Secretary>[] = [
    {
      key: 'user_name',
      header: 'نام',
      render: (s) => <span className="font-medium text-gray-900">{s.user_name}</span>,
    },
    {
      key: 'mobile_number',
      header: 'موبایل',
      render: (s) => <span dir="ltr">{maskMobile(s.mobile_number)}</span>,
    },
    { key: 'doctor_name', header: 'پزشک', render: (s) => `دکتر ${s.doctor_name}` },
    { key: 'is_active', header: 'وضعیت', render: (s) => <ActiveBadge active={s.is_active} /> },
    { key: 'created_at', header: 'تاریخ ثبت', render: (s) => formatDate(s.created_at) },
  ];

  const items = data?.data ?? [];
  const total = data?.meta?.totalRecords ?? 0;

  return (
    <div>
      <PageHeader
        title="منشی‌ها"
        breadcrumbs={[{ label: 'داشبورد', to: '/admin/dashboard' }, { label: 'منشی‌ها' }]}
      />

      <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
        <DataTable<Secretary>
          columns={columns}
          data={items}
          loading={isLoading}
          searchValue={search}
          onSearchChange={(v) => { setSearch(v); setPage(1); }}
          searchPlaceholder="جستجو بر اساس نام یا پزشک..."
          emptyMessage="هیچ منشی‌ای یافت نشد"
          actions={(sec) => (
            <>
              <button onClick={() => openEdit(sec)}
                className="p-1.5 text-gray-400 hover:text-primary-600 hover:bg-primary-50 rounded-lg transition-colors" title="ویرایش دسترسی‌ها">
                <PencilIcon className="w-4 h-4" />
              </button>
              <button onClick={() => setDeleteTarget(sec)}
                className="p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors" title="حذف">
                <TrashIcon className="w-4 h-4" />
              </button>
            </>
          )}
        />
        <Pagination page={page} total={total} limit={limit} onPageChange={setPage} />
      </div>

      <Modal
        open={!!editTarget}
        title={`دسترسی‌های ${editTarget?.user_name}`}
        size="lg"
        onClose={() => setEditTarget(null)}
        footer={
          <>
            <button onClick={() => setEditTarget(null)}
              className="px-4 py-2 border border-gray-300 text-sm text-gray-700 rounded-[10px] hover:bg-gray-50 transition-colors">
              لغو
            </button>
            <button
              onClick={() => editTarget && updatePermsMutation.mutate({ uuid: editTarget.uuid, permissions: editPerms })}
              disabled={updatePermsMutation.isPending}
              className="px-4 py-2 bg-primary-600 text-white text-sm rounded-[10px] hover:bg-primary-700 disabled:opacity-50 transition-colors">
              {updatePermsMutation.isPending ? 'در حال ذخیره...' : 'ذخیره دسترسی‌ها'}
            </button>
          </>
        }
      >
        <PermissionsMatrix permissions={editPerms} onChange={setEditPerms} />
      </Modal>

      <ConfirmDialog
        open={!!deleteTarget}
        title="حذف منشی"
        message={`آیا از حذف منشی "${deleteTarget?.user_name}" اطمینان دارید؟`}
        confirmLabel="حذف"
        danger
        loading={deleteMutation.isPending}
        onConfirm={() => deleteTarget && deleteMutation.mutate(deleteTarget)}
        onCancel={() => setDeleteTarget(null)}
      />
    </div>
  );
}
