'use client';

import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { AlertCircle, ArrowLeft, Check, Download, Loader2, Search, Star } from 'lucide-react';

import {
  getSkillHubFile,
  getSkillHubDetail,
  getSkillHubVersion,
  getSkillHubVersions,
  installSkillHubSkill,
  searchSkillHubSkills,
} from '@/lib/api';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { SkillDetailView } from '@/components/skills/SkillDetailView';
import type { SkillFileContent, SkillHubSearchItem, SkillHubVersionResponse, SkillVersionRef } from '@/types';
import { pickAppText } from '@/lib/i18n/core';
import { useAppI18n } from '@/lib/i18n/provider';

type SortMode = 'relevance' | 'downloads' | 'newest';

function publishedVersion(skill: SkillHubSearchItem | null): string {
  return skill?.publishedVersion?.version || skill?.headlineVersion?.version || '';
}

function readmeFromVersion(version: SkillHubVersionResponse | null): string {
  const raw = version?.detail?.parsedMetadataJson;
  if (!raw) return '';
  try {
    const parsed = JSON.parse(raw);
    if (parsed && typeof parsed.body === 'string') {
      return parsed.body;
    }
  } catch {
    // keep empty fallback
  }
  return '';
}

export default function MarketplacePage() {
  const { locale } = useAppI18n();
  const t = useCallback((zh: string, en: string) => pickAppText(locale, zh, en), [locale]);
  const [query, setQuery] = useState('');
  const [sort, setSort] = useState<SortMode>('newest');
  const [starredOnly, setStarredOnly] = useState(false);
  const [page, setPage] = useState(0);
  const [items, setItems] = useState<SkillHubSearchItem[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [selected, setSelected] = useState<SkillHubSearchItem | null>(null);
  const [versionDetail, setVersionDetail] = useState<SkillHubVersionResponse | null>(null);
  const [versions, setVersions] = useState<SkillVersionRef[]>([]);
  const [selectedVersion, setSelectedVersion] = useState('');
  const [readmeContent, setReadmeContent] = useState('');
  const [selectedFile, setSelectedFile] = useState<SkillFileContent | null>(null);
  const [detailLoading, setDetailLoading] = useState(false);
  const [versionLoading, setVersionLoading] = useState(false);
  const [fileLoading, setFileLoading] = useState(false);
  const [installing, setInstalling] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const result = await searchSkillHubSkills({ q: query, sort, page, size: 12 });
      const nextItems = Array.isArray(result.items) ? result.items : [];
      setItems(starredOnly ? nextItems.filter((item) => (item.starCount || 0) > 0) : nextItems);
      setTotal(result.total || 0);
    } catch (err: any) {
      setError(err.message || t('加载 SkillHub 失败', 'Failed to load SkillHub'));
    } finally {
      setLoading(false);
    }
  }, [page, query, sort, starredOnly, t]);

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

  const openDetail = async (item: SkillHubSearchItem) => {
    setSelected(item);
    setVersionDetail(null);
    setVersions([]);
    setSelectedVersion('');
    setReadmeContent('');
    setSelectedFile(null);
    setDetailLoading(true);
    setError(null);
    try {
      const detail = await getSkillHubDetail(item.namespace, item.slug);
      setSelected(detail);
      const version = publishedVersion(detail);
      const versionList = await getSkillHubVersions(detail.namespace, detail.slug).catch(() => ({
        items: version ? [{ version, status: detail.publishedVersion?.status || detail.headlineVersion?.status }] : [],
        total: version ? 1 : 0,
        page: 0,
        size: 1,
      }));
      setVersions(versionList.items || []);
      if (version) {
        await loadVersion(detail, version);
      }
    } catch (err: any) {
      setError(err.message || t('加载技能详情失败', 'Failed to load skill details'));
    } finally {
      setDetailLoading(false);
    }
  };

  const loadVersion = async (skill: SkillHubSearchItem, version: string) => {
    setVersionLoading(true);
    setSelectedVersion(version);
    setSelectedFile(null);
    try {
      const nextVersion = await getSkillHubVersion(skill.namespace, skill.slug, version);
      setVersionDetail(nextVersion);
      const readme = await getSkillHubFile(skill.namespace, skill.slug, version, 'SKILL.md')
        .then((file) => file.content || '')
        .catch(() => readmeFromVersion(nextVersion));
      setReadmeContent(readme);
    } finally {
      setVersionLoading(false);
    }
  };

  const openVersion = async (version: string) => {
    if (!selected || selectedVersion === version) return;
    setError(null);
    try {
      await loadVersion(selected, version);
    } catch (err: any) {
      setError(err.message || t('加载技能版本失败', 'Failed to load skill version'));
    }
  };

  const openFile = async (filePath: string) => {
    if (!selected || !selectedVersion) return;
    setFileLoading(true);
    setError(null);
    try {
      setSelectedFile(await getSkillHubFile(selected.namespace, selected.slug, selectedVersion, filePath));
    } catch (err: any) {
      setError(err.message || t('加载文件失败', 'Failed to load file'));
    } finally {
      setFileLoading(false);
    }
  };

  const installSelected = async () => {
    if (!selected) return;
    setInstalling(true);
    setError(null);
    try {
      const result = await installSkillHubSkill(selected.namespace, selected.slug, selectedVersion || publishedVersion(selected));
      setSelected({ ...selected, installed: true, installed_version: result.version });
      await load();
    } catch (err: any) {
      setError(err.message || t('安装技能失败', 'Failed to install skill'));
    } finally {
      setInstalling(false);
    }
  };

  const totalPages = useMemo(() => Math.max(1, Math.ceil(total / 12)), [total]);

  return (
    <div className="mx-auto max-w-7xl space-y-6 p-4 sm:p-6">
      <div className="mx-auto max-w-4xl space-y-5">
        <div className="text-center">
          <h1 className="text-2xl font-bold tracking-normal sm:text-3xl">
            {t('市场', 'Marketplace')}
          </h1>
          <p className="mt-2 text-sm leading-6 text-muted-foreground">
            {t('搜索、查看并安装 SkillHub 技能。', 'Search, inspect, and install SkillHub skills.')}
          </p>
        </div>
        <form
          className="flex flex-col gap-3 sm:flex-row"
          onSubmit={(event) => {
            event.preventDefault();
            setPage(0);
            void load();
          }}
        >
          <div className="relative flex-1">
            <Search className="absolute left-4 top-1/2 h-5 w-5 -translate-y-1/2 text-muted-foreground" />
            <Input
              value={query}
              onChange={(event) => setQuery(event.target.value)}
              placeholder={t('搜索技能...', 'Search skills...')}
              className="h-14 rounded-2xl pl-12 text-base"
            />
          </div>
          <Button type="submit" className="h-14 rounded-2xl px-10 text-base sm:w-auto">
            {t('搜索', 'Search')}
          </Button>
        </form>
      </div>

      {error && (
        <Card className="mb-6 border-destructive">
          <CardContent className="flex items-start gap-2 pt-6 text-sm text-destructive">
            <AlertCircle className="mt-0.5 h-4 w-4 shrink-0" />
            <span className="min-w-0 break-words">{error}</span>
          </CardContent>
        </Card>
      )}

      {selected ? (
        <div className="space-y-5">
          <Button
            variant="ghost"
            className="h-11"
            onClick={() => {
              setSelected(null);
              setVersionDetail(null);
              setVersions([]);
              setSelectedVersion('');
              setReadmeContent('');
              setSelectedFile(null);
            }}
          >
            <ArrowLeft className="mr-2 h-4 w-4" />
            {t('返回搜索', 'Back to search')}
          </Button>
          {detailLoading ? (
            <Card>
              <CardContent className="flex justify-center py-16">
                <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
              </CardContent>
            </Card>
          ) : (
            <SkillDetailView
              title={selected.displayName || selected.slug}
              summary={selected.summary}
              currentVersion={selectedVersion || publishedVersion(selected)}
              versions={versions.length > 0 ? versions : [{ version: selectedVersion || publishedVersion(selected) }]}
              files={versionDetail?.files || []}
              content={readmeContent || readmeFromVersion(versionDetail)}
              selectedFile={selectedFile}
              loadingFile={fileLoading}
              loadingVersion={versionLoading}
              onSelectVersion={(version) => void openVersion(version)}
              onOpenFile={(filePath) => void openFile(filePath)}
              badges={
                <>
                  <Badge variant="outline" className="max-w-full break-all">@{selected.namespace}</Badge>
                  <Badge variant="outline">{t('下载', 'Downloads')}: {selected.downloadCount || 0}</Badge>
                  <Badge variant="outline">{t('收藏', 'Stars')}: {selected.starCount || 0}</Badge>
                  {selected.installed && (
                    <Badge variant="secondary" className="gap-1">
                      <Check className="h-3 w-3" />
                      {t('已安装', 'Installed')}
                    </Badge>
                  )}
                </>
              }
              actions={
                <Button className="h-11" onClick={installSelected} disabled={installing || detailLoading || versionLoading}>
                  {installing ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Download className="mr-2 h-4 w-4" />}
                  {selected.installed ? t('重新安装/更新', 'Reinstall/update') : t('安装', 'Install')}
                </Button>
              }
              labels={{
                overview: t('说明', 'Overview'),
                files: t('文件', 'Files'),
                versions: t('版本', 'Versions'),
                noReadme: t('暂无说明', 'No overview available'),
                noFiles: t('暂无文件', 'No files'),
                selectFile: t('选择一个文件查看详情', 'Select a file to view details'),
                binaryFile: t('二进制文件暂不预览', 'Binary file preview is not available'),
                current: t('当前', 'Current'),
                size: t('大小', 'Size'),
              }}
            />
          )}
        </div>
      ) : (
        <div className="space-y-6">
          <div className="flex flex-wrap items-center gap-3">
            <span className="text-sm font-medium text-muted-foreground">{t('排序：', 'Sort:')}</span>
            {([
              ['relevance', t('相关性', 'Relevance')],
              ['downloads', t('下载量', 'Downloads')],
              ['newest', t('最新', 'Newest')],
            ] as Array<[SortMode, string]>).map(([value, label]) => (
              <Button key={value} size="sm" variant={sort === value ? 'default' : 'outline'} onClick={() => { setSort(value); setPage(0); }}>
                {label}
              </Button>
            ))}
            <span className="text-sm font-medium text-muted-foreground sm:ml-4">{t('筛选：', 'Filter:')}</span>
            <Button size="sm" variant={starredOnly ? 'default' : 'outline'} onClick={() => setStarredOnly((value) => !value)}>
              <Star className="mr-2 h-4 w-4" />
              {t('只看已收藏', 'Starred only')}
            </Button>
          </div>

          {loading ? (
            <div className="flex justify-center py-20">
              <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
            </div>
          ) : (
            <div className="grid gap-5 md:grid-cols-2 xl:grid-cols-3">
              {items.map((item) => (
                <Card key={`${item.namespace}/${item.slug}`} className="overflow-hidden transition hover:border-primary">
                  <button
                    type="button"
                    className="block h-full w-full text-left"
                    onClick={() => void openDetail(item)}
                  >
                    <CardHeader>
                      <div className="flex flex-col items-start gap-3 sm:flex-row sm:justify-between">
                        <CardTitle className="min-w-0 break-words text-xl">{item.displayName || item.slug}</CardTitle>
                        <Badge variant="outline" className="max-w-full break-all">@{item.namespace}</Badge>
                      </div>
                    </CardHeader>
                    <CardContent className="space-y-5">
                      <p className="line-clamp-3 min-h-[4.5rem] break-words text-sm leading-6 text-muted-foreground">{item.summary}</p>
                      <div className="flex flex-wrap items-center gap-3 text-sm text-muted-foreground">
                        <Badge variant="secondary" className="max-w-full break-all">v{publishedVersion(item) || '-'}</Badge>
                        <span>{item.downloadCount || 0}</span>
                        <span>{item.starCount || 0}</span>
                        {item.installed && <Badge variant="outline">{t('已安装', 'Installed')}</Badge>}
                      </div>
                    </CardContent>
                  </button>
                </Card>
              ))}
            </div>
          )}

          <div className="flex flex-wrap items-center justify-center gap-3">
            <Button variant="outline" disabled={page <= 0} onClick={() => setPage((value) => Math.max(0, value - 1))}>
              {t('上一页', 'Previous')}
            </Button>
            <span className="text-sm text-muted-foreground">{page + 1} / {totalPages}</span>
            <Button variant="outline" disabled={page + 1 >= totalPages} onClick={() => setPage((value) => value + 1)}>
              {t('下一页', 'Next')}
            </Button>
          </div>
        </div>
      )}
    </div>
  );
}
