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';
import Button from '../../components/ui/Button';

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 preApiIds = searchParams.get('apiIds');

  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;
                }
              }
            }
          }

          // 신청함에서 일괄 전달된 apiIds 자동 선택
          if (preApiIds) {
            const aIds = preApiIds
              .split(',')
              .map((s) => Number(s.trim()))
              .filter((n) => !isNaN(n) && n > 0);
            if (aIds.length > 0) {
              const aIdSet = new Set(aIds);
              const domainsToExpand = new Set<string>();
              for (const service of catalogRes.data) {
                for (const domainGroup of service.domains) {
                  const hasMatch = domainGroup.apis.some((a) => aIdSet.has(a.apiId));
                  if (hasMatch) {
                    domainsToExpand.add(domainGroup.domain);
                  }
                }
              }
              setSelectedApiIds(aIdSet);
              setExpandedDomains(domainsToExpand);
            }
          }
        } else {
          setError(catalogRes.message || '카탈로그를 불러오는데 실패했습니다.');
        }
      } catch {
        setError('카탈로그를 불러오는데 실패했습니다.');
      } finally {
        setIsLoading(false);
      }
    };

    fetchData();
  }, [preApiId, preApiIds]);

  // 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-[var(--color-text-secondary)]">로딩 중...</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')}
              variant="primary"
            >
              내 키 목록으로 이동
            </Button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-7xl mx-auto">
      <h1 className="text-2xl font-bold text-[var(--color-text-primary)] 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-[var(--color-bg-surface)] rounded-lg shadow p-6 mb-6 space-y-4">
          <div>
            <label className="block text-sm font-medium text-[var(--color-text-primary)] 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-[var(--color-border-strong)] bg-[var(--color-bg-surface)] text-[var(--color-text-primary)] rounded-lg px-3 py-2 focus:ring-2 focus:ring-[var(--color-primary)] focus:outline-none"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-[var(--color-text-primary)] mb-1">사용 목적</label>
            <textarea
              value={purpose}
              onChange={(e) => setPurpose(e.target.value)}
              rows={2}
              placeholder="사용 목적을 입력하세요"
              className="w-full border border-[var(--color-border-strong)] bg-[var(--color-bg-surface)] text-[var(--color-text-primary)] rounded-lg px-3 py-2 focus:ring-2 focus:ring-[var(--color-primary)] focus:outline-none"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-[var(--color-text-primary)] 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-[var(--color-border-strong)] text-[var(--color-text-primary)] bg-[var(--color-bg-surface)] ${isPermanent || usagePeriodMode === 'custom' ? 'opacity-40 cursor-not-allowed' : 'hover:bg-[var(--color-bg-base)]'}`}>
                3개월
              </button>
              <button type="button" onClick={() => handlePresetPeriod(6)}
                disabled={isPermanent || usagePeriodMode === 'custom'}
                className={`px-3 py-1.5 text-sm rounded-lg border border-[var(--color-border-strong)] text-[var(--color-text-primary)] bg-[var(--color-bg-surface)] ${isPermanent || usagePeriodMode === 'custom' ? 'opacity-40 cursor-not-allowed' : 'hover:bg-[var(--color-bg-base)]'}`}>
                6개월
              </button>
              <button type="button" onClick={() => handlePresetPeriod(9)}
                disabled={isPermanent || usagePeriodMode === 'custom'}
                className={`px-3 py-1.5 text-sm rounded-lg border border-[var(--color-border-strong)] text-[var(--color-text-primary)] bg-[var(--color-bg-surface)] ${isPermanent || usagePeriodMode === 'custom' ? 'opacity-40 cursor-not-allowed' : 'hover:bg-[var(--color-bg-base)]'}`}>
                9개월
              </button>
              <span className="text-[var(--color-text-tertiary)] mx-1">|</span>
              <Button type="button" size="sm" onClick={handlePermanent}
                variant={isPermanent ? 'primary' : 'outline'}>
                영구
              </Button>
              <span className="text-[var(--color-text-tertiary)] mx-1">|</span>
              <label className="flex items-center gap-2 text-sm text-[var(--color-text-primary)] 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-[var(--color-primary)] dark:bg-[var(--color-primary-600)]' : 'bg-[var(--color-border-strong)]'}`}>
                  <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 border border-indigo-200 rounded-lg">
                <span className="text-indigo-700 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-[var(--color-border-strong)] rounded-lg px-3 py-2 focus:ring-2 focus:ring-[var(--color-primary)] focus:outline-none ${usagePeriodMode !== 'custom' ? 'bg-[var(--color-bg-base)] text-[var(--color-text-secondary)]' : 'bg-[var(--color-bg-surface)] text-[var(--color-text-primary)]'}`} />
                <span className="text-[var(--color-text-secondary)]">~</span>
                <input type="date" value={usageToDate}
                  onChange={(e) => setUsageToDate(e.target.value)}
                  readOnly={usagePeriodMode !== 'custom'}
                  className={`border border-[var(--color-border-strong)] rounded-lg px-3 py-2 focus:ring-2 focus:ring-[var(--color-primary)] focus:outline-none ${usagePeriodMode !== 'custom' ? 'bg-[var(--color-bg-base)] text-[var(--color-text-secondary)]' : 'bg-[var(--color-bg-surface)] text-[var(--color-text-primary)]'}`} />
              </div>
            )}
          </div>

          <div>
            <label className="block text-sm font-medium text-[var(--color-text-primary)] 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-[var(--color-border-strong)] bg-[var(--color-bg-surface)] text-[var(--color-text-primary)] rounded-lg px-3 py-2 focus:ring-2 focus:ring-[var(--color-primary)] focus:outline-none" />
            <p className="text-xs text-[var(--color-text-tertiary)] mt-1">발급받은 API Key로 프록시 서버에 요청하는 서비스 IP</p>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-[var(--color-text-primary)] mb-1">
                서비스 용도 <span className="text-red-500">*</span>
              </label>
              <select value={servicePurpose}
                onChange={(e) => setServicePurpose(e.target.value)}
                required
                className="w-full border border-[var(--color-border-strong)] bg-[var(--color-bg-surface)] text-[var(--color-text-primary)] rounded-lg px-3 py-2 focus:ring-2 focus:ring-[var(--color-primary)] 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-[var(--color-text-primary)] mb-1">
                하루 예상 요청량 <span className="text-red-500">*</span>
              </label>
              <select value={dailyRequestEstimate}
                onChange={(e) => setDailyRequestEstimate(e.target.value)}
                required
                className="w-full border border-[var(--color-border-strong)] bg-[var(--color-bg-surface)] text-[var(--color-text-primary)] rounded-lg px-3 py-2 focus:ring-2 focus:ring-[var(--color-primary)] 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-[var(--color-bg-surface)] rounded-xl border border-[var(--color-border)] shadow mb-6 overflow-hidden">
          {/* Header bar */}
          <div className="flex items-center justify-between gap-4 px-5 py-3.5 border-b border-[var(--color-border)] bg-[var(--color-bg-surface)]">
            <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-[var(--color-text-primary)]">API 선택</h2>
              {selectedApiIds.size > 0 && (
                <span className="text-xs font-medium bg-blue-100 text-[var(--color-primary)] 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-[var(--color-bg-base)] border border-[var(--color-border)] rounded-lg px-3 py-1.5 text-sm text-[var(--color-text-primary)] placeholder-[var(--color-text-tertiary)] focus:ring-2 focus:ring-[var(--color-primary)] focus:outline-none w-56"
              />
              {selectedApiIds.size > 0 && (
                <button
                  type="button"
                  onClick={handleClearSelection}
                  className="text-xs text-[var(--color-text-secondary)] hover:text-red-500 px-2 py-1.5 rounded-lg hover:bg-[var(--color-bg-base)] 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' : 'border-[var(--color-border)]'}`}
                >
                  {/* Domain header */}
                  <div
                    className={`flex items-center justify-between px-5 py-3.5 cursor-pointer ${hasSelections ? 'bg-blue-50/50' : 'bg-[var(--color-bg-base)]'}`}
                    onClick={() => handleToggleDomain(domainGroup.domain)}
                  >
                    <div className="flex items-center gap-3">
                      <svg className={`h-4 w-4 text-[var(--color-text-tertiary)] 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-[var(--color-text-primary)]">{/^[a-zA-Z\s\-_]+$/.test(domainGroup.domain) ? domainGroup.domain.toUpperCase() : domainGroup.domain}</span>
                      {selectedCount > 0 && (
                        <span className="text-xs font-medium bg-blue-100 text-[var(--color-primary)] px-2 py-0.5 rounded-full">
                          {selectedCount} selected
                        </span>
                      )}
                    </div>
                    <span className="text-xs font-medium bg-[var(--color-bg-base)] text-[var(--color-text-secondary)] px-2 py-0.5 rounded-full">
                      {domainApis.length}개 API
                    </span>
                  </div>

                  {/* API list */}
                  {isDomainExpanded && (
                    <div className="divide-y divide-[var(--color-border)] bg-[var(--color-bg-surface)]">
                      {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-[var(--color-bg-base)] ${isSelected ? 'bg-blue-50/50' : ''}`}
                            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-[var(--color-text-primary)] truncate">{api.apiName}</p>
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  )}
                </div>
              );
            })}
            {filteredDomainGroups.length === 0 && (
              <div className="px-6 py-8 text-center text-[var(--color-text-tertiary)]">
                {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-[var(--color-primary)] dark:bg-[var(--color-primary-600)] 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}
            variant="primary"
          >
            {isSubmitting ? '신청 중...' : '신청하기'}
          </Button>
        </div>
      </form>
    </div>
  );
};

export default KeyRequestPage;
