import { useState, useEffect, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import type { ServiceInfo, ServiceApi, CreateServiceApiRequest } from '../../types/service';
import { getServices, getServiceApis, createServiceApi } from '../../services/serviceService';
import Button from '../../components/ui/Button';
import Badge from '../../components/ui/Badge';

const METHOD_COLOR: Record<string, string> = {
  GET: 'bg-green-50 text-green-700 dark:bg-green-500/15 dark:text-green-400',
  POST: 'bg-blue-50 text-blue-700 dark:bg-blue-500/15 dark:text-blue-400',
  PUT: 'bg-amber-50 text-amber-700 dark:bg-amber-500/15 dark:text-amber-400',
  DELETE: 'bg-red-50 text-red-700 dark:bg-red-500/15 dark:text-red-400',
};

interface FlatApi extends ServiceApi {
  serviceName: string;
}

const ApisPage = () => {
  const navigate = useNavigate();

  const [services, setServices] = useState<ServiceInfo[]>([]);
  const [allApis, setAllApis] = useState<FlatApi[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Filter state
  const [filterServiceId, setFilterServiceId] = useState<number | 'all'>('all');
  const [searchText, setSearchText] = useState('');
  const [filterActive, setFilterActive] = useState<'all' | 'active' | 'inactive'>('all');

  // Create API modal state
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [modalError, setModalError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [modalServiceId, setModalServiceId] = useState<number | ''>('');
  const [modalMethod, setModalMethod] = useState('GET');
  const [modalPath, setModalPath] = useState('');
  const [modalName, setModalName] = useState('');
  const [modalDomain, setModalDomain] = useState('');
  const [modalSection, setModalSection] = useState('');
  const [modalDescription, setModalDescription] = useState('');

  const fetchAll = async () => {
    try {
      setLoading(true);
      setError(null);

      const svcRes = await getServices();
      if (!svcRes.success || !svcRes.data) {
        setError(svcRes.message || '서비스 목록을 불러오는데 실패했습니다.');
        return;
      }
      const loadedServices = svcRes.data;
      setServices(loadedServices);

      if (loadedServices.length === 0) {
        setAllApis([]);
        return;
      }

      const results = await Promise.allSettled(
        loadedServices.map((svc) => getServiceApis(svc.serviceId)),
      );

      const flat: FlatApi[] = [];
      results.forEach((result, idx) => {
        if (result.status === 'fulfilled' && result.value.success && result.value.data) {
          result.value.data.forEach((api) => {
            flat.push({ ...api, serviceName: loadedServices[idx].serviceName });
          });
        }
      });

      setAllApis(flat);
    } catch {
      setError('API 목록을 불러오는데 실패했습니다.');
    } finally {
      setLoading(false);
    }
  };

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

  const filteredApis = useMemo(() => {
    return allApis.filter((api) => {
      if (filterServiceId !== 'all' && api.serviceId !== filterServiceId) return false;
      if (filterActive === 'active' && !api.isActive) return false;
      if (filterActive === 'inactive' && api.isActive) return false;
      if (searchText.trim()) {
        const q = searchText.trim().toLowerCase();
        if (!api.apiName.toLowerCase().includes(q) && !api.apiPath.toLowerCase().includes(q)) {
          return false;
        }
      }
      return true;
    });
  }, [allApis, filterServiceId, filterActive, searchText]);

  const handleOpenModal = () => {
    setModalServiceId(services.length > 0 ? services[0].serviceId : '');
    setModalMethod('GET');
    setModalPath('');
    setModalName('');
    setModalDomain('');
    setModalSection('');
    setModalDescription('');
    setModalError(null);
    setIsModalOpen(true);
  };

  const handleCloseModal = () => {
    setIsModalOpen(false);
    setModalError(null);
  };

  const handleModalSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (modalServiceId === '') return;
    setModalError(null);
    setSubmitting(true);

    try {
      const req: CreateServiceApiRequest = {
        apiMethod: modalMethod,
        apiPath: modalPath,
        apiName: modalName,
        apiDomain: modalDomain || undefined,
        apiSection: modalSection || undefined,
        description: modalDescription || undefined,
      };
      const res = await createServiceApi(modalServiceId as number, req);
      if (!res.success) {
        setModalError(res.message || 'API 생성에 실패했습니다.');
        return;
      }
      handleCloseModal();
      await fetchAll();
      if (res.data) {
        navigate(`/admin/apis/${res.data.serviceId}/${res.data.apiId}`);
      }
    } catch {
      setModalError('API 생성에 실패했습니다.');
    } finally {
      setSubmitting(false);
    }
  };

  if (loading) {
    return (
      <div className="max-w-7xl mx-auto text-center py-10 text-[var(--color-text-secondary)]">
        로딩 중...
      </div>
    );
  }

  return (
    <div className="max-w-7xl mx-auto">
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold text-[var(--color-text-primary)]">API 관리</h1>
        <Button onClick={handleOpenModal}>API 생성</Button>
      </div>

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

      {/* Filters */}
      <div className="flex flex-wrap gap-3 mb-4">
        <select
          value={filterServiceId}
          onChange={(e) =>
            setFilterServiceId(e.target.value === 'all' ? 'all' : Number(e.target.value))
          }
          className="px-3 py-2 rounded-lg border border-[var(--color-border-strong)] bg-[var(--color-bg-surface)] text-[var(--color-text-primary)] text-sm focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)]"
        >
          <option value="all">전체 서비스</option>
          {services.map((svc) => (
            <option key={svc.serviceId} value={svc.serviceId}>
              {svc.serviceName}
            </option>
          ))}
        </select>

        <input
          type="text"
          value={searchText}
          onChange={(e) => setSearchText(e.target.value)}
          placeholder="API명, Path 검색"
          className="px-3 py-2 rounded-lg border border-[var(--color-border-strong)] bg-[var(--color-bg-surface)] text-[var(--color-text-primary)] text-sm focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] min-w-[200px]"
        />

        <div className="flex rounded-lg border border-[var(--color-border-strong)] overflow-hidden text-sm">
          {(['all', 'active', 'inactive'] as const).map((v) => (
            <button
              key={v}
              onClick={() => setFilterActive(v)}
              className={`px-3 py-2 font-medium ${
                filterActive === v
                  ? 'bg-[var(--color-primary)] text-white dark:bg-[var(--color-primary-600)]'
                  : 'bg-[var(--color-bg-surface)] text-[var(--color-text-primary)] hover:bg-[var(--color-bg-base)]'
              }`}
            >
              {v === 'all' ? '전체' : v === 'active' ? 'Active' : 'Inactive'}
            </button>
          ))}
        </div>
      </div>

      {/* Table */}
      <div className="overflow-x-auto bg-[var(--color-bg-surface)] rounded-lg shadow">
        <table className="w-full divide-y divide-[var(--color-border)] text-sm">
          <thead className="bg-[var(--color-bg-base)]">
            <tr>
              <th className="px-4 py-3 text-left font-medium text-[var(--color-text-secondary)]">서비스</th>
              <th className="px-4 py-3 text-left font-medium text-[var(--color-text-secondary)]">Method</th>
              <th className="px-4 py-3 text-left font-medium text-[var(--color-text-secondary)]">Path</th>
              <th className="px-4 py-3 text-left font-medium text-[var(--color-text-secondary)]">API명</th>
              <th className="px-4 py-3 text-left font-medium text-[var(--color-text-secondary)]">Domain</th>
              <th className="px-4 py-3 text-left font-medium text-[var(--color-text-secondary)]">Section</th>
              <th className="px-4 py-3 text-left font-medium text-[var(--color-text-secondary)]">Active</th>
              <th className="px-4 py-3 text-left font-medium text-[var(--color-text-secondary)]">명세</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-[var(--color-border)]">
            {filteredApis.map((api) => (
              <tr
                key={`${api.serviceId}-${api.apiId}`}
                onClick={() => navigate(`/admin/apis/${api.serviceId}/${api.apiId}`)}
                className="cursor-pointer hover:bg-[var(--color-bg-base)]"
              >
                <td className="px-4 py-3 text-[var(--color-text-primary)]">{api.serviceName}</td>
                <td className="px-4 py-3">
                  <Badge className={METHOD_COLOR[api.apiMethod] ?? ''}>
                    {api.apiMethod}
                  </Badge>
                </td>
                <td className="px-4 py-3 font-mono text-[var(--color-text-primary)] truncate max-w-[240px]">
                  {api.apiPath}
                </td>
                <td className="px-4 py-3 text-[var(--color-text-primary)]">{api.apiName}</td>
                <td className="px-4 py-3 text-[var(--color-text-secondary)]">{api.apiDomain || '-'}</td>
                <td className="px-4 py-3 text-[var(--color-text-secondary)]">{api.apiSection || '-'}</td>
                <td className="px-4 py-3">
                  <Badge variant={api.isActive ? 'success' : 'danger'}>
                    {api.isActive ? 'Active' : 'Inactive'}
                  </Badge>
                </td>
                <td className="px-4 py-3">
                  <span className="text-[var(--color-text-tertiary)]">-</span>
                </td>
              </tr>
            ))}
            {filteredApis.length === 0 && (
              <tr>
                <td colSpan={8} className="px-4 py-8 text-center text-[var(--color-text-tertiary)]">
                  등록된 API가 없습니다
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      {/* Create API Modal */}
      {isModalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
          <div className="bg-[var(--color-bg-surface)] rounded-xl shadow-xl w-full max-w-lg mx-4">
            <div className="flex items-center justify-between px-6 py-4 border-b border-[var(--color-border)]">
              <h2 className="text-lg font-semibold text-[var(--color-text-primary)]">API 생성</h2>
              <Button variant="ghost" size="sm" onClick={handleCloseModal} className="text-xl font-bold leading-none px-2">
                ×
              </Button>
            </div>

            <form onSubmit={handleModalSubmit} className="px-6 py-4 space-y-4">
              {modalError && (
                <div className="p-3 bg-red-50 text-red-700 rounded-lg text-sm">
                  {modalError}
                </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={modalServiceId}
                  onChange={(e) => setModalServiceId(Number(e.target.value))}
                  required
                  className="w-full px-3 py-2 rounded-lg border border-[var(--color-border-strong)] bg-[var(--color-bg-surface)] text-[var(--color-text-primary)] text-sm focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)]"
                >
                  {services.map((svc) => (
                    <option key={svc.serviceId} value={svc.serviceId}>
                      {svc.serviceName}
                    </option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium text-[var(--color-text-primary)] mb-1">
                  Method <span className="text-red-500">*</span>
                </label>
                <select
                  value={modalMethod}
                  onChange={(e) => setModalMethod(e.target.value)}
                  className="w-full px-3 py-2 rounded-lg border border-[var(--color-border-strong)] bg-[var(--color-bg-surface)] text-[var(--color-text-primary)] text-sm focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)]"
                >
                  {['GET', 'POST', 'PUT', 'DELETE'].map((m) => (
                    <option key={m} value={m}>{m}</option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium text-[var(--color-text-primary)] mb-1">
                  API Path <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  value={modalPath}
                  onChange={(e) => setModalPath(e.target.value)}
                  required
                  placeholder="/api/v1/example"
                  className="w-full px-3 py-2 rounded-lg border border-[var(--color-border-strong)] bg-[var(--color-bg-surface)] text-[var(--color-text-primary)] text-sm font-mono focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)]"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-[var(--color-text-primary)] mb-1">
                  API명 <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  value={modalName}
                  onChange={(e) => setModalName(e.target.value)}
                  required
                  placeholder="API 이름"
                  className="w-full px-3 py-2 rounded-lg border border-[var(--color-border-strong)] bg-[var(--color-bg-surface)] text-[var(--color-text-primary)] text-sm focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)]"
                />
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-sm font-medium text-[var(--color-text-primary)] mb-1">
                    Domain
                  </label>
                  <input
                    type="text"
                    value={modalDomain}
                    onChange={(e) => setModalDomain(e.target.value)}
                    placeholder="도메인 (선택)"
                    className="w-full px-3 py-2 rounded-lg border border-[var(--color-border-strong)] bg-[var(--color-bg-surface)] text-[var(--color-text-primary)] text-sm focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)]"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-[var(--color-text-primary)] mb-1">
                    Section
                  </label>
                  <input
                    type="text"
                    value={modalSection}
                    onChange={(e) => setModalSection(e.target.value)}
                    placeholder="섹션 (선택)"
                    className="w-full px-3 py-2 rounded-lg border border-[var(--color-border-strong)] bg-[var(--color-bg-surface)] text-[var(--color-text-primary)] text-sm focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)]"
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-[var(--color-text-primary)] mb-1">
                  설명
                </label>
                <textarea
                  value={modalDescription}
                  onChange={(e) => setModalDescription(e.target.value)}
                  rows={3}
                  placeholder="API 설명 (선택)"
                  className="w-full px-3 py-2 rounded-lg border border-[var(--color-border-strong)] bg-[var(--color-bg-surface)] text-[var(--color-text-primary)] text-sm focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] resize-none"
                />
              </div>

              <div className="flex justify-end gap-3 pt-2">
                <Button type="button" variant="outline" onClick={handleCloseModal}>
                  취소
                </Button>
                <Button type="submit" disabled={submitting}>
                  {submitting ? '생성 중...' : '생성'}
                </Button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};

export default ApisPage;
