import React, { useState, useEffect } from 'react';
import type { Asset, Category } from '../../../types';
import { apiClient } from '../../../lib/api-client';
import { Cpu, Terminal, Brain, Server, Search, Download, Calendar, User, Tag, HelpCircle, X } from 'lucide-react';
import { useToast } from '../../../hooks/use-toast';

const GithubIcon: React.FC<{ className?: string }> = ({ className }) => (
  <svg
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
    strokeLinecap="round"
    strokeLinejoin="round"
    className={className}
  >
    <path d="M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4" />
    <path d="M9 18c-4.51 2-5-2-7-2" />
  </svg>
);

export const AssetExplorer: React.FC = () => {
  const { success, error } = useToast();
  const [assets, setAssets] = useState<Asset[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [loading, setLoading] = useState(true);

  // Filter state
  const [selectedCategory, setSelectedCategory] = useState<string>('all');
  const [selectedSubcategory, setSelectedSubcategory] = useState<string>('all');
  const [searchQuery, setSearchQuery] = useState('');
  
  // Selected asset details modal state
  const [selectedAsset, setSelectedAsset] = useState<Asset | null>(null);

  const fetchAssets = async () => {
    setLoading(true);
    try {
      const response = await apiClient.get<Asset[]>('/assets', {
        params: {
          categoryId: selectedCategory,
          subcategory: selectedSubcategory,
          search: searchQuery
        }
      });
      setAssets(response.data);
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  const fetchCategories = async () => {
    try {
      const response = await apiClient.get<Category[]>('/categories');
      setCategories(response.data);
    } catch (err) {
      console.error(err);
    }
  };

  // Trigger search and filters
  useEffect(() => {
    fetchAssets();
  }, [selectedCategory, selectedSubcategory, searchQuery]);

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

  const handleDownload = async (asset: Asset) => {
    success('Starting download', `Downloading ${asset.title}...`);
    try {
      const updatedAsset = { ...asset, downloadsCount: asset.downloadsCount + 1 };
      await apiClient.put(`/assets/${asset.id}`, updatedAsset);
      
      setAssets(prev => prev.map(a => a.id === asset.id ? updatedAsset : a));
      if (selectedAsset?.id === asset.id) {
        setSelectedAsset(updatedAsset);
      }
    } catch (err) {
      console.error(err);
      error('Download tracking failed', 'Unable to record download statistics.');
    }
  };

  const getCategoryIcon = (catId: string) => {
    switch (catId) {
      case 'silicon': return <Cpu className="h-5 w-5" />;
      case 'software': return <Terminal className="h-5 w-5" />;
      case 'ai': return <Brain className="h-5 w-5" />;
      case 'cloud': return <Server className="h-5 w-5" />;
      default: return <HelpCircle className="h-5 w-5" />;
    }
  };

  const currentCategory = categories.find(c => c.id === selectedCategory);

  return (
    <div className="space-y-6 text-ink-900">
      <div className="rounded-2xl bg-ink-0 p-6 md:p-8 border border-ink-200 flex flex-col md:flex-row items-center justify-between gap-6">
        <div className="space-y-2">
          <h1 className="text-2xl explorer-title font-bold text-ink-900 md:text-3xl">Tech4Biz Asset Explorer</h1>
          <p className="text-sm explorer-desc text-ink-700 max-w-xl">
            Browse, preview, and download proprietary hardware IP, framework assemblies, and cloud-native building blocks licensed under your master agreements.
          </p>
        </div>
        <div className="flex gap-4">
          <div className="bg-ink-50 rounded-xl border border-ink-200 p-4 text-center min-w-[6.5rem]">
            <p className="text-2xl font-bold text-ink-900">{assets.length}</p>
            <p className="text-[10px] uppercase font-bold tracking-wider text-ink-600">Available</p>
          </div>
        </div>
      </div>

      {/* Toolbar - Search & Category tabs */}
      <div className="space-y-4 rounded-xl border border-ink-200 bg-ink-0 p-4 shadow-sm md:p-6">
        {/* Search & Subcategory select */}
        <div className="flex flex-col md:flex-row gap-4">
          <div className="relative flex-1">
            <Search className="absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 text-ink-600" />
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder="Search by IP block name, language, metadata tag..."
              className="w-full rounded-lg border border-ink-200 pl-10 pr-4 py-2 text-sm focus:border-ink-900/50 focus:outline-none transition-colors bg-ink-50 text-ink-900 placeholder-ink-400"
            />
          </div>
          {currentCategory && currentCategory.subcategories.length > 0 && (
            <div className="w-full md:w-64">
              <select
                value={selectedSubcategory}
                onChange={(e) => setSelectedSubcategory(e.target.value)}
                className="w-full rounded-lg border border-ink-200 bg-ink-50 px-3 py-2 text-sm focus:border-ink-900/50 focus:outline-none text-ink-900"
              >
                <option value="all">All Subcategories</option>
                {currentCategory.subcategories.map(sub => (
                  <option key={sub} value={sub}>{sub}</option>
                ))}
              </select>
            </div>
          )}
        </div>

        {/* Category Tabs */}
        <div className="flex flex-wrap gap-2 pt-2">
          <button
            onClick={() => {
              setSelectedCategory('all');
              setSelectedSubcategory('all');
            }}
            className={`flex items-center gap-2 rounded-lg px-4 py-2.5 text-xs font-semibold transition-all ${
              selectedCategory === 'all'
                ? 'bg-ink-900 text-ink-0 shadow-sm'
                : 'bg-ink-50 text-ink-700 border border-ink-200 hover:bg-ink-100'
            }`}
          >
            All Resources
          </button>
          {categories.map(cat => (
            <button
              key={cat.id}
              onClick={() => {
                setSelectedCategory(cat.id);
                setSelectedSubcategory('all');
              }}
              className={`flex items-center gap-2 rounded-lg px-4 py-2.5 text-xs font-semibold transition-all ${
                selectedCategory === cat.id
                  ? 'bg-ink-900 text-ink-0 shadow-sm'
                  : 'bg-ink-50 text-ink-700 border border-ink-200 hover:bg-ink-100'
              }`}
            >
              {getCategoryIcon(cat.id)}
              {cat.name}
            </button>
          ))}
        </div>
      </div>

      {/* Skeletons/Grid */}
      {loading ? (
        <div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
          {[1, 2, 3].map(n => (
            <div key={n} className="animate-pulse rounded-xl border border-ink-200 bg-ink-0 p-5 space-y-4">
              <div className="h-40 rounded-lg bg-ink-100" />
              <div className="h-4 w-3/4 rounded bg-ink-100" />
              <div className="h-10 rounded bg-ink-100" />
              <div className="h-4 w-1/2 rounded bg-ink-100" />
            </div>
          ))}
        </div>
      ) : assets.length === 0 ? (
        <div className="rounded-xl border border-ink-200 bg-ink-0 p-12 text-center">
          <p className="text-base font-bold text-ink-800 mb-1">No Assets Found</p>
          <p className="text-sm text-ink-600">Try adjusting your filters or searching for another keyword.</p>
        </div>
      ) : (
        <div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
          {assets.map(asset => (
            <div
              key={asset.id}
              className="group rounded-xl border border-ink-200 bg-ink-0 shadow-sm overflow-hidden flex flex-col hover:border-ink-400 transition-all duration-300"
            >
              {/* Card Image banner */}
              <div className="h-44 w-full relative overflow-hidden bg-ink-100">
                <img
                  src={asset.thumbnailUrl}
                  alt={asset.title}
                  className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
                />
                <span className="absolute left-3 top-3 rounded-full bg-ink-0/90 backdrop-blur px-2.5 py-1 text-[10px] font-bold uppercase tracking-wider text-ink-900 shadow-sm border border-ink-200 flex items-center gap-1.5">
                  {getCategoryIcon(asset.categoryId)}
                  {asset.subcategory}
                </span>
              </div>

              {/* Card Body */}
              <div className="p-5 flex-1 flex flex-col justify-between space-y-4">
                <div className="space-y-2">
                  <h3 className="text-base font-bold text-ink-800 group-hover:text-ink-900 transition-colors line-clamp-1">
                    {asset.title}
                  </h3>
                  <p className="text-xs text-ink-600 line-clamp-2 leading-relaxed">
                    {asset.description}
                  </p>
                </div>

                <div className="space-y-4 pt-2">
                  {/* Tags */}
                  <div className="flex flex-wrap gap-1.5">
                    {asset.tags.map(tag => (
                      <span key={tag} className="rounded bg-ink-50 px-2 py-0.5 text-[9px] font-semibold text-ink-700 border border-ink-200">
                        #{tag}
                      </span>
                    ))}
                  </div>

                  {/* Actions */}
                  <div className="flex items-center justify-between border-t border-ink-100 pt-3">
                    <button
                      onClick={() => setSelectedAsset(asset)}
                      className="text-xs font-bold text-ink-800 hover:text-ink-900 transition-colors"
                    >
                      View Details
                    </button>
                    <div className="flex items-center gap-2">
                      {asset.githubUrl && (
                        <a
                          href={asset.githubUrl}
                          target="_blank"
                          rel="noreferrer"
                          className="rounded-lg border border-ink-200 p-2 text-ink-600 hover:text-ink-800 hover:bg-ink-50 transition-colors"
                          title="Open Repository"
                        >
                          <GithubIcon className="h-4 w-4" />
                        </a>
                      )}
                      <button
                        onClick={() => handleDownload(asset)}
                        className="rounded-lg bg-ink-900 p-2 text-ink-0 hover:bg-ink-800 transition-colors shadow-sm"
                        title="Download Asset"
                      >
                        <Download className="h-4 w-4" />
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Asset Details Modal */}
      {selectedAsset && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-ink-900/20 backdrop-blur-sm p-4 animate-fade-in">
          <div className="w-full max-w-2xl rounded-2xl border border-ink-200 bg-ink-0 p-6 shadow-xl max-h-[90vh] overflow-y-auto space-y-6 relative animate-scale-up">
            <button
              onClick={() => setSelectedAsset(null)}
              className="absolute right-4 top-4 rounded-full p-1.5 text-ink-600 hover:bg-ink-100 hover:text-ink-800 transition-colors"
            >
              <X className="h-5 w-5" />
            </button>

            {/* Modal Image banner */}
            <div className="h-60 rounded-xl overflow-hidden bg-ink-100 relative">
              <img
                src={selectedAsset.thumbnailUrl}
                alt={selectedAsset.title}
                className="w-full h-full object-cover"
              />
              <span className="absolute left-4 top-4 rounded-full bg-ink-0/95 px-3 py-1.5 text-xs font-bold uppercase tracking-wider text-ink-900 shadow-sm border border-ink-200 flex items-center gap-1.5">
                {getCategoryIcon(selectedAsset.categoryId)}
                {selectedAsset.subcategory}
              </span>
            </div>

            {/* Meta */}
            <div className="space-y-4">
              <h2 className="text-xl font-bold text-ink-800 leading-snug">{selectedAsset.title}</h2>
              <div className="flex flex-wrap gap-y-2 gap-x-4 text-xs text-ink-600 font-medium">
                <span className="flex items-center gap-1.5">
                  <User className="h-4 w-4 text-ink-600" />
                  By: {selectedAsset.author}
                </span>
                <span className="flex items-center gap-1.5">
                  <Calendar className="h-4 w-4 text-ink-600" />
                  Released: {selectedAsset.publishDate}
                </span>
                <span className="flex items-center gap-1.5">
                  <Download className="h-4 w-4 text-ink-600" />
                  Downloads: {selectedAsset.downloadsCount}
                </span>
              </div>
            </div>

            {/* Description */}
            <div className="border-t border-ink-100 pt-4">
              <h4 className="text-xs font-bold uppercase tracking-wider text-ink-600 mb-2">Description / Technical Overview</h4>
              <p className="text-sm text-ink-700 leading-relaxed bg-ink-50 p-4 rounded-lg border border-ink-200">
                {selectedAsset.description}
              </p>
            </div>

            {/* Tags */}
            <div>
              <h4 className="text-xs font-bold uppercase tracking-wider text-ink-600 mb-2 flex items-center gap-1">
                <Tag className="h-3 w-3 text-ink-600" /> Tags
              </h4>
              <div className="flex flex-wrap gap-2">
                {selectedAsset.tags.map(tag => (
                  <span key={tag} className="rounded bg-ink-50 px-2.5 py-1 text-xs font-semibold text-ink-700 border border-ink-200">
                    {tag}
                  </span>
                ))}
              </div>
            </div>

            {/* Footer buttons */}
            <div className="border-t border-ink-100 pt-4 flex justify-end gap-3">
              {selectedAsset.githubUrl && (
                <a
                  href={selectedAsset.githubUrl}
                  target="_blank"
                  rel="noreferrer"
                  className="flex items-center gap-2 rounded-lg border border-ink-200 bg-ink-0 px-4 py-2 text-sm font-semibold text-ink-700 hover:bg-ink-50 transition-colors"
                >
                  <GithubIcon className="h-4 w-4" />
                  Repository URL
                </a>
              )}
              <button
                onClick={() => handleDownload(selectedAsset)}
                className="flex items-center gap-2 rounded-lg bg-ink-900 px-5 py-2 text-sm font-semibold text-ink-0 hover:bg-ink-800 transition-colors"
              >
                <Download className="h-4 w-4" />
                Download Files
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};
export default AssetExplorer;
