import { useState } from 'react';
import { useParams, Link } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { apiFetch } from '../lib/api';
import { useI18n } from '../lib/i18n';
import DocPreview from './tabs/DocPreview';
import ModuleManagement from './tabs/ModuleManagement';
import McpIntegration from './tabs/McpIntegration';
import ProjectSettings from './tabs/ProjectSettings';
import Badge from '../components/Badge';
import Skeleton from '../components/Skeleton';

type ProjectData = {
  id: string; name: string; description: string | null; baseUrl: string | null;
  openApiVersion: string;
  modules: Array<{ id: string; name: string; description: string | null; _count: { endpoints: number } }>;
  _count: { endpoints: number; modules: number };
};

const tabs = [
  { key: 'mcp', labelKey: 'dashboard.projectDetail.tabMcp', icon: 'M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1' },
  { key: 'docs', labelKey: 'dashboard.projectDetail.tabDocs', icon: 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z' },
  { key: 'modules', labelKey: 'dashboard.projectDetail.tabModules', icon: 'M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10' },
  { key: 'settings', labelKey: 'dashboard.projectDetail.tabSettings', icon: 'M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z' },
] as const;

type TabKey = (typeof tabs)[number]['key'];

export default function ProjectDetail() {
  const { id } = useParams<{ id: string }>();
  const [activeTab, setActiveTab] = useState<TabKey>('mcp');
  const { t } = useI18n();

  const { data: project, isLoading } = useQuery({
    queryKey: ['project', id],
    queryFn: () => apiFetch<ProjectData>(`/projects/${id}`),
  });

  if (isLoading) {
    return (
      <div className="space-y-6">
        <Skeleton className="h-4 w-28" />
        <div className="space-y-2">
          <Skeleton className="h-7 w-56" />
          <Skeleton className="h-4 w-80" />
        </div>
        <Skeleton className="h-10 w-96" />
        <Skeleton className="h-[300px] w-full" />
      </div>
    );
  }

  if (!project) {
    return (
      <div className="text-center py-20">
        <svg className="w-10 h-10 mx-auto text-text-muted mb-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}><path d="M9.75 9.75l4.5 4.5m0-4.5l-4.5 4.5M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
        <p className="text-text-muted text-sm">{t('dashboard.projectDetail.notFound')}</p>
        <Link to="/dashboard" className="text-accent hover:underline text-sm mt-2 inline-block">{t('dashboard.projectDetail.backToProjects')}</Link>
      </div>
    );
  }

  return (
    <div>
      {/* Breadcrumb */}
      <div className="flex items-center gap-1.5 text-[13px] text-text-muted mb-5">
        <Link to="/dashboard" className="hover:text-text-primary transition-colors">{t('dashboard.projectDetail.breadcrumbProjects')}</Link>
        <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}><path d="M9 5l7 7-7 7" /></svg>
        <span className="text-text-secondary font-medium">{project.name}</span>
      </div>

      {/* Header */}
      <div className="flex items-start justify-between mb-6">
        <div>
          <h2 className="text-xl font-semibold text-text-primary tracking-[-0.01em]">{project.name}</h2>
          {project.description && <p className="text-[13px] text-text-muted mt-1 max-w-xl">{project.description}</p>}
        </div>
        <div className="flex items-center gap-1.5 shrink-0 ml-4">
          <Badge>OpenAPI {project.openApiVersion}</Badge>
          <Badge>{project._count.endpoints} {t('common.endpoints')}</Badge>
        </div>
      </div>

      {/* Tabs */}
      <div className="flex gap-0.5 p-0.5 rounded-lg bg-bg-tertiary mb-6 max-w-fit border border-border-muted">
        {tabs.map((tab) => (
          <button
            key={tab.key}
            onClick={() => setActiveTab(tab.key)}
            className={`flex items-center gap-1.5 px-3 py-[6px] rounded-md text-[13px] font-medium transition-all duration-150 ${
              activeTab === tab.key
                ? 'bg-bg-elevated text-text-primary shadow-sm'
                : 'text-text-muted hover:text-text-secondary'
            }`}
          >
            <svg className="w-[14px] h-[14px]" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}><path d={tab.icon} /></svg>
            <span className="hidden sm:inline">{t(tab.labelKey)}</span>
          </button>
        ))}
      </div>

      {/* Content */}
      <div key={activeTab} className="animate-fade-in">
        {activeTab === 'docs' && <DocPreview projectId={project.id} />}
        {activeTab === 'modules' && <ModuleManagement projectId={project.id} />}
        {activeTab === 'mcp' && <McpIntegration project={project} />}
        {activeTab === 'settings' && <ProjectSettings project={{ ...project, _count: project._count }} />}
      </div>
    </div>
  );
}
