import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import type { Asset } from '../../../types/assets';
import type { AssetGroup } from '../../../services/assets-api';
import Modal from '../../../components/ui/Modal';
import Button from '../../../components/ui/Button';
import { Folder, Plus, Trash2, Search, CheckCircle, ExternalLink } from 'lucide-react';
import { createAssetGroup, deleteAssetGroup } from '../../../services/assets-api';
import { useToast } from '../../../hooks/use-toast';

interface ManageGroupsModalProps {
  isOpen: boolean;
  onClose: () => void;
  assets: Asset[];
  groups: AssetGroup[];
  onRefresh: () => void;
}

export const ManageGroupsModal: React.FC<ManageGroupsModalProps> = ({
  isOpen,
  onClose,
  assets,
  groups,
  onRefresh,
}) => {
  const { success, error } = useToast();
  const [name, setName] = useState('');
  const [description, setDescription] = useState('');
  const [selectedAssetIds, setSelectedAssetIds] = useState<string[]>([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);

  const filteredAssets = assets.filter(asset =>
    asset.title.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const handleToggleAsset = (id: string) => {
    setSelectedAssetIds(prev =>
      prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]
    );
  };

  const handleSelectAll = () => {
    if (selectedAssetIds.length === assets.length) {
      setSelectedAssetIds([]);
    } else {
      setSelectedAssetIds(assets.map(a => a.id));
    }
  };

  const handleCreateGroup = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!name.trim()) return;
    setIsSubmitting(true);
    try {
      await createAssetGroup({
        name: name.trim(),
        description: description.trim() || undefined,
        assetIds: selectedAssetIds,
      });
      success('Asset group created', `"${name}" group was successfully registered.`);
      setName('');
      setDescription('');
      setSelectedAssetIds([]);
      onRefresh();
    } catch (err: any) {
      console.error(err);
      error('Failed to create group', err.response?.data?.error || 'Something went wrong.');
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleDeleteGroup = async (id: string, groupName: string) => {
    if (!window.confirm(`Are you sure you want to permanently delete the asset bundle "${groupName}"?`)) {
      return;
    }
    try {
      await deleteAssetGroup(id);
      success('Asset group deleted', `"${groupName}" group has been deleted.`);
      onRefresh();
    } catch (err: any) {
      console.error(err);
      error('Failed to delete group', err.response?.data?.error || 'Something went wrong.');
    }
  };

  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-6 h-6 rounded bg-red-500/10 border border-red-500/20 flex items-center justify-center text-red-650 shrink-0">
          <span className="text-[8px] font-bold">PDF</span>
        </div>
      );
    }
    if (lowerType.includes('word') || lowerTitle.endsWith('.docx') || lowerTitle.endsWith('.doc')) {
      return (
        <div className="w-6 h-6 rounded bg-blue-500/10 border border-blue-500/20 flex items-center justify-center text-blue-650 shrink-0">
          <span className="text-[8px] font-bold">DOC</span>
        </div>
      );
    }
    if (lowerType.includes('presentation') || lowerTitle.endsWith('.pptx') || lowerTitle.endsWith('.ppt')) {
      return (
        <div className="w-6 h-6 rounded bg-orange-500/10 border border-orange-500/20 flex items-center justify-center text-orange-650 shrink-0">
          <span className="text-[8px] font-bold">PPT</span>
        </div>
      );
    }
    return (
      <div className="w-6 h-6 rounded bg-ink-500/10 border border-ink-500/20 flex items-center justify-center text-ink-600 shrink-0">
        <span className="text-[8px] font-bold">URL</span>
      </div>
    );
  };

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      title="Manage Asset Groups & Bundles"
      subtitle="Bundle a fixed group of collateral/resources to easily assign them to partner users in one click."
      size="xl"
    >
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 min-h-[450px]">
        {/* Left Side: Existing Groups */}
        <div className="border-r border-ink-200 pr-0 lg:pr-6 flex flex-col min-h-0">
          <h3 className="text-xs font-bold uppercase tracking-wider text-ink-500 mb-4 flex items-center gap-1.5 font-sans">
            <Folder className="w-4 h-4 text-ink-750" />
            <span>Active Asset Groups ({groups.length})</span>
          </h3>

          <div className="flex-1 overflow-y-auto space-y-3 max-h-[380px] pr-1">
            {groups.length === 0 ? (
              <div className="text-center py-12 bg-ink-50/55 rounded-xl border border-dashed border-ink-200">
                <Folder className="w-10 h-10 text-ink-300 mx-auto mb-2" />
                <p className="text-xs font-bold text-ink-900 font-sans">No Asset Groups Created</p>
                <p className="text-[10px] text-ink-450 mt-1 font-sans">Use the panel on the right to bundle your first set of resources.</p>
              </div>
            ) : (
              groups.map(group => (
                <div key={group.id} className="p-3 bg-ink-0 border border-ink-200 rounded-xl shadow-sm hover:border-ink-305 transition-all flex justify-between items-start gap-4">
                  <div className="min-w-0 flex-1 font-sans">
                    <p className="text-xs font-bold text-ink-900 truncate">{group.name}</p>
                    {group.description && (
                      <p className="text-[10px] text-ink-500 mt-0.5 font-medium">{group.description}</p>
                    )}
                    <div className="flex flex-wrap gap-1.5 mt-3 items-center">
                      <Link
                        to={`/admin/groups/${group.id}`}
                        onClick={onClose}
                        className="text-[9px] px-2 py-0.5 rounded bg-ink-900 hover:bg-ink-800 text-ink-0 font-bold flex items-center gap-1 transition-all border border-transparent shadow-sm cursor-pointer"
                      >
                        <ExternalLink className="w-2.5 h-2.5" />
                        <span>View Page</span>
                      </Link>
                      <span className="text-[9px] px-1.5 py-0.5 rounded bg-ink-100 border border-ink-200 text-ink-700 font-bold">
                        {group.assets.length} Assets
                      </span>
                    </div>
                  </div>
                  <button
                    onClick={() => handleDeleteGroup(group.id, group.name)}
                    className="p-1.5 text-red-500 hover:text-red-700 hover:bg-red-500/10 rounded-lg transition-colors cursor-pointer shrink-0"
                    title="Delete Group"
                  >
                    <Trash2 className="w-4 h-4" />
                  </button>
                </div>
              ))
            )}
          </div>
        </div>

        {/* Right Side: Create Group Form */}
        <form onSubmit={handleCreateGroup} className="flex flex-col min-h-0">
          <h3 className="text-xs font-bold uppercase tracking-wider text-ink-500 mb-4 flex items-center gap-1.5 font-sans">
            <Plus className="w-4 h-4 text-ink-750" />
            <span>Create New Bundle</span>
          </h3>

          <div className="space-y-4 flex-1 overflow-y-auto max-h-[380px] pr-1">
            <div>
              <label className="text-[10px] font-bold text-ink-500 uppercase tracking-wide mb-1 block font-sans">
                Bundle Name *
              </label>
              <input
                type="text"
                value={name}
                onChange={e => setName(e.target.value)}
                placeholder="e.g. Sales Onboarding Pack"
                required
                className="w-full px-3 py-2 bg-ink-50 border border-ink-200 rounded-lg text-xs focus:outline-none focus:ring-2 focus:ring-ink-900/10 text-ink-900 placeholder-ink-400 font-semibold font-sans"
              />
            </div>

            <div>
              <label className="text-[10px] font-bold text-ink-500 uppercase tracking-wide mb-1 block font-sans">
                Description
              </label>
              <textarea
                value={description}
                onChange={e => setDescription(e.target.value)}
                placeholder="Describe what assets are bundled in this group."
                rows={2}
                className="w-full px-3 py-2 bg-ink-50 border border-ink-200 rounded-lg text-xs focus:outline-none focus:ring-2 focus:ring-ink-900/10 text-ink-900 placeholder-ink-400 font-semibold resize-none font-sans"
              />
            </div>

            <div>
              <div className="flex justify-between items-center mb-1.5 font-sans">
                <label className="text-[10px] font-bold text-ink-500 uppercase tracking-wide">
                  Select Assets to Include
                </label>
                <button
                  type="button"
                  onClick={handleSelectAll}
                  className="text-[9px] font-bold text-ink-900 hover:underline cursor-pointer"
                >
                  {selectedAssetIds.length === assets.length ? 'Deselect All' : 'Select All'}
                </button>
              </div>

              {/* Asset search and list */}
              <div className="border border-ink-200 rounded-lg overflow-hidden flex flex-col max-h-[200px]">
                <div className="relative border-b border-ink-200 shrink-0">
                  <Search className="w-3.5 h-3.5 text-ink-400 absolute left-2.5 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/50 py-1.5 pl-8 pr-3 text-[11px] font-medium outline-none text-ink-900 font-sans"
                  />
                </div>

                <div className="overflow-y-auto divide-y divide-ink-200 bg-ink-0">
                  {filteredAssets.length === 0 ? (
                    <div className="p-4 text-center text-[10px] text-ink-400 font-medium font-sans">
                      No assets found
                    </div>
                  ) : (
                    filteredAssets.map(asset => {
                      const isSelected = selectedAssetIds.includes(asset.id);
                      return (
                        <div
                          key={asset.id}
                          onClick={() => handleToggleAsset(asset.id)}
                          className={`flex items-center gap-3 p-2 text-xs font-semibold cursor-pointer transition-all hover:bg-ink-100 ${
                            isSelected ? 'bg-ink-100/70' : ''
                          }`}
                        >
                          <div className={`w-3.5 h-3.5 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-2.5 h-2.5 stroke-[3]" />}
                          </div>
                          {getFileIcon(asset.type, asset.title)}
                          <div className="min-w-0 flex-1 font-sans">
                            <p className="truncate text-ink-900 text-[11px]">{asset.title}</p>
                            {asset.categoryId && (
                              <span className="text-[8px] px-1 py-0.2 rounded bg-ink-100 text-ink-600 font-bold uppercase tracking-wider">
                                {asset.categoryId}
                              </span>
                            )}
                          </div>
                        </div>
                      );
                    })
                  )}
                </div>
              </div>
            </div>

            <Button
              type="submit"
              variant="primary"
              size="sm"
              disabled={isSubmitting || !name.trim()}
              className="w-full flex justify-center py-2"
            >
              {isSubmitting ? 'Creating Bundle...' : 'Create Group / Bundle'}
            </Button>
          </div>
        </form>
      </div>
    </Modal>
  );
};
