import { useState, useEffect, useMemo, useRef } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { getCatalog } from '../../services/apiHubService';
import { createKeyRequest } from '../../services/apiKeyService';
import type { ServiceCatalog } from '../../types/apihub';

const IndeterminateCheckbox = ({ checked, indeterminate, onChange, className }: { checked: boolean; indeterminate: boolean; onChange: () => void; className?: string }) => {
  const ref = useRef<HTMLInputElement>(null);
  useEffect(() => {
    if (ref.current) ref.current.indeterminate = indeterminate;
  }, [indeterminate]);
  return <input ref={ref} type="checkbox" checked={checked} onChange={onChange} className={className || 'rounded'} />;
};

interface FlatApi {
  apiId: number;
  apiName: string;
  description: string | null;
}

interface FlatDomainGroup {
  domain: string;
  apis: FlatApi[];
}

const KeyRequestPage = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const preApiId = searchParams.get('apiId');

  const [catalog, setCatalog] = useState<ServiceCatalog[]>([]);
  const [expandedDomains, setExpandedDomains] = useState<Set<string>>(new Set());
  const [selectedApiIds, setSelectedApiIds] = useState<Set<number>>(new Set());
  const [keyName, setKeyName] = useState('');
  const [purpose, setPurpose] = useState('');
  const [serviceIp, setServiceIp] = useState('');
  const [servicePurpose, setServicePurpose] = useState('');
  const [dailyRequestEstimate, setDailyRequestEstimate] = useState('');
  const [usagePeriodMode, setUsagePeriodMode] = useState<'preset' | 'custom'>('preset');
  const [isPermanent, setIsPermanent] = useState(false);
  const [usageFromDate, setUsageFromDate] = useState('');
  const [usageToDate, setUsageToDate] = useState('');
  const [searchQuery, setSearchQuery] = useState('');
  const [isLoading, setIsLoading] = useState(true);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);

  useEffect(() => {
    const fetchData = async () => {
      try {
        setIsLoading(true);
        const catalogRes = await getCatalog();
        if (catalogRes.success && catalogRes.data) {
          setCatalog(catalogRes.data);

          // 쿼리 파라미터로 전달된 API 자동 선택
          if (preApiId) {
            const aId = Number(preApiId);
            for (const service of catalogRes.data) {
              for (const domainGroup of service.domains) {
                const targetApi = domainGroup.apis.find((a) => a.apiId === aId);
                if (targetApi) {
                  setSelectedApiIds(new Set([aId]));
                  setExpandedDomains(new Set([domainGroup.domain]));
                  break;
                }
              }
            }
          }
        } else {
          setError(catalogRes.message || '카탈로그를 불러오는데 실패했습니다.');
        }
      } catch {
        setError('카탈로그를 불러오는데 실패했습니다.');
      } finally {
        setIsLoading(false);
      }
    };

    fetchData();
  }, [preApiId]);

  // catalog → FlatDomainGroup[] 변환 (도메인 기준 플랫 그룹핑, 알파벳순 정렬)
  const flatDomainGroups = useMemo<FlatDomainGroup[]>(() => {
    const domainMap = new Map<string, FlatApi[]>();

    for (const service of catalog) {
      for (const domainGroup of service.domains) {
        const domainName = domainGroup.domain || '미분류';
        if (!domainMap.has(domainName)) {
          domainMap.set(domainName, []);
        }
        const existing = domainMap.get(domainName)!;
        for (const api of domainGroup.apis) {
          existing.push({
            apiId: api.apiId,
            apiName: api.apiName,
            description: api.description,
          });
        }
      }
    }

    const result: FlatDomainGroup[] = [];
    domainMap.forEach((apis, domain) => {
      result.push({ domain, apis });
    });

    return result;
  }, [catalog]);

  const allApis = useMemo<FlatApi[]>(() => {
    return flatDomainGroups.flatMap((dg) => dg.apis);
  }, [flatDomainGroups]);

  const allApisSelected = allApis.length > 0 && allApis.every((a) => selectedApiIds.has(a.apiId));
  const someApisSelected = allApis.some((a) => selectedApiIds.has(a.apiId));

  const filteredDomainGroups = useMemo<FlatDomainGroup[]>(() => {
    if (!searchQuery.trim()) return flatDomainGroups;
    const query = searchQuery.toLowerCase();
    return flatDomainGroups
      .map((dg) => ({
        domain: dg.domain,
        apis: dg.apis.filter(
          (a) =>
            a.apiName.toLowerCase().includes(query) ||
            (a.description?.toLowerCase().includes(query) ?? false),
        ),
      }))
      .filter((dg) => dg.apis.length > 0);
  }, [flatDomainGroups, searchQuery]);

  const handleToggleDomain = (domain: string) => {
    setExpandedDomains((prev) => {
      const next = new Set(prev);
      if (next.has(domain)) {
        next.delete(domain);
      } else {
        next.add(domain);
      }
      return next;
    });
  };

  const handleToggleApi = (apiId: number) => {
    setSelectedApiIds((prev) => {
      const next = new Set(prev);
      if (next.has(apiId)) {
        next.delete(apiId);
      } else {
        next.add(apiId);
      }
      return next;
    });
  };

  const handleToggleAllDomainApis = (domain: string) => {
    const domainGroup = flatDomainGroups.find((dg) => dg.domain === domain);
    if (!domainGroup) return;

    const domainApis = domainGroup.apis;
    const allSelected = domainApis.every((a) => selectedApiIds.has(a.apiId));

    setSelectedApiIds((prev) => {
      const next = new Set(prev);
      domainApis.forEach((a) => {
        if (allSelected) {
          next.delete(a.apiId);
        } else {
          next.add(a.apiId);
        }
      });
      return next;
    });
  };

  const handleToggleAll = () => {
    if (allApisSelected) {
      setSelectedApiIds(new Set());
    } else {
      setSelectedApiIds(new Set(allApis.map((a) => a.apiId)));
    }
  };

  const handleClearSelection = () => {
    setSelectedApiIds(new Set());
  };

  const handlePresetPeriod = (months: number) => {
    const from = new Date();
    const to = new Date();
    to.setMonth(to.getMonth() + months);
    setUsageFromDate(from.toISOString().split('T')[0]);
    setUsageToDate(to.toISOString().split('T')[0]);
    setUsagePeriodMode('preset');
    setIsPermanent(false);
  };

  const handlePermanent = () => {
    setIsPermanent(true);
    setUsageFromDate('');
    setUsageToDate('');
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (selectedApiIds.size === 0) {
      setError('최소 하나의 API를 선택해주세요.');
      return;
    }
    if (!isPermanent && (!usageFromDate || !usageToDate)) {
      setError('사용 기간을 설정해주세요.');
      return;
    }

    setError(null);
    setIsSubmitting(true);

    try {
      const res = await createKeyRequest({
        keyName,
        purpose: purpose || undefined,
        requestedApiIds: Array.from(selectedApiIds),
        serviceIp: serviceIp || undefined,
        servicePurpose: servicePurpose || undefined,
        dailyRequestEstimate: dailyRequestEstimate ? Number(dailyRequestEstimate) : undefined,
        usageFromDate: isPermanent ? undefined : usageFromDate,
        usageToDate: isPermanent ? undefined : usageToDate,
      });
      if (res.success) {
        setSuccess(true);
      } else {
        setError(res.message || 'API Key 신청에 실패했습니다.');
      }
    } catch {
      setError('API Key 신청에 실패했습니다.');
    } finally {
      setIsSubmitting(false);
    }
  };

  if (isLoading) {
    return <div className="max-w-7xl mx-auto text-center py-10 text-gray-500 dark:text-gray-400">로딩 중...</div>;
  }

  if (success) {
    return (
      <div className="max-w-7xl mx-auto">
        <div className="max-w-lg mx-auto mt-10 text-center">
          <div className="bg-green-50 border border-green-200 rounded-lg p-6">
            <h2 className="text-lg font-semibold text-green-800 mb-2">신청이 완료되었습니다</h2>
            <p className="text-green-700 text-sm mb-4">
              관리자 승인 후 API Key가 생성됩니다.
            </p>
            <button
              onClick={() => navigate('/apikeys/my-keys')}
              className="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-lg text-sm font-medium"
            >
              내 키 목록으로 이동
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-7xl mx-auto">
      <h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100 mb-6">API Key 신청</h1>

      {error && (
        <div className="mb-4 p-3 bg-red-50 text-red-700 rounded-lg text-sm">{error}</div>
      )}

      <form onSubmit={handleSubmit}>
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6 mb-6 space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Key Name <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              value={keyName}
              onChange={(e) => setKeyName(e.target.value)}
              required
              placeholder="API Key 이름을 입력하세요"
              className="w-full border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">사용 목적</label>
            <textarea
              value={purpose}
              onChange={(e) => setPurpose(e.target.value)}
              rows={2}
              placeholder="사용 목적을 입력하세요"
              className="w-full border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              사용 기간 <span className="text-red-500">*</span>
            </label>
            <div className="flex items-center gap-2 mb-2">
              <button type="button" onClick={() => handlePresetPeriod(3)}
                disabled={isPermanent || usagePeriodMode === 'custom'}
                className={`px-3 py-1.5 text-sm rounded-lg border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 ${isPermanent || usagePeriodMode === 'custom' ? 'opacity-40 cursor-not-allowed' : 'hover:bg-blue-50 dark:hover:bg-gray-600'}`}>
                3개월
              </button>
              <button type="button" onClick={() => handlePresetPeriod(6)}
                disabled={isPermanent || usagePeriodMode === 'custom'}
                className={`px-3 py-1.5 text-sm rounded-lg border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 ${isPermanent || usagePeriodMode === 'custom' ? 'opacity-40 cursor-not-allowed' : 'hover:bg-blue-50 dark:hover:bg-gray-600'}`}>
                6개월
              </button>
              <button type="button" onClick={() => handlePresetPeriod(9)}
                disabled={isPermanent || usagePeriodMode === 'custom'}
                className={`px-3 py-1.5 text-sm rounded-lg border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 ${isPermanent || usagePeriodMode === 'custom' ? 'opacity-40 cursor-not-allowed' : 'hover:bg-blue-50 dark:hover:bg-gray-600'}`}>
                9개월
              </button>
              <span className="text-gray-400 dark:text-gray-600 mx-1">|</span>
              <button type="button" onClick={handlePermanent}
                className={`px-3 py-1.5 text-sm rounded-lg border font-medium ${isPermanent ? 'bg-indigo-600 text-white border-indigo-600' : 'text-indigo-600 border-indigo-300 dark:border-indigo-500 dark:text-indigo-400 hover:bg-indigo-50 dark:hover:bg-indigo-900/30'}`}>
                영구
              </button>
              <span className="text-gray-400 dark:text-gray-600 mx-1">|</span>
              <label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300 cursor-pointer select-none">
                직접 선택
                <button type="button"
                  onClick={() => {
                    setUsagePeriodMode(usagePeriodMode === 'custom' ? 'preset' : 'custom');
                    setIsPermanent(false);
                  }}
                  className={`relative w-10 h-5 rounded-full transition-colors ${usagePeriodMode === 'custom' && !isPermanent ? 'bg-blue-600' : 'bg-gray-300 dark:bg-gray-600'}`}>
                  <span className={`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full shadow transition-transform ${usagePeriodMode === 'custom' && !isPermanent ? 'translate-x-5' : ''}`} />
                </button>
              </label>
            </div>
            {isPermanent ? (
              <div className="flex items-center gap-2 px-3 py-2 bg-indigo-50 dark:bg-indigo-900/30 border border-indigo-200 dark:border-indigo-700 rounded-lg">
                <span className="text-indigo-700 dark:text-indigo-300 text-sm font-medium">영구 사용 (만료일 없음)</span>
              </div>
            ) : (
              <div className="flex items-center gap-2">
                <input type="date" value={usageFromDate}
                  onChange={(e) => setUsageFromDate(e.target.value)}
                  readOnly={usagePeriodMode !== 'custom'}
                  className={`border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none ${usagePeriodMode !== 'custom' ? 'bg-gray-50 text-gray-500 dark:bg-gray-700 dark:text-gray-400' : 'bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100'}`} />
                <span className="text-gray-500 dark:text-gray-400">~</span>
                <input type="date" value={usageToDate}
                  onChange={(e) => setUsageToDate(e.target.value)}
                  readOnly={usagePeriodMode !== 'custom'}
                  className={`border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none ${usagePeriodMode !== 'custom' ? 'bg-gray-50 text-gray-500 dark:bg-gray-700 dark:text-gray-400' : 'bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100'}`} />
              </div>
            )}
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              서비스 IP <span className="text-red-500">*</span>
            </label>
            <input type="text" value={serviceIp}
              onChange={(e) => setServiceIp(e.target.value)}
              required placeholder="예: 192.168.1.100"
              className="w-full border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none" />
            <p className="text-xs text-gray-400 dark:text-gray-500 mt-1">발급받은 API Key로 프록시 서버에 요청하는 서비스 IP</p>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                서비스 용도 <span className="text-red-500">*</span>
              </label>
              <select value={servicePurpose}
                onChange={(e) => setServicePurpose(e.target.value)}
                required
                className="w-full border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none">
                <option value="">선택하세요</option>
                <option value="로컬 환경">로컬 환경</option>
                <option value="개발 서버">개발 서버</option>
                <option value="검증 서버">검증 서버</option>
                <option value="운영 서버">운영 서버</option>
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                하루 예상 요청량 <span className="text-red-500">*</span>
              </label>
              <select value={dailyRequestEstimate}
                onChange={(e) => setDailyRequestEstimate(e.target.value)}
                required
                className="w-full border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none">
                <option value="">선택하세요</option>
                <option value="100">100 이하</option>
                <option value="500">100~500</option>
                <option value="1000">500~1,000</option>
                <option value="5000">1,000~5,000</option>
                <option value="10000">5,000~10,000</option>
                <option value="50000">10,000 이상</option>
              </select>
            </div>
          </div>
        </div>

        {/* API Selection Section */}
        <div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-700 shadow mb-6 overflow-hidden">
          {/* Header bar */}
          <div className="flex items-center justify-between gap-4 px-5 py-3.5 border-b border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900">
            <div className="flex items-center gap-3">
              <label className="flex items-center gap-2 cursor-pointer" onClick={(e) => e.stopPropagation()}>
                <IndeterminateCheckbox
                  checked={allApisSelected}
                  indeterminate={!allApisSelected && someApisSelected}
                  onChange={handleToggleAll}
                  className="rounded"
                />
              </label>
              <h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">API 선택</h2>
              {selectedApiIds.size > 0 && (
                <span className="text-xs font-medium bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400 px-2.5 py-0.5 rounded-full">
                  {selectedApiIds.size}개 선택
                </span>
              )}
            </div>
            <div className="flex items-center gap-2">
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder="API 검색..."
                className="bg-gray-100 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg px-3 py-1.5 text-sm text-gray-900 dark:text-gray-100 placeholder-gray-400 dark:placeholder-gray-500 focus:ring-2 focus:ring-blue-500 focus:outline-none w-56"
              />
              {selectedApiIds.size > 0 && (
                <button
                  type="button"
                  onClick={handleClearSelection}
                  className="text-xs text-gray-500 dark:text-gray-400 hover:text-red-500 dark:hover:text-red-400 px-2 py-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
                >
                  선택 해제
                </button>
              )}
            </div>
          </div>

          {/* Domain cards */}
          <div className="p-4 space-y-3">
            {filteredDomainGroups.map((domainGroup) => {
              const isDomainExpanded = expandedDomains.has(domainGroup.domain);
              const domainApis = domainGroup.apis;
              const allDomainSelected = domainApis.length > 0 && domainApis.every((a) => selectedApiIds.has(a.apiId));
              const someDomainSelected = !allDomainSelected && domainApis.some((a) => selectedApiIds.has(a.apiId));
              const selectedCount = domainApis.filter((a) => selectedApiIds.has(a.apiId)).length;
              const hasSelections = selectedCount > 0;

              return (
                <div
                  key={domainGroup.domain}
                  className={`rounded-xl border overflow-hidden transition-colors ${hasSelections ? 'border-blue-300 dark:border-blue-700' : 'border-gray-200 dark:border-gray-700'}`}
                >
                  {/* Domain header */}
                  <div
                    className={`flex items-center justify-between px-5 py-3.5 cursor-pointer ${hasSelections ? 'bg-blue-50/50 dark:bg-blue-900/20' : 'bg-gray-50 dark:bg-gray-800/80'}`}
                    onClick={() => handleToggleDomain(domainGroup.domain)}
                  >
                    <div className="flex items-center gap-3">
                      <svg className={`h-4 w-4 text-gray-400 transition-transform ${isDomainExpanded ? 'rotate-90' : ''}`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                      </svg>
                      <label className="flex items-center cursor-pointer" onClick={(e) => e.stopPropagation()}>
                        <IndeterminateCheckbox
                          checked={allDomainSelected}
                          indeterminate={someDomainSelected}
                          onChange={() => handleToggleAllDomainApis(domainGroup.domain)}
                          className="rounded"
                        />
                      </label>
                      <span className="font-semibold text-gray-900 dark:text-gray-100">{/^[a-zA-Z\s\-_]+$/.test(domainGroup.domain) ? domainGroup.domain.toUpperCase() : domainGroup.domain}</span>
                      {selectedCount > 0 && (
                        <span className="text-xs font-medium bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400 px-2 py-0.5 rounded-full">
                          {selectedCount} selected
                        </span>
                      )}
                    </div>
                    <span className="text-xs font-medium bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400 px-2 py-0.5 rounded-full">
                      {domainApis.length}개 API
                    </span>
                  </div>

                  {/* API list */}
                  {isDomainExpanded && (
                    <div className="divide-y divide-gray-100 dark:divide-gray-700/50 bg-white dark:bg-gray-900">
                      {domainApis.map((api) => {
                        const isSelected = selectedApiIds.has(api.apiId);
                        return (
                          <div
                            key={api.apiId}
                            className={`flex items-start gap-3 px-5 py-3 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/30 ${isSelected ? 'bg-blue-50/50 dark:bg-blue-900/10' : ''}`}
                            onClick={() => handleToggleApi(api.apiId)}
                          >
                            <div className="flex items-center pt-0.5">
                              <input
                                type="checkbox"
                                checked={isSelected}
                                onChange={() => handleToggleApi(api.apiId)}
                                onClick={(e) => e.stopPropagation()}
                                className="rounded"
                              />
                            </div>
                            <div className="flex-1 min-w-0">
                              <p className="text-sm font-semibold text-gray-900 dark:text-gray-100 truncate">{api.apiName}</p>
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  )}
                </div>
              );
            })}
            {filteredDomainGroups.length === 0 && (
              <div className="px-6 py-8 text-center text-gray-400 dark:text-gray-500">
                {searchQuery.trim() ? '검색 결과가 없습니다.' : '등록된 API가 없습니다.'}
              </div>
            )}
          </div>
        </div>

        {/* Bottom sticky summary bar */}
        {selectedApiIds.size > 0 && (
          <div className="sticky bottom-4 z-10 mx-auto mb-4">
            <div className="bg-blue-600 dark:bg-blue-700 text-white rounded-xl px-5 py-3 shadow-lg flex items-center justify-between">
              <span className="text-sm font-medium">{selectedApiIds.size}개 API가 선택되었습니다</span>
              <button
                type="button"
                onClick={handleClearSelection}
                className="text-sm text-blue-200 hover:text-white transition-colors"
              >
                선택 해제
              </button>
            </div>
          </div>
        )}

        <div className="flex justify-end">
          <button
            type="submit"
            disabled={isSubmitting}
            className="bg-blue-600 hover:bg-blue-700 disabled:bg-blue-300 text-white px-6 py-2 rounded-lg text-sm font-medium"
          >
            {isSubmitting ? '신청 중...' : '신청하기'}
          </button>
        </div>
      </form>
    </div>
  );
};

export default KeyRequestPage;
