import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { ArrowLeft, Folder, File, Tag, Trash2, Plus, Search, CheckCircle } from 'lucide-react';
import { getAssetGroups, getAssets, addAssetsToGroup, removeAssetsFromGroup } from '../../services/assets-api';
import type { AssetGroup } from '../../services/assets-api';
import type { Asset } from '../../types/assets';
import PageHeader from '../../components/ui/PageHeader';
import { PageLayout } from '../../components/layout/PageLayout';
import Button from '../../components/ui/Button';
import Modal from '../../components/ui/Modal';
import { useToast } from '../../hooks/use-toast';

export const GroupDetailsPage: React.FC = () => {
  const { groupId } = useParams<{ groupId: string }>();
  const navigate = useNavigate();
  const { success, error } = useToast();

  const [group, setGroup] = useState<AssetGroup | null>(null);
  const [allAssets, setAllAssets] = useState<Asset[]>([]);
  const [loading, setLoading] = useState(true);
  
  const [isAddModalOpen, setIsAddModalOpen] = useState(false);
  const [selectedAssetIds, setSelectedAssetIds] = useState<string[]>([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [assetToRemove, setAssetToRemove] = useState<{ id: string, title: string } | null>(null);

  const loadData = async () => {
    if (!groupId) return;
    try {
      const [groups, assets] = await Promise.all([
        getAssetGroups(),
        getAssets()
      ]);
      const found = groups.find(g => g.id === groupId);
      setGroup(found || null);
      setAllAssets(assets);
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    setLoading(true);
    loadData();
  }, [groupId]);

  const handleRemoveAsset = (assetId: string, assetTitle: string) => {
    setAssetToRemove({ id: assetId, title: assetTitle });
  };

  const handleAddAssets = async () => {
    if (!groupId || selectedAssetIds.length === 0) return;
    try {
      await addAssetsToGroup(groupId, selectedAssetIds);
      success('Assets added', `Successfully added ${selectedAssetIds.length} assets to the bundle.`);
      setSelectedAssetIds([]);
      setIsAddModalOpen(false);
      loadData();
    } catch (err: any) {
      error('Failed to add assets', err.response?.data?.error || 'Something went wrong.');
    }
  };

  const existingAssetIds = new Set(group?.assets.map(a => a.id) || []);
  const addableAssets = allAssets.filter(a => !existingAssetIds.has(a.id));
  const filteredAddableAssets = addableAssets.filter(a =>
    a.title.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const getFileIcon = (type: string, title: string) => {
    const lowerType = type.toLowerCase();
    const lowerTitle = title.toLowerCase();
    if (lowerType.includes('pdf') || lowerTitle.endsWith('.pdf')) {
      return (
        <div className="w-10 h-10 rounded-xl bg-red-500/10 border border-red-500/20 flex items-center justify-center text-red-650 shrink-0">
          <span className="text-[10px] font-bold">PDF</span>
        </div>
      );
    }
    if (lowerType.includes('word') || lowerTitle.endsWith('.docx') || lowerTitle.endsWith('.doc')) {
      return (
        <div className="w-10 h-10 rounded-xl bg-blue-500/10 border border-blue-500/20 flex items-center justify-center text-blue-650 shrink-0">
          <span className="text-[10px] font-bold">DOC</span>
        </div>
      );
    }
    if (lowerType.includes('presentation') || lowerTitle.endsWith('.pptx') || lowerTitle.endsWith('.ppt')) {
      return (
        <div className="w-10 h-10 rounded-xl bg-orange-500/10 border border-orange-500/20 flex items-center justify-center text-orange-650 shrink-0">
          <span className="text-[10px] font-bold">PPT</span>
        </div>
      );
    }
    return (
      <div className="w-10 h-10 rounded-xl bg-ink-500/10 border border-ink-500/20 flex items-center justify-center text-ink-600 shrink-0">
        <span className="text-[10px] font-bold">URL</span>
      </div>
    );
  };

  const headerNode = (
    <div className="flex flex-col gap-2">
      <button
        onClick={() => navigate('/admin/assets')}
        className="flex items-center gap-1 text-[11px] font-bold text-ink-500 hover:text-ink-900 transition-colors uppercase tracking-wider mb-2 cursor-pointer w-fit"
      >
        <ArrowLeft className="w-3.5 h-3.5" />
        <span>Back to Asset Library</span>
      </button>
      <PageHeader
        title={group ? `Bundle: ${group.name}` : 'Asset Bundle'}
        subtitle={group?.description || 'View and inspect the assets stored in this bundle.'}
        badge={
          <div className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full bg-ink-100 border border-ink-200 text-[10px] font-bold text-ink-900 tracking-wider uppercase">
            <Folder className="w-3.5 h-3.5 text-ink-800" />
            <span>{group?.assets?.length || 0} Assets</span>
          </div>
        }
      />
    </div>
  );

  return (
    <PageLayout header={headerNode}>
      <div className="p-5 flex-1 min-h-0 overflow-y-auto">
        {loading ? (
          <div className="py-20 flex justify-center items-center">
            <div className="w-8 h-8 border-4 border-ink-900/30 border-t-ink-900 rounded-full animate-spin" />
          </div>
        ) : !group ? (
          <div className="py-16 text-center bg-ink-0 border border-ink-200 rounded-xl">
            <Folder className="w-12 h-12 text-ink-300 mx-auto mb-4" />
            <h3 className="text-lg font-bold text-ink-900">Group not found</h3>
            <p className="text-ink-500 text-sm mt-1">
              The asset group you are looking for does not exist or has been deleted.
            </p>
            <Button
              onClick={() => navigate('/admin/assets')}
              variant="primary"
              size="sm"
              className="mt-4"
            >
              Return to Catalog
            </Button>
          </div>
        ) : (
          <div className="space-y-6">
            <div className="bg-ink-0 border border-ink-200 rounded-xl p-5 shadow-sm">
              <div className="flex justify-between items-center mb-4">
                <h3 className="text-xs font-bold text-ink-500 uppercase tracking-wider">
                  Assets in this Bundle
                </h3>
                <Button
                  onClick={() => setIsAddModalOpen(true)}
                  variant="primary"
                  size="xs"
                  className="flex items-center gap-1"
                >
                  <Plus className="w-3 h-3" />
                  <span>Add Assets</span>
                </Button>
              </div>

              {group.assets.length === 0 ? (
                <div className="py-12 text-center border border-dashed border-ink-200 rounded-xl bg-ink-50/50">
                  <File className="w-10 h-10 text-ink-300 mx-auto mb-2" />
                  <p className="text-xs font-bold text-ink-900">This bundle is currently empty</p>
                  <p className="text-[10px] text-ink-450 mt-1">Add assets to this group using the "Add Assets" button above.</p>
                </div>
              ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  {group.assets.map(asset => (
                    <div
                      key={asset.id}
                      className="p-4 bg-ink-50/40 border border-ink-200 rounded-xl shadow-sm hover:border-ink-350 transition-all flex items-start gap-4"
                    >
                      {getFileIcon(asset.type, asset.title)}
                      <div className="min-w-0 flex-1">
                        <div className="flex items-center gap-2">
                          <p className="text-xs font-bold text-ink-900 truncate">{asset.title}</p>
                          {asset.isDownloadable && (
                            <span className="shrink-0 text-[8px] font-bold uppercase tracking-wider px-1.5 py-0.2 rounded bg-green-500/10 text-green-600 border border-green-500/20">
                              Downloadable
                            </span>
                          )}
                        </div>
                        {asset.description && (
                          <p className="text-[10px] text-ink-550 mt-1 line-clamp-2 leading-relaxed">
                            {asset.description}
                          </p>
                        )}
                        <div className="flex flex-wrap gap-2 mt-3 items-center text-[9px] text-ink-450 font-bold">
                          <div className="flex items-center gap-1 bg-ink-100 px-1.5 py-0.5 rounded border border-ink-200 text-ink-700">
                            <Tag className="w-3 h-3" />
                            <span className="uppercase">{asset.categoryId || 'General'}</span>
                          </div>
                          {asset.subcategory && (
                            <div className="bg-ink-50 px-1.5 py-0.5 rounded border border-ink-150">
                              {asset.subcategory}
                            </div>
                          )}
                        </div>
                      </div>
                      <button
                        onClick={() => handleRemoveAsset(asset.id, asset.title)}
                        className="p-1.5 text-red-500 hover:text-red-750 hover:bg-red-500/10 rounded-lg transition-colors cursor-pointer shrink-0"
                        title="Remove from Bundle"
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>
        )}
      </div>

      {/* Add Assets Modal */}
      <Modal
        isOpen={isAddModalOpen}
        onClose={() => {
          setIsAddModalOpen(false);
          setSelectedAssetIds([]);
          setSearchQuery('');
        }}
        title="Add Assets to Bundle"
        subtitle={`Select assets to add to "${group?.name}"`}
        size="md"
      >
        <div className="space-y-4">
          <div className="relative">
            <Search className="w-4 h-4 text-ink-450 absolute left-3 top-1/2 -translate-y-1/2" />
            <input
              type="text"
              value={searchQuery}
              onChange={e => setSearchQuery(e.target.value)}
              placeholder="Search catalog assets..."
              className="w-full bg-ink-50 border border-ink-200 rounded-lg pl-9 pr-4 py-2 text-xs focus:outline-none focus:ring-2 focus:ring-ink-900/10 text-ink-900 placeholder-ink-400 font-semibold"
            />
          </div>

          <div className="border border-ink-200 rounded-xl overflow-hidden max-h-[300px] overflow-y-auto divide-y divide-ink-200 bg-ink-0">
            {filteredAddableAssets.length === 0 ? (
              <div className="p-8 text-center text-xs text-ink-400 font-medium">
                No new assets available to add
              </div>
            ) : (
              filteredAddableAssets.map(asset => {
                const isSelected = selectedAssetIds.includes(asset.id);
                return (
                  <div
                    key={asset.id}
                    onClick={() => {
                      setSelectedAssetIds(prev =>
                        prev.includes(asset.id) ? prev.filter(x => x !== asset.id) : [...prev, asset.id]
                      );
                    }}
                    className={`flex items-center gap-3 p-3 text-xs font-semibold cursor-pointer transition-all hover:bg-ink-50 ${
                      isSelected ? 'bg-ink-50/70' : ''
                    }`}
                  >
                    <div className={`w-4 h-4 rounded border flex items-center justify-center transition-all ${
                      isSelected
                        ? 'border-ink-900 bg-ink-900 text-ink-0'
                        : 'border-ink-200 bg-ink-50'
                    }`}>
                      {isSelected && <CheckCircle className="w-3 h-3 stroke-[3]" />}
                    </div>
                    <div className="min-w-0 flex-1">
                      <p className="truncate text-ink-900">{asset.title}</p>
                      <span className="text-[9px] text-ink-450 uppercase tracking-wider">
                        {asset.type === 'case_study' ? 'Case Study' : asset.type === 'url' ? 'External Link' : asset.categoryId || 'General'}
                      </span>
                    </div>
                  </div>
                );
              })
            )}
          </div>

          <div className="flex gap-3 justify-end pt-2">
            <Button
              onClick={() => {
                setIsAddModalOpen(false);
                setSelectedAssetIds([]);
                setSearchQuery('');
              }}
              variant="secondary"
              size="sm"
            >
              Cancel
            </Button>
            <Button
              onClick={handleAddAssets}
              variant="primary"
              size="sm"
              disabled={selectedAssetIds.length === 0}
            >
              Add {selectedAssetIds.length} Asset{selectedAssetIds.length !== 1 ? 's' : ''}
            </Button>
          </div>
        </div>
      </Modal>

      {/* Remove Confirmation Modal */}
      <Modal
        isOpen={assetToRemove !== null}
        onClose={() => setAssetToRemove(null)}
        title="Remove Asset from Bundle"
        subtitle="Confirm you want to remove this resource."
        size="sm"
      >
        <div className="space-y-4 font-sans">
          <p className="text-xs text-ink-600 leading-relaxed">
            Are you sure you want to remove <span className="font-bold text-ink-900">"{assetToRemove?.title}"</span> from this asset bundle?
          </p>
          <div className="flex gap-3 justify-end pt-2">
            <Button
              onClick={() => setAssetToRemove(null)}
              variant="secondary"
              size="sm"
            >
              Cancel
            </Button>
            <Button
              onClick={async () => {
                if (!assetToRemove || !groupId) return;
                try {
                  await removeAssetsFromGroup(groupId, [assetToRemove.id]);
                  success('Asset removed', `"${assetToRemove.title}" was removed from the bundle.`);
                  setAssetToRemove(null);
                  loadData();
                } catch (err: any) {
                  error('Failed to remove asset', err.response?.data?.error || 'Something went wrong.');
                }
              }}
              variant="danger"
              size="sm"
            >
              Remove Asset
            </Button>
          </div>
        </div>
      </Modal>
    </PageLayout>
  );
};
