import { useEffect, useState, useCallback } from 'react';
import { Ban, RotateCcw, Loader2, Globe, Layers } from 'lucide-react';
import { Card, CardContent } from '@shared/components/ui/card';
import { Badge } from '@shared/components/ui/badge';
import { Button } from '@shared/components/ui/button';
import { Select } from '@shared/components/ui/select';
import { PageContainer, PageHeader } from '@shared/components/layout';
import { useAuth } from '@/app/auth/AuthContext';
import {
  fetchExclusions,
  excludeForGroup,
  excludeGlobal,
  releaseExclusion,
  type CandidateExclusion,
} from '@/services/parentInferenceApi';
import { formatDateTime } from '@shared/utils/dateFormat';

/**
 * 모선 후보 제외 페이지.
 * - GROUP scope: 특정 group_key + sub_cluster에서 후보 제외
 * - GLOBAL scope: 모든 그룹에서 영구 제외 (admin: exclusion-management 권한 필요)
 *
 * 권한:
 *   - parent-inference-workflow:parent-exclusion (CREATE/UPDATE/READ): GROUP scope
 *   - parent-inference-workflow:exclusion-management (CREATE): GLOBAL scope
 */

export function ParentExclusion() {
  const { hasPermission } = useAuth();
  const canCreateGroup = hasPermission('parent-inference-workflow:parent-exclusion', 'CREATE');
  const canRelease = hasPermission('parent-inference-workflow:parent-exclusion', 'UPDATE');
  const canCreateGlobal = hasPermission('parent-inference-workflow:exclusion-management', 'CREATE');

  const [items, setItems] = useState<CandidateExclusion[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [filter, setFilter] = useState<'' | 'GROUP' | 'GLOBAL'>('');
  const [busy, setBusy] = useState<number | null>(null);

  // 신규 GROUP 제외 폼
  const [grpKey, setGrpKey] = useState('');
  const [grpSub, setGrpSub] = useState('1');
  const [grpMmsi, setGrpMmsi] = useState('');
  const [grpReason, setGrpReason] = useState('');

  // 신규 GLOBAL 제외 폼
  const [glbMmsi, setGlbMmsi] = useState('');
  const [glbReason, setGlbReason] = useState('');

  const load = useCallback(async () => {
    setLoading(true);
    setError('');
    try {
      const res = await fetchExclusions(filter || undefined, 0, 50);
      setItems(res.content);
    } catch (e: unknown) {
      const msg = e instanceof Error ? e.message : 'unknown';
      setError(msg);
    } finally {
      setLoading(false);
    }
  }, [filter]);

  useEffect(() => { load(); }, [load]);

  const handleAddGroup = async () => {
    if (!canCreateGroup || !grpKey || !grpMmsi) return;
    setBusy(-1);
    try {
      await excludeForGroup(grpKey, parseInt(grpSub, 10), { excludedMmsi: grpMmsi, reason: grpReason });
      setGrpKey(''); setGrpMmsi(''); setGrpReason('');
      await load();
    } catch (e: unknown) {
      alert('실패: ' + (e instanceof Error ? e.message : 'unknown'));
    } finally {
      setBusy(null);
    }
  };

  const handleAddGlobal = async () => {
    if (!canCreateGlobal || !glbMmsi) return;
    setBusy(-2);
    try {
      await excludeGlobal({ excludedMmsi: glbMmsi, reason: glbReason });
      setGlbMmsi(''); setGlbReason('');
      await load();
    } catch (e: unknown) {
      alert('실패: ' + (e instanceof Error ? e.message : 'unknown'));
    } finally {
      setBusy(null);
    }
  };

  const handleRelease = async (id: number) => {
    if (!canRelease) return;
    setBusy(id);
    try {
      await releaseExclusion(id, '운영자 해제');
      await load();
    } catch (e: unknown) {
      alert('실패: ' + (e instanceof Error ? e.message : 'unknown'));
    } finally {
      setBusy(null);
    }
  };

  return (
    <PageContainer size="lg">
      <PageHeader
        icon={Ban}
        iconColor="text-red-400"
        title="모선 후보 제외"
        description="GROUP/GLOBAL 스코프로 잘못된 후보를 차단합니다."
        actions={
          <>
            <Select
              size="sm"
              aria-label="스코프 필터"
              title="스코프 필터"
              value={filter}
              onChange={(e) => setFilter(e.target.value as '' | 'GROUP' | 'GLOBAL')}
            >
              <option value="">전체 스코프</option>
              <option value="GROUP">GROUP</option>
              <option value="GLOBAL">GLOBAL</option>
            </Select>
            <Button variant="primary" size="sm" onClick={load}>
              새로고침
            </Button>
          </>
        }
      />

      {/* 신규 등록: GROUP */}
      <Card>
        <CardContent className="p-4 space-y-2">
          <div className="text-xs font-medium text-heading flex items-center gap-2">
            <Layers className="w-3.5 h-3.5" /> GROUP 제외 (특정 그룹 한정)
            {!canCreateGroup && <span className="text-yellow-400 text-[10px]">권한 없음</span>}
          </div>
          <div className="flex items-center gap-2">
            <input aria-label="group_key" value={grpKey} onChange={(e) => setGrpKey(e.target.value)} placeholder="group_key"
                   className="flex-1 bg-surface-overlay border border-border rounded px-3 py-1.5 text-xs" disabled={!canCreateGroup} />
            <input aria-label="sub_cluster_id" type="number" value={grpSub} onChange={(e) => setGrpSub(e.target.value)} placeholder="sub"
                   className="w-24 bg-surface-overlay border border-border rounded px-3 py-1.5 text-xs" disabled={!canCreateGroup} />
            <input aria-label="excluded MMSI" value={grpMmsi} onChange={(e) => setGrpMmsi(e.target.value)} placeholder="excluded MMSI"
                   className="w-40 bg-surface-overlay border border-border rounded px-3 py-1.5 text-xs" disabled={!canCreateGroup} />
            <input aria-label="제외 사유" value={grpReason} onChange={(e) => setGrpReason(e.target.value)} placeholder="사유"
                   className="flex-1 bg-surface-overlay border border-border rounded px-3 py-1.5 text-xs" disabled={!canCreateGroup} />
            <button type="button" onClick={handleAddGroup}
                    disabled={!canCreateGroup || !grpKey || !grpMmsi || busy === -1}
                    className="px-3 py-1.5 bg-orange-600 hover:bg-orange-500 disabled:bg-orange-600/40 text-white text-xs rounded flex items-center gap-1">
              {busy === -1 ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Ban className="w-3.5 h-3.5" />}
              제외
            </button>
          </div>
        </CardContent>
      </Card>

      {/* 신규 등록: GLOBAL */}
      <Card>
        <CardContent className="p-4 space-y-2">
          <div className="text-xs font-medium text-heading flex items-center gap-2">
            <Globe className="w-3.5 h-3.5" /> GLOBAL 제외 (모든 그룹 영구 차단, 관리자 권한)
            {!canCreateGlobal && <span className="text-yellow-400 text-[10px]">권한 없음</span>}
          </div>
          <div className="flex items-center gap-2">
            <input aria-label="excluded MMSI (전역)" value={glbMmsi} onChange={(e) => setGlbMmsi(e.target.value)} placeholder="excluded MMSI"
                   className="w-40 bg-surface-overlay border border-border rounded px-3 py-1.5 text-xs" disabled={!canCreateGlobal} />
            <input aria-label="전역 제외 사유" value={glbReason} onChange={(e) => setGlbReason(e.target.value)} placeholder="사유"
                   className="flex-1 bg-surface-overlay border border-border rounded px-3 py-1.5 text-xs" disabled={!canCreateGlobal} />
            <button type="button" onClick={handleAddGlobal}
                    disabled={!canCreateGlobal || !glbMmsi || busy === -2}
                    className="px-3 py-1.5 bg-red-600 hover:bg-red-500 disabled:bg-red-600/40 text-white text-xs rounded flex items-center gap-1">
              {busy === -2 ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Globe className="w-3.5 h-3.5" />}
              전역 제외
            </button>
          </div>
        </CardContent>
      </Card>

      {error && <div className="text-xs text-red-400">에러: {error}</div>}

      {loading && (
        <div className="flex items-center justify-center py-12 text-muted-foreground">
          <Loader2 className="w-5 h-5 animate-spin" />
        </div>
      )}

      {!loading && (
        <Card>
          <CardContent className="p-0 overflow-x-auto">
            <table className="w-full text-xs">
              <thead className="bg-surface-overlay text-hint">
                <tr>
                  <th className="px-3 py-2 text-left">ID</th>
                  <th className="px-3 py-2 text-left">스코프</th>
                  <th className="px-3 py-2 text-left">Group Key</th>
                  <th className="px-3 py-2 text-center">Sub</th>
                  <th className="px-3 py-2 text-left">제외 MMSI</th>
                  <th className="px-3 py-2 text-left">사유</th>
                  <th className="px-3 py-2 text-left">등록자</th>
                  <th className="px-3 py-2 text-left">생성</th>
                  <th className="px-3 py-2 text-center">액션</th>
                </tr>
              </thead>
              <tbody>
                {items.length === 0 && (
                  <tr><td colSpan={9} className="px-3 py-8 text-center text-hint">활성 제외 항목이 없습니다.</td></tr>
                )}
                {items.map((it) => (
                  <tr key={it.id} className="border-t border-border hover:bg-surface-overlay/50">
                    <td className="px-3 py-2 text-hint font-mono">{it.id}</td>
                    <td className="px-3 py-2">
                      <Badge intent={it.scopeType === 'GLOBAL' ? 'critical' : 'high'} size="xs">
                        {it.scopeType}
                      </Badge>
                    </td>
                    <td className="px-3 py-2 text-heading font-medium">{it.groupKey || '-'}</td>
                    <td className="px-3 py-2 text-center text-muted-foreground">{it.subClusterId ?? '-'}</td>
                    <td className="px-3 py-2 text-cyan-400 font-mono">{it.excludedMmsi}</td>
                    <td className="px-3 py-2 text-muted-foreground">{it.reason || '-'}</td>
                    <td className="px-3 py-2 text-muted-foreground">{it.actorAcnt || '-'}</td>
                    <td className="px-3 py-2 text-muted-foreground text-[10px]">{formatDateTime(it.createdAt)}</td>
                    <td className="px-3 py-2 text-center">
                      <button type="button" disabled={!canRelease || busy === it.id} onClick={() => handleRelease(it.id)}
                              className="p-1 rounded hover:bg-blue-500/20 disabled:opacity-30 text-blue-400" title="해제">
                        <RotateCcw className="w-3.5 h-3.5" />
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </CardContent>
        </Card>
      )}
    </PageContainer>
  );
}
