'use client';

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

import {
  getSkillHubDetail,
  getSkillHubVersion,
  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 type { SkillHubSearchItem, SkillHubVersionResponse } 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 || '';
}

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 [detailLoading, setDetailLoading] = 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);
    setDetailLoading(true);
    setError(null);
    try {
      const detail = await getSkillHubDetail(item.namespace, item.slug);
      setSelected(detail);
      const version = publishedVersion(detail);
      if (version) {
        setVersionDetail(await getSkillHubVersion(detail.namespace, detail.slug, version));
      }
    } catch (err: any) {
      setError(err.message || t('加载技能详情失败', 'Failed to load skill details'));
    } finally {
      setDetailLoading(false);
    }
  };

  const installSelected = async () => {
    if (!selected) return;
    setInstalling(true);
    setError(null);
    try {
      const result = await installSkillHubSkill(selected.namespace, selected.slug, 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 p-6">
      <div className="mx-auto mb-10 max-w-4xl">
        <form
          className="flex gap-3"
          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">
            {t('搜索', 'Search')}
          </Button>
        </form>
      </div>

      {error && (
        <Card className="mb-6 border-destructive">
          <CardContent className="flex items-center gap-2 pt-6 text-sm text-destructive">
            <AlertCircle className="h-4 w-4" />
            {error}
          </CardContent>
        </Card>
      )}

      {selected ? (
        <div className="space-y-5">
          <Button variant="ghost" onClick={() => setSelected(null)}>
            <ArrowLeft className="mr-2 h-4 w-4" />
            {t('返回搜索', 'Back to search')}
          </Button>
          <Card>
            <CardHeader>
              <div className="flex flex-wrap items-start justify-between gap-4">
                <div>
                  <div className="mb-2 flex items-center gap-2">
                    <Badge variant="outline">@{selected.namespace}</Badge>
                    {selected.installed && (
                      <Badge variant="secondary" className="gap-1">
                        <Check className="h-3 w-3" />
                        {t('已安装', 'Installed')}
                      </Badge>
                    )}
                  </div>
                  <CardTitle className="text-2xl">{selected.displayName || selected.slug}</CardTitle>
                  <p className="mt-3 max-w-3xl text-sm leading-6 text-muted-foreground">{selected.summary}</p>
                </div>
                <Button onClick={installSelected} disabled={installing || detailLoading}>
                  {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>
              </div>
            </CardHeader>
            <CardContent className="space-y-4">
              {detailLoading ? (
                <div className="flex justify-center py-10">
                  <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
                </div>
              ) : (
                <>
                  <div className="flex flex-wrap gap-2 text-sm text-muted-foreground">
                    <Badge variant="outline">v{publishedVersion(selected) || '-'}</Badge>
                    <span>{t('下载', 'Downloads')}: {selected.downloadCount || 0}</span>
                    <span>{t('收藏', 'Stars')}: {selected.starCount || 0}</span>
                  </div>
                  <div className="grid gap-4 lg:grid-cols-[minmax(0,1.2fr)_minmax(320px,0.8fr)]">
                    <div className="rounded-lg border border-border bg-muted/20 p-4">
                      <div className="mb-2 text-sm font-medium">SKILL.md</div>
                      <pre className="max-h-[520px] overflow-auto whitespace-pre-wrap text-xs">
                        {versionDetail?.detail?.parsedMetadataJson || t('暂无预览', 'No preview available')}
                      </pre>
                    </div>
                    <div className="rounded-lg border border-border bg-muted/20 p-4">
                      <div className="mb-3 text-sm font-medium">{t('版本文件', 'Version files')}</div>
                      <div className="space-y-2">
                        {(versionDetail?.files || []).map((file) => (
                          <div key={file.filePath} className="flex items-center justify-between gap-3 rounded-md bg-background px-3 py-2 text-xs">
                            <span className="break-all font-mono">{file.filePath}</span>
                            <span className="shrink-0 text-muted-foreground">{file.fileSize} B</span>
                          </div>
                        ))}
                      </div>
                    </div>
                  </div>
                </>
              )}
            </CardContent>
          </Card>
        </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="ml-4 text-sm font-medium text-muted-foreground">{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="cursor-pointer transition hover:border-primary" onClick={() => void openDetail(item)}>
                  <CardHeader>
                    <div className="flex items-start justify-between gap-3">
                      <CardTitle className="text-xl">{item.displayName || item.slug}</CardTitle>
                      <Badge variant="outline">@{item.namespace}</Badge>
                    </div>
                  </CardHeader>
                  <CardContent className="space-y-5">
                    <p className="line-clamp-3 min-h-[4.5rem] 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">v{publishedVersion(item) || '-'}</Badge>
                      <span>{item.downloadCount || 0}</span>
                      <span>{item.starCount || 0}</span>
                      {item.installed && <Badge variant="outline">{t('已安装', 'Installed')}</Badge>}
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          )}

          <div className="flex 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>
  );
}
