import { useEffect, useState } from "react";
import { usePermissionStore, PERMISSION_LABELS, PERMS, type ChannelOverride, hasPermission } from "../stores/permissions.ts";
import { useRoleStore } from "../stores/role.ts";
import { useMemberStore } from "../stores/member.ts";
import { useChannelStore } from "../stores/channel.ts";
import { api } from "../lib/api.ts";

interface ChannelSettingsModalProps {
  serverId: string;
  channelId: string;
  channelName: string;
  onClose: () => void;
}

type Tab = 'overview' | 'permissions';
type TargetMode = 'role' | 'user';

interface OverrideFormData {
  targetType: TargetMode;
  targetId: string;
  allow: number;
  deny: number;
}

function OverrideMatrix({ allow, deny, onChange }: { allow: number; deny: number; onChange: (allow: number, deny: number) => void }) {
  const toggle = (flag: number, state: 'allow' | 'deny' | 'inherit') => {
    let nextAllow = allow;
    let nextDeny = deny;
    if (state === 'allow') {
      nextAllow |= flag;
      nextDeny &= ~flag;
    } else if (state === 'deny') {
      nextAllow &= ~flag;
      nextDeny |= flag;
    } else {
      nextAllow &= ~flag;
      nextDeny &= ~flag;
    }
    onChange(nextAllow, nextDeny);
  };

  const state = (flag: number): 'allow' | 'deny' | 'inherit' => {
    if (hasPermission(allow, flag)) return 'allow';
    if (hasPermission(deny, flag)) return 'deny';
    return 'inherit';
  };

  return (
    <div className="space-y-1 max-h-64 overflow-y-auto border border-gb-bg-t p-2">
      {(Object.keys(PERMISSION_LABELS) as (keyof typeof PERMISSION_LABELS)[]).map((key) => {
        const flag = PERMS[key];
        const s = state(flag);
        return (
          <div key={key} className="flex items-center justify-between text-xs font-mono py-1">
            <span className="text-gb-fg">{PERMISSION_LABELS[key]}</span>
            <div className="flex gap-1">
              {(['inherit', 'allow', 'deny'] as const).map((opt) => (
                <button
                  key={opt}
                  onClick={() => toggle(flag, opt)}
                  className={`px-2 py-0.5 border ${
                    s === opt
                      ? opt === 'allow' ? 'bg-gb-green text-gb-bg border-gb-green' :
                        opt === 'deny' ? 'bg-gb-red text-gb-bg border-gb-red' :
                        'bg-gb-orange text-gb-bg border-gb-orange'
                      : 'border-gb-bg-t text-gb-fg-f hover:border-gb-fg-t'
                  }`}
                >
                  {opt.toUpperCase()}
                </button>
              ))}
            </div>
          </div>
        );
      })}
    </div>
  );
}

