'use client';

import {
  useCallback,
  useEffect,
  useRef,
  useState,
} from 'react';
import {
  Bold,
  Building2,
  GraduationCap,
  Italic,
  List,
  ListOrdered,
  Minus,
  Send,
  Underline,
  Users,
} from 'lucide-react';
import { apiFetchJson } from '@/lib/auth';
import { useBranches } from '@/lib/hooks/use-branches';
import { useSearchParams } from 'next/navigation';
import { PageHeader } from '@/components/school/page-header';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { SelectNative } from '@/components/ui/select-native';
import { useToast } from '@/components/school/toast-context';
import { cn } from '@/lib/utils';

/* ─── Tipler ──────────────────────────────────────────────────────────────── */

type ClassroomOpt = { id: string; name: string; branchName?: string };
type TargetType = 'PARENTS_CLASSROOM' | 'TEACHERS' | 'ALL_PARENTS';

interface TargetOption {
  value: TargetType;
  icon: React.ComponentType<{ className?: string }>;
  label: string;
  description: string;
  colorClass: string;
  activeBg: string;
  activeBorder: string;
  activeIcon: string;
  activeDot: string;
}

const TARGET_OPTIONS: TargetOption[] = [
  {
    value: 'PARENTS_CLASSROOM',
    icon: Users,
    label: 'Sınıf Velileri',
    description: 'Seçilen sınıftaki öğrencilerin velilerine gönderilir',
    colorClass: 'text-brand-700',
    activeBg: 'bg-brand-50',
    activeBorder: 'border-brand-400',
    activeIcon: 'text-brand-600',
    activeDot: 'bg-brand-500',
  },
  {
    value: 'TEACHERS',
    icon: GraduationCap,
    label: 'Öğretmenler',
    description: 'Okulda kayıtlı tüm aktif öğretmenlere iletilir',
    colorClass: 'text-violet-700',
    activeBg: 'bg-violet-50',
    activeBorder: 'border-violet-400',
    activeIcon: 'text-violet-600',
    activeDot: 'bg-violet-500',
  },
  {
    value: 'ALL_PARENTS',
    icon: Building2,
    label: 'Tüm Okul',
    description: 'Bütün öğrencilerin velilerine toplu gönderim yapılır',
    colorClass: 'text-amber-700',
    activeBg: 'bg-amber-50',
    activeBorder: 'border-amber-400',
    activeIcon: 'text-amber-600',
    activeDot: 'bg-amber-500',
  },
];

/* ─── Editör araç çubuğu ─────────────────────────────────────────────────── */

interface ToolbarButtonProps {
  onClick: () => void;
  title: string;
  children: React.ReactNode;
  active?: boolean;
}

function ToolbarButton({ onClick, title, children, active }: ToolbarButtonProps) {
  return (
    <button
      type="button"
      title={title}
      onMouseDown={(e) => {
        e.preventDefault();
        onClick();
      }}
      className={cn(
        'inline-flex h-7 w-7 items-center justify-center rounded transition-colors',
        active
          ? 'bg-zinc-900 text-white dark:bg-white dark:text-zinc-900'
          : 'text-zinc-500 hover:bg-zinc-100 hover:text-zinc-800 dark:text-zinc-400 dark:hover:bg-zinc-800 dark:hover:text-zinc-200',
      )}
    >
      {children}
    </button>
  );
}

/* ─── Sayfa bileşeni ─────────────────────────────────────────────────────── */

