import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { PlusIcon, PencilIcon, TrashIcon, TagIcon } from '@heroicons/react/24/outline';
import { toast } from 'sonner';
import { api } from '../lib/api';
import type { ApiResponse } from '../lib/api';
import Modal from '../components/ui/Modal';
import ConfirmDialog from '../components/ui/ConfirmDialog';
import SettingsLayout from '../components/layout/SettingsLayout';
import { usePermissions } from '../hooks/usePermissions';

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

const schema = z.object({
  name:   z.string().min(1, 'نام برچسب الزامی است'),
  color:  z.string().regex(/^#([0-9a-fA-F]{6})$/, 'رنگ نامعتبر است'),
  active: z.boolean(),
});
type Form = z.infer<typeof schema>;

/** Preset swatches — mirrors the tauri AddPurchaseSubTabModal palette. */
const TAG_COLORS = ['#d61600', '#0088ff', '#ffa200', '#7cc985'];
const DEFAULTS: Form = { name: '', color: TAG_COLORS[0], active: true };

const EMPTY: TenantTag[] = [];

/** برچسب‌ها — per-tenant tag management inside the settings shell. */
export default function TagsSettingsPage() {
  const qc = useQueryClient();
  // مجوزهای منشی؛ برای owner/پزشک همیشه true (usePermissions بدون context آزاد است).
  const { can } = usePermissions();
  const canCreate = can('tags', 'create');
  const canUpdate = can('tags', 'update');
  const canDelete = can('tags', 'delete');
  const [modal, setModal] = useState<'create' | TenantTag | null>(null);
  const [deleteTarget, setDeleteTarget] = useState<TenantTag | null>(null);

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

  const form = useForm<Form>({ resolver: zodResolver(schema), defaultValues: DEFAULTS });

  const invalidate = () => qc.invalidateQueries({ queryKey: ['tenant-tags'] });

  const createTag = useMutation({
    mutationFn: (d: Form) => api.post('/api/v1/tenant-tag', d),
    onSuccess: () => { invalidate(); setModal(null); form.reset(DEFAULTS); toast.success('برچسب ایجاد شد'); },
    onError: (e: any) => toast.error(e.message),
  });
  const editTag = useMutation({
    mutationFn: ({ uuid, d }: { uuid: string; d: Form }) => api.patch(`/api/v1/tenant-tag/${uuid}`, d),
    onSuccess: () => { invalidate(); setModal(null); toast.success('برچسب ویرایش شد'); },
    onError: (e: any) => toast.error(e.message),
  });
  const delTag = useMutation({
    mutationFn: (uuid: string) => api.delete(`/api/v1/tenant-tag/${uuid}`),
    onSuccess: () => { invalidate(); setDeleteTarget(null); toast.success('برچسب حذف شد'); },
    onError: (e: any) => { toast.error(e.message); setDeleteTarget(null); },
  });

  const openCreate = () => { form.reset(DEFAULTS); setModal('create'); };
  const openEdit = (t: TenantTag) => { form.reset({ name: t.name, color: t.color, active: t.active }); setModal(t); };

  return (
    <SettingsLayout active="tags">
      <div className="fade-in">
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16, gap: 12, flexWrap: 'wrap' }}>
          <h1 className="section-title">برچسب‌ها</h1>
          {canCreate && (
            <button className="btn primary" onClick={openCreate}><PlusIcon style={{ width: 16 }} /> برچسب جدید</button>
          )}
        </div>

        {isLoading ? (
          <div style={{ padding: 16, color: 'var(--text-3)', fontSize: 13 }}>در حال بارگذاری...</div>
        ) : tags.length === 0 ? (
          <div className="card" style={{ padding: '56px 0', textAlign: 'center', color: 'var(--text-3)' }}>
            <TagIcon style={{ width: 48, margin: '0 auto 14px', display: 'block', opacity: 0.3 }} />
            <div style={{ fontSize: 14, color: 'var(--text-2)' }}>هنوز برچسبی ثبت نشده است.</div>
          </div>
        ) : (
          <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', overflow: 'hidden' }}>
            {tags.map((t, i) => (
              <div key={t.uuid} style={{
                display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px',
                borderTop: i === 0 ? 'none' : '1px solid var(--border)', opacity: t.active ? 1 : 0.55,
              }}>
                <span style={{ width: 14, height: 14, borderRadius: '50%', background: t.color, flexShrink: 0, border: '1px solid var(--border)' }} />
                <span style={{ flex: 1, fontWeight: 600, fontSize: 14 }}>{t.name}</span>
                <span className={`badge ${t.active ? 'green' : 'gray'}`} style={{ fontSize: 11 }}><span className="bdot" />{t.active ? 'فعال' : 'غیرفعال'}</span>
                {canUpdate && (
                  <button className="btn sm ghost" aria-label="ویرایش" onClick={() => openEdit(t)} style={{ color: 'var(--text-2)' }}><PencilIcon style={{ width: 15 }} /></button>
                )}
                {canDelete && (
                  <button className="btn sm ghost" aria-label="حذف" onClick={() => setDeleteTarget(t)} style={{ color: 'var(--danger)' }}><TrashIcon style={{ width: 15 }} /></button>
                )}
              </div>
            ))}
          </div>
        )}
      </div>

      <Modal open={modal !== null} onClose={() => setModal(null)} title={modal === 'create' ? 'افزودن برچسب جدید' : 'ویرایش برچسب'}>
        <form onSubmit={form.handleSubmit((d) => {
          if (modal === 'create') createTag.mutate(d);
          else if (modal && typeof modal === 'object') editTag.mutate({ uuid: modal.uuid, d });
        })} style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
          <div>
            <label className="field-label">نام برچسب</label>
            <div className="field"><input {...form.register('name')} placeholder="نام برچسب را وارد کنید" autoFocus /></div>
            {form.formState.errors.name && <span className="field-error">{form.formState.errors.name.message}</span>}
          </div>

          <div>
            <label className="field-label" style={{ fontWeight: 700 }}>رنگ برچسب</label>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              {TAG_COLORS.map((c) => {
                const selected = form.watch('color') === c;
                return (
                  <button
                    key={c}
                    type="button"
                    aria-label={`رنگ ${c}`}
                    aria-pressed={selected}
                    onClick={() => form.setValue('color', c)}
                    style={{
                      width: 28, height: 28, borderRadius: '50%', background: c, cursor: 'pointer', padding: 0,
                      border: selected ? '2px solid var(--text)' : '1px solid var(--border)',
                    }}
                  />
                );
              })}
            </div>
          </div>

          <div>
            <label className="field-label" style={{ fontWeight: 700 }}>وضعیت برچسب</label>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <label className="switch" title="وضعیت برچسب">
                <input type="checkbox" checked={form.watch('active')} onChange={(e) => form.setValue('active', e.target.checked)} aria-label="وضعیت برچسب" />
                <span className="switch-track"><span className="switch-thumb" /></span>
              </label>
              <span style={{ fontSize: 14, color: 'var(--text-2)' }}>{form.watch('active') ? 'فعال' : 'غیرفعال'}</span>
            </div>
          </div>

          <button type="submit" className="btn primary" style={{ width: '100%', justifyContent: 'center', height: 46 }} disabled={createTag.isPending || editTag.isPending}>
            {modal === 'create' ? 'ثبت برچسب' : 'ذخیره تغییرات'}
          </button>
        </form>
      </Modal>

      <ConfirmDialog
        open={!!deleteTarget}
        title="حذف برچسب"
        message={`آیا از حذف برچسب «${deleteTarget?.name}» مطمئن هستید؟`}
        confirmLabel="حذف"
        onConfirm={() => deleteTarget && delTag.mutate(deleteTarget.uuid)}
        onCancel={() => setDeleteTarget(null)}
        loading={delTag.isPending}
      />
    </SettingsLayout>
  );
}
