import React, { useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import { api } from '../lib/api';
import type { ApiResponse } from '../lib/api';
import { Cog6ToothIcon, CheckCircleIcon } from '@heroicons/react/24/outline';

// ── Schema ────────────────────────────────────────────────────────────────

const schema = z.object({
  site_name:                  z.string().min(1, 'نام سایت الزامی است'),
  support_phone:              z.string(),
  commission_enabled:         z.string(),
  commission_percent:         z.string().refine(v => {
    const n = Number(v);
    return !isNaN(n) && n >= 0 && n <= 100;
  }, 'درصد باید بین ۰ تا ۱۰۰ باشد'),
  max_cancel_hours_before:    z.string(),
  appointment_reminder_hours: z.string(),
});

type FormValues = z.infer<typeof schema>;

interface Settings {
  site_name: string;
  support_phone: string;
  commission_enabled: string;
  commission_percent: string;
  max_cancel_hours_before: string;
  appointment_reminder_hours: string;
}

// ── Component ─────────────────────────────────────────────────────────────

export default function SettingsPage() {
  const qc = useQueryClient();

  const { data, isLoading } = useQuery({
    queryKey: ['admin-settings'],
    queryFn: () => api.get<ApiResponse<Settings>>('/api/v1/admin/settings'),
    staleTime: 30_000,
  });

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const settings: Settings | undefined = (data?.data as any)?.data ?? data?.data;

  const {
    register,
    handleSubmit,
    reset,
    watch,
    formState: { errors, isDirty },
  } = useForm<FormValues>({ resolver: zodResolver(schema) });

  useEffect(() => {
    if (settings) {
      reset({
        site_name:                  settings.site_name ?? 'ClinicPro',
        support_phone:              settings.support_phone ?? '',
        commission_enabled:         settings.commission_enabled ?? '0',
        commission_percent:         settings.commission_percent ?? '0',
        max_cancel_hours_before:    settings.max_cancel_hours_before ?? '24',
        appointment_reminder_hours: settings.appointment_reminder_hours ?? '2',
      });
    }
  }, [settings, reset]);

  const mutation = useMutation({
    mutationFn: (values: FormValues) =>
      api.patch<ApiResponse<Settings>>('/api/v1/admin/settings', values),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['admin-settings'] });
    },
  });

  const commissionEnabled = watch('commission_enabled') === '1';

  const onSubmit = (values: FormValues) => {
    mutation.mutate(values);
  };

  if (isLoading) {
    return (
      <div className="fade-in">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--gap)' }}>
          {Array.from({ length: 3 }).map((_, i) => (
            <div key={i} className="card card-pad">
              <div className="skeleton" style={{ height: 200, borderRadius: 'var(--r)' }} />
            </div>
          ))}
        </div>
      </div>
    );
  }

  return (
    <div className="fade-in">
      <div className="card-title-row" style={{ marginBottom: 'var(--gap)' }}>
        <div>
          <h1 className="section-title">تنظیمات سایت</h1>
          <div className="muted" style={{ fontSize: 13, marginTop: 3 }}>پیکربندی کلی پلتفرم</div>
        </div>
        {mutation.isSuccess && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: 'var(--success)', fontSize: 13.5 }}>
            <CheckCircleIcon style={{ width: 18, height: 18 }} />
            تنظیمات ذخیره شد
          </div>
        )}
      </div>

      <form onSubmit={handleSubmit(onSubmit)}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--gap)' }}>

          {/* اطلاعات پایه */}
          <div className="card card-pad">
            <div className="card-title-row" style={{ marginBottom: '1.25rem' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <div className="ico" style={{ background: 'var(--primary-soft)', color: 'var(--primary)', width: 36, height: 36, borderRadius: 10 }}>
                  <Cog6ToothIcon style={{ width: 18, height: 18 }} />
                </div>
                <h3 style={{ fontSize: 15 }}>اطلاعات پایه</h3>
              </div>
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem' }}>
              <div>
                <label style={{ fontSize: 13, fontWeight: 500, display: 'block', marginBottom: 6 }}>نام سایت</label>
                <input
                  {...register('site_name')}
                  style={{
                    width: '100%', height: 38, padding: '0 12px', borderRadius: 'var(--r-sm)',
                    border: `1px solid ${errors.site_name ? 'var(--danger)' : 'var(--border)'}`,
                    background: 'var(--surface)', color: 'var(--text)', fontSize: 13.5,
                    boxSizing: 'border-box',
                  }}
                />
                {errors.site_name && <p style={{ color: 'var(--danger)', fontSize: 12, marginTop: 4 }}>{errors.site_name.message}</p>}
              </div>

              <div>
                <label style={{ fontSize: 13, fontWeight: 500, display: 'block', marginBottom: 6 }}>شماره پشتیبانی</label>
                <input
                  {...register('support_phone')}
                  dir="ltr"
                  placeholder="021-12345678"
                  style={{
                    width: '100%', height: 38, padding: '0 12px', borderRadius: 'var(--r-sm)',
                    border: '1px solid var(--border)', background: 'var(--surface)', color: 'var(--text)', fontSize: 13.5,
                    boxSizing: 'border-box',
                  }}
                />
              </div>
            </div>
          </div>

          {/* تنظیمات کمیسیون */}
          <div className="card card-pad">
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: '1.25rem' }}>
              <div className="ico" style={{ background: 'var(--success-bg)', color: 'var(--success)', width: 36, height: 36, borderRadius: 10 }}>
                <span style={{ fontSize: 18 }}>٪</span>
              </div>
              <h3 style={{ fontSize: 15 }}>کمیسیون سایت</h3>
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
              {/* toggle فعال/غیرفعال */}
              <label style={{ display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer' }}>
                <div style={{ position: 'relative', width: 44, height: 24, flexShrink: 0 }}>
                  <input
                    type="checkbox"
                    checked={commissionEnabled}
                    onChange={(e) => {
                      const target = e.target;
                      const input = document.querySelector<HTMLInputElement>('input[name="commission_enabled"]');
                      if (input) {
                        input.value = target.checked ? '1' : '0';
                        // Trigger react-hook-form change
                        input.dispatchEvent(new Event('input', { bubbles: true }));
                      }
                    }}
                    style={{ opacity: 0, width: 0, height: 0, position: 'absolute' }}
                  />
                  <input type="hidden" {...register('commission_enabled')} />
                  <div style={{
                    width: 44, height: 24, borderRadius: 12,
                    background: commissionEnabled ? 'var(--primary)' : 'var(--border)',
                    transition: 'background .2s', position: 'relative',
                  }}>
                    <div style={{
                      position: 'absolute', top: 2, width: 20, height: 20, borderRadius: '50%', background: '#fff',
                      transition: 'right .2s', right: commissionEnabled ? 2 : 22,
                      boxShadow: '0 1px 3px rgba(0,0,0,.2)',
                    }} />
                  </div>
                </div>
                <span style={{ fontSize: 14 }}>
                  {commissionEnabled ? 'کمیسیون فعال است' : 'کمیسیون غیرفعال است'}
                </span>
              </label>

              {commissionEnabled && (
                <div style={{ maxWidth: 280 }}>
                  <label style={{ fontSize: 13, fontWeight: 500, display: 'block', marginBottom: 6 }}>
                    درصد کمیسیون از کاربر (۰–۱۰۰)
                  </label>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <input
                      {...register('commission_percent')}
                      type="number"
                      min={0}
                      max={100}
                      style={{
                        width: 120, height: 38, padding: '0 12px', borderRadius: 'var(--r-sm)',
                        border: `1px solid ${errors.commission_percent ? 'var(--danger)' : 'var(--border)'}`,
                        background: 'var(--surface)', color: 'var(--text)', fontSize: 13.5,
                        boxSizing: 'border-box',
                      }}
                    />
                    <span className="muted" style={{ fontSize: 13 }}>درصد</span>
                  </div>
                  {errors.commission_percent && (
                    <p style={{ color: 'var(--danger)', fontSize: 12, marginTop: 4 }}>{errors.commission_percent.message}</p>
                  )}
                  <p className="muted" style={{ fontSize: 12, marginTop: 8 }}>
                    کمیسیون فقط از کاربر دریافت می‌شود. منشی‌ها کمیسیون ندارند.
                  </p>
                </div>
              )}
            </div>
          </div>

          {/* تنظیمات نوبت‌دهی */}
          <div className="card card-pad">
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: '1.25rem' }}>
              <div className="ico" style={{ background: 'var(--warning-bg)', color: 'var(--warning)', width: 36, height: 36, borderRadius: 10 }}>
                <span style={{ fontSize: 16 }}>⏱</span>
              </div>
              <h3 style={{ fontSize: 15 }}>تنظیمات نوبت‌دهی</h3>
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem' }}>
              <div>
                <label style={{ fontSize: 13, fontWeight: 500, display: 'block', marginBottom: 6 }}>
                  حداکثر ساعت مجاز برای لغو نوبت
                </label>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <input
                    {...register('max_cancel_hours_before')}
                    type="number"
                    min={0}
                    style={{
                      width: 100, height: 38, padding: '0 12px', borderRadius: 'var(--r-sm)',
                      border: '1px solid var(--border)', background: 'var(--surface)', color: 'var(--text)', fontSize: 13.5,
                      boxSizing: 'border-box',
                    }}
                  />
                  <span className="muted" style={{ fontSize: 13 }}>ساعت قبل از نوبت</span>
                </div>
              </div>

              <div>
                <label style={{ fontSize: 13, fontWeight: 500, display: 'block', marginBottom: 6 }}>
                  ارسال یادآور قبل از نوبت
                </label>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <input
                    {...register('appointment_reminder_hours')}
                    type="number"
                    min={0}
                    style={{
                      width: 100, height: 38, padding: '0 12px', borderRadius: 'var(--r-sm)',
                      border: '1px solid var(--border)', background: 'var(--surface)', color: 'var(--text)', fontSize: 13.5,
                      boxSizing: 'border-box',
                    }}
                  />
                  <span className="muted" style={{ fontSize: 13 }}>ساعت قبل از نوبت</span>
                </div>
              </div>
            </div>
          </div>

          {/* دکمه ذخیره */}
          <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
            <button
              type="button"
              className="btn ghost"
              onClick={() => settings && reset({
                site_name:                  settings.site_name,
                support_phone:              settings.support_phone,
                commission_enabled:         settings.commission_enabled,
                commission_percent:         settings.commission_percent,
                max_cancel_hours_before:    settings.max_cancel_hours_before,
                appointment_reminder_hours: settings.appointment_reminder_hours,
              })}
              disabled={!isDirty || mutation.isPending}
            >
              بازگشت
            </button>
            <button
              type="submit"
              className="btn primary"
              disabled={mutation.isPending || !isDirty}
            >
              {mutation.isPending ? 'در حال ذخیره...' : 'ذخیره تنظیمات'}
            </button>
          </div>

        </div>
      </form>
    </div>
  );
}