export default function SchoolNotificationsPage() {
  const { toast } = useToast();
  const searchParams = useSearchParams();
  const branchId = searchParams.get('branchId') ?? 'all';
  const { branches } = useBranches();

  /* State */
  const [classrooms, setClassrooms] = useState<ClassroomOpt[]>([]);
  const [target, setTarget] = useState<TargetType>('ALL_PARENTS');
  const [classroomId, setClassroomId] = useState('');
  const [notifBranchId, setNotifBranchId] = useState('');
  const [title, setTitle] = useState('');
  const [sending, setSending] = useState(false);

  /* Editör ref */
  const editorRef = useRef<HTMLDivElement>(null);

  /* Sınıfları yükle (şubeye göre filtreli) */
  useEffect(() => {
    setClassroomId('');
    const q = new URLSearchParams({ limit: '200' });
    if (branchId !== 'all') q.set('branchId', branchId);
    apiFetchJson<ClassroomOpt[]>(`/v1/admin/classrooms?${q.toString()}`).then((res) => {
      setClassrooms(Array.isArray(res.data) ? res.data : []);
    });
  }, [branchId]);

  /* Hedef değişince sınıf / şube seçimini sıfırla */
  useEffect(() => {
    if (target !== 'PARENTS_CLASSROOM') setClassroomId('');
    if (target === 'PARENTS_CLASSROOM') setNotifBranchId('');
  }, [target]);

  /* execCommand yardımcıları */
  const exec = useCallback((command: string, value?: string) => {
    editorRef.current?.focus();
    document.execCommand(command, false, value);
  }, []);

  /* Gönder */
  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!title.trim()) return;

    const body = editorRef.current?.innerHTML ?? '';
    const bodyText = editorRef.current?.innerText?.trim() ?? '';

    setSending(true);
    const res = await apiFetchJson('/v1/admin/notifications/broadcast', {
      method: 'POST',
      body: JSON.stringify({
        title: title.trim(),
        body: bodyText ? body : undefined,
        targetType: target,
        classroomId: target === 'PARENTS_CLASSROOM' ? classroomId || undefined : undefined,
        branchId:
          target === 'TEACHERS' || target === 'ALL_PARENTS'
            ? notifBranchId || undefined
            : undefined,
      }),
    });
    setSending(false);

    if (res.error) {
      toast({ title: 'Gönderilemedi', description: res.error, variant: 'destructive' });
    } else {
      const d = res.data as { created?: number; message?: string };
      toast({
        title: 'Duyuru gönderildi',
        description: d?.message ?? `${d?.created ?? 0} bildirim oluşturuldu`,
      });
      setTitle('');
      if (editorRef.current) editorRef.current.innerHTML = '';
    }
  }

  const selectedOpt = TARGET_OPTIONS.find((o) => o.value === target)!;

  return (
    <div className="space-y-6">
      <PageHeader
        eyebrow="İletişim"
        title="Duyurular"
        description="Velilere veya öğretmenlere uygulama içi anlık bildirim gönderin."
      />

      <form onSubmit={handleSubmit} className="space-y-5">
        {/* ── Hedef Kitle Kartı ──────────────────────────────────────── */}
        <div className="admin-panel p-5">
          <div className="mb-4 border-b border-zinc-100 pb-3 dark:border-zinc-800">
            <p className="text-[13px] font-semibold uppercase tracking-widest text-zinc-400 dark:text-zinc-500">
              Kime Gönderilsin?
            </p>
          </div>

          <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
            {TARGET_OPTIONS.map((opt) => {
              const Icon = opt.icon;
              const isActive = target === opt.value;
              return (
                <button
                  key={opt.value}
                  type="button"
                  onClick={() => setTarget(opt.value)}
                  className={cn(
                    'group relative flex flex-col gap-2.5 rounded-xl border-2 p-4 text-left transition-all duration-150',
                    isActive
                      ? `${opt.activeBg} ${opt.activeBorder} shadow-sm`
                      : 'border-zinc-200/80 bg-white hover:border-zinc-300 hover:bg-zinc-50/80 dark:border-zinc-700/60 dark:bg-zinc-900/30 dark:hover:border-zinc-600',
                  )}
                >
                  {/* Seçim indikatörü */}
                  <span
                    className={cn(
                      'absolute right-3 top-3 h-2 w-2 rounded-full transition-opacity',
                      isActive ? `${opt.activeDot} opacity-100` : 'opacity-0',
                    )}
                  />

                  {/* İkon */}
                  <span
                    className={cn(
                      'flex h-9 w-9 items-center justify-center rounded-lg border transition-colors',
                      isActive
                        ? `border-current/20 ${opt.activeBg} ${opt.activeIcon}`
                        : 'border-zinc-200 bg-zinc-50 text-zinc-400 group-hover:border-zinc-300 group-hover:text-zinc-500 dark:border-zinc-700 dark:bg-zinc-800/60',
                    )}
                  >
                    <Icon className="h-[18px] w-[18px]" />
                  </span>

                  {/* Metin */}
                  <div>
                    <p
                      className={cn(
                        'text-[13px] font-semibold leading-tight',
                        isActive
                          ? opt.colorClass
                          : 'text-zinc-700 dark:text-zinc-200',
                      )}
                    >
                      {opt.label}
                    </p>
                    <p className="mt-0.5 text-[12px] leading-snug text-zinc-400 dark:text-zinc-500">
                      {opt.description}
                    </p>
                  </div>
                </button>
              );
            })}
          </div>

          {/* Şube seçimi — TEACHERS ve ALL_PARENTS */}
          <div
            className={cn(
              'overflow-hidden transition-all duration-200',
              target === 'TEACHERS' || target === 'ALL_PARENTS'
                ? 'mt-4 max-h-24 opacity-100'
                : 'max-h-0 opacity-0',
            )}
          >
            <div className="space-y-1.5">
              <Label className="text-[13px] text-zinc-600 dark:text-zinc-400">
                Şube <span className="font-normal text-zinc-400">(opsiyonel — tüm şubeler için boş bırakın)</span>
              </Label>
              <SelectNative
                value={notifBranchId}
                onChange={(e) => setNotifBranchId(e.target.value)}
                className="max-w-sm"
              >
                <option value="">— Tüm şubeler —</option>
                {branches.map((b) => (
                  <option key={b.id} value={b.id}>
                    {b.name}
                  </option>
                ))}
              </SelectNative>
            </div>
          </div>

          {/* Sınıf seçimi — yalnızca PARENTS_CLASSROOM */}
          <div
            className={cn(
              'overflow-hidden transition-all duration-200',
              target === 'PARENTS_CLASSROOM' ? 'mt-4 max-h-24 opacity-100' : 'max-h-0 opacity-0',
            )}
          >
            <div className="space-y-1.5">
              <Label className="text-[13px] text-zinc-600 dark:text-zinc-400">Sınıf Seç</Label>
              <SelectNative
                value={classroomId}
                onChange={(e) => setClassroomId(e.target.value)}
                required={target === 'PARENTS_CLASSROOM'}
                className="max-w-sm"
              >
                <option value="">— Sınıf seçin —</option>
                {classrooms.map((c) => (
                  <option key={c.id} value={c.id}>
                    {c.name}
                    {c.branchName ? ` · ${c.branchName}` : ''}
                  </option>
                ))}
              </SelectNative>
            </div>
          </div>
        </div>

        {/* ── Duyuru İçeriği ─────────────────────────────────────────── */}
        <div className="admin-panel p-5">
          <div className="mb-4 border-b border-zinc-100 pb-3 dark:border-zinc-800">
            <p className="text-[13px] font-semibold uppercase tracking-widest text-zinc-400 dark:text-zinc-500">
              Duyuru İçeriği
            </p>
          </div>

          <div className="space-y-4">
            {/* Başlık */}
            <div className="space-y-1.5">
              <Label htmlFor="notif-title" className="text-[13px] font-medium text-zinc-700 dark:text-zinc-300">
                Başlık <span className="text-red-500">*</span>
              </Label>
              <Input
                id="notif-title"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                placeholder="Örn: Yarın okul çıkış saati değişti"
                required
                minLength={2}
                maxLength={120}
                className="text-[13px]"
              />
              <p className="text-right text-[11px] text-zinc-400">{title.length} / 120</p>
            </div>

            {/* Zengin metin editörü */}
            <div className="space-y-1.5">
              <Label className="text-[13px] font-medium text-zinc-700 dark:text-zinc-300">
                Mesaj <span className="text-zinc-400 font-normal">(opsiyonel)</span>
              </Label>

              <div className="overflow-hidden rounded-lg border border-zinc-200 shadow-sm focus-within:border-zinc-400 focus-within:ring-2 focus-within:ring-zinc-900/10 dark:border-zinc-700 dark:focus-within:border-zinc-500 dark:focus-within:ring-white/10">
                {/* Araç çubuğu */}
                <div className="flex items-center gap-0.5 border-b border-zinc-200 bg-zinc-50 px-2 py-1.5 dark:border-zinc-700 dark:bg-zinc-800/60">
                  <ToolbarButton onClick={() => exec('bold')} title="Kalın (Ctrl+B)">
                    <Bold className="h-3.5 w-3.5" />
                  </ToolbarButton>
                  <ToolbarButton onClick={() => exec('italic')} title="İtalik (Ctrl+I)">
                    <Italic className="h-3.5 w-3.5" />
                  </ToolbarButton>
                  <ToolbarButton onClick={() => exec('underline')} title="Altı çizili (Ctrl+U)">
                    <Underline className="h-3.5 w-3.5" />
                  </ToolbarButton>

                  <span className="mx-1.5 h-4 w-px bg-zinc-200 dark:bg-zinc-700" />

                  <ToolbarButton onClick={() => exec('insertUnorderedList')} title="Madde listesi">
                    <List className="h-3.5 w-3.5" />
                  </ToolbarButton>
                  <ToolbarButton onClick={() => exec('insertOrderedList')} title="Numaralı liste">
                    <ListOrdered className="h-3.5 w-3.5" />
                  </ToolbarButton>

                  <span className="mx-1.5 h-4 w-px bg-zinc-200 dark:bg-zinc-700" />

                  <ToolbarButton onClick={() => exec('insertHorizontalRule')} title="Ayraç ekle">
                    <Minus className="h-3.5 w-3.5" />
                  </ToolbarButton>

                  <span className="ml-auto text-[11px] text-zinc-400 dark:text-zinc-500 pr-1">
                    Biçimlendirme desteklenir
                  </span>
                </div>

                {/* Yazı alanı */}
                <div
                  ref={editorRef}
                  contentEditable
                  suppressContentEditableWarning
                  data-placeholder="Duyuru detaylarını buraya yazın…"
                  className={cn(
                    'min-h-[140px] w-full bg-white px-3 py-2.5 text-[13px] leading-relaxed text-zinc-900 outline-none',
                    'dark:bg-zinc-900/40 dark:text-zinc-100',
                    // placeholder
                    '[&:empty]:before:content-[attr(data-placeholder)] [&:empty]:before:text-zinc-400 [&:empty]:before:dark:text-zinc-600',
                    // liste stilleri
                    '[&_ul]:list-disc [&_ul]:pl-5 [&_ol]:list-decimal [&_ol]:pl-5',
                    '[&_hr]:my-2 [&_hr]:border-zinc-200 [&_hr]:dark:border-zinc-700',
                  )}
                />
              </div>
            </div>
          </div>
        </div>

        {/* ── Gönder Çubuğu ──────────────────────────────────────────── */}
        <div className="flex items-center justify-between rounded-xl border border-zinc-200/90 bg-white px-5 py-3.5 shadow-theme-xs dark:border-zinc-800/90 dark:bg-zinc-900/40">
          {/* Özet bilgi */}
          <div className="flex items-center gap-2">
            <span
              className={cn(
                'flex h-7 w-7 items-center justify-center rounded-lg',
                selectedOpt.activeBg,
                selectedOpt.activeIcon,
              )}
            >
              <selectedOpt.icon className="h-4 w-4" />
            </span>
            <span className="text-[13px] text-zinc-500 dark:text-zinc-400">
              <span className={cn('font-semibold', selectedOpt.colorClass)}>{selectedOpt.label}</span>
              {target === 'PARENTS_CLASSROOM' && classroomId && (
                <>
                  {' · '}
                  <span className="text-zinc-700 dark:text-zinc-300">
                    {classrooms.find((c) => c.id === classroomId)?.name ?? ''}
                  </span>
                </>
              )}
              {(target === 'TEACHERS' || target === 'ALL_PARENTS') && notifBranchId && (
                <>
                  {' · '}
                  <span className="text-zinc-700 dark:text-zinc-300">
                    {branches.find((b) => b.id === notifBranchId)?.name ?? ''}
                  </span>
                </>
              )}
            </span>
          </div>

          <Button
            type="submit"
            disabled={sending || !title.trim()}
            className="gap-2 bg-brand-600 text-white shadow-sm hover:bg-brand-700 disabled:opacity-50"
          >
            {sending ? (
              <>
                <span className="h-3.5 w-3.5 animate-spin rounded-full border-2 border-white/30 border-t-white" />
                Gönderiliyor…
              </>
            ) : (
              <>
                <Send className="h-3.5 w-3.5" />
                Duyuru Gönder
              </>
            )}
          </Button>
        </div>
      </form>
    </div>
  );
}