export function ChannelSettingsModal({ serverId, channelId, channelName, onClose }: ChannelSettingsModalProps) {
  const [tab, setTab] = useState<Tab>('overview');
  const [form, setForm] = useState<OverrideFormData>({ targetType: 'role', targetId: '', allow: 0, deny: 0 });
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [editName, setEditName] = useState(channelName);
  const [savingName, setSavingName] = useState(false);
  const updateChannel = useChannelStore((s) => s.updateChannel);

  const overrides = usePermissionStore((s) => s.overridesByChannel[channelId] || []);
  const fetchOverrides = usePermissionStore((s) => s.fetchOverrides);
  const setOverride = usePermissionStore((s) => s.setOverride);
  const deleteOverride = usePermissionStore((s) => s.deleteOverride);

  const roles = useRoleStore((s) => s.roles);
  const fetchRoles = useRoleStore((s) => s.fetchRoles);
  const members = useMemberStore((s) => s.membersByServer[serverId] || []);
  const fetchMembers = useMemberStore((s) => s.fetchMembers);

  useEffect(() => {
    fetchOverrides(channelId).catch(() => setError('Failed to load overrides'));
    fetchRoles(serverId).catch(() => {});
    fetchMembers(serverId).catch(() => {});
  }, [channelId, serverId, fetchOverrides, fetchRoles, fetchMembers]);

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [onClose]);

  const handleSave = async () => {
    if (!form.targetId) {
      setError('Select a target');
      return;
    }
    setSaving(true);
    setError(null);
    try {
      await setOverride(channelId, form.targetType, form.targetId, form.allow, form.deny);
      setForm({ targetType: 'role', targetId: '', allow: 0, deny: 0 });
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to save override');
    } finally {
      setSaving(false);
    }
  };

  const handleSaveName = async () => {
    const name = editName.trim();
    if (!name || name === channelName) return;
    setSavingName(true);
    setError(null);
    try {
      const updated = await api.patch<{ id: string; server_id: string; name: string; type: string; category: string | null; position: number; group_id?: string | null }>(
        `/servers/${serverId}/channels/${channelId}`,
        { name }
      );
      updateChannel(updated as any);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to rename channel');
    } finally {
      setSavingName(false);
    }
  };

  const targets = form.targetType === 'role'
    ? roles.filter((r) => !r.is_default).map((r) => ({ id: r.id, label: r.name }))
    : members.map((m) => ({ id: m.id, label: m.username }));

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" onClick={onClose}>
      <div className="bg-gb-bg border border-gb-bg-t w-[600px] max-h-[80vh] flex flex-col font-mono" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between px-4 py-3 border-b border-gb-bg-t">
          <span className="text-sm text-gb-orange">CHANNEL SETTINGS: #{channelName}</span>
          <button onClick={onClose} className="text-xs text-gb-red">[x]</button>
        </div>
        <div className="flex border-b border-gb-bg-t">
          <button onClick={() => setTab('overview')} className={`px-4 py-2 text-xs ${tab === 'overview' ? 'text-gb-orange bg-gb-bg-s' : 'text-gb-fg-s hover:text-gb-fg'}`}>[OVERVIEW]</button>
          <button onClick={() => setTab('permissions')} className={`px-4 py-2 text-xs ${tab === 'permissions' ? 'text-gb-orange bg-gb-bg-s' : 'text-gb-fg-s hover:text-gb-fg'}`}>[PERMISSIONS]</button>
        </div>
        <div className="flex-1 overflow-y-auto p-4">
          {tab === 'overview' && (
            <div className="space-y-3">
              <div className="text-xs text-gb-fg-f">Channel name</div>
              <div className="flex gap-2">
                <input
                  value={editName}
                  onChange={(e) => setEditName(e.target.value)}
                  onKeyDown={(e) => { if (e.key === 'Enter') handleSaveName(); }}
                  className="terminal-input text-sm flex-1"
                />
                <button
                  onClick={handleSaveName}
                  disabled={savingName || !editName.trim() || editName.trim() === channelName}
                  className="px-3 py-1 bg-gb-orange text-gb-bg text-xs disabled:opacity-50"
                >
                  {savingName ? 'SAVING...' : '[SAVE]'}
                </button>
              </div>
              {error && <div className="text-xs text-gb-red">ERR: {error}</div>}
            </div>
          )}
          {tab === 'permissions' && (
            <div className="space-y-3">
              <div className="text-xs text-gb-fg-f">Existing overrides</div>
              {overrides.length === 0 && <div className="text-xs text-gb-fg-f">[none]</div>}
              {overrides.map((o: ChannelOverride) => (
                <div key={o.id} className="flex items-center justify-between border border-gb-bg-t p-2 text-xs">
                  <span className="text-gb-fg">{o.target_type}:{o.target_id}</span>
                  <div className="flex gap-2 text-gb-fg-f">
                    <span>allow:{o.allow_bitflags}</span>
                    <span>deny:{o.deny_bitflags}</span>
                    <button onClick={() => deleteOverride(channelId, o.target_type, o.target_id)} className="text-gb-red hover:text-gb-orange">[x]</button>
                  </div>
                </div>
              ))}

              <div className="border-t border-gb-bg-t pt-3">
                <div className="text-xs text-gb-fg-f mb-2">New override</div>
                <div className="flex gap-2 mb-2">
                  <select
                    value={form.targetType}
                    onChange={(e) => setForm({ ...form, targetType: e.target.value as TargetMode, targetId: '' })}
                    className="terminal-input text-xs"
                  >
                    <option value="role">role</option>
                    <option value="user">user</option>
                  </select>
                  <select
                    value={form.targetId}
                    onChange={(e) => setForm({ ...form, targetId: e.target.value })}
                    className="terminal-input text-xs flex-1"
                  >
                    <option value="">-- select --</option>
                    {targets.map((t) => (
                      <option key={t.id} value={t.id}>{t.label}</option>
                    ))}
                  </select>
                </div>
                <OverrideMatrix allow={form.allow} deny={form.deny} onChange={(a, d) => setForm({ ...form, allow: a, deny: d })} />
                {error && <div className="text-xs text-gb-red mt-2">ERR: {error}</div>}
                <button
                  onClick={handleSave}
                  disabled={saving || !form.targetId}
                  className="mt-2 px-3 py-1 bg-gb-orange text-gb-bg text-xs disabled:opacity-50"
                >
                  {saving ? 'SAVING...' : '[SAVE OVERRIDE]'}
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
