import React, { useState } from 'react';
import { X, Shield, Plus, Trash2, Send, Tag, CheckCircle2, AlertCircle, Bell } from 'lucide-react';
import type { TaxonomyMeta, Organization, Asset } from '../../../types/assets';
import { createVertical, deleteVertical, sendAssetAnnouncement } from '../../../services/assets-api';

interface AssetAdminManagerModalProps {
  isOpen: boolean;
  onClose: () => void;
  meta: TaxonomyMeta | null;
  organizations: Organization[];
  allAssets?: Asset[];
  onRefreshMeta: () => void;
}

export const AssetAdminManagerModal: React.FC<AssetAdminManagerModalProps> = ({
  isOpen,
  onClose,
  meta,
  organizations,
  allAssets = [],
  onRefreshMeta,
}) => {
  const [activeTab, setActiveTab] = useState<'verticals' | 'taxonomy' | 'announcements'>('verticals');
  const [loading, setLoading] = useState(false);
  const [statusMsg, setStatusMsg] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  // Inspect filter state for Taxonomy Stats interactive list
  const [inspectFilter, setInspectFilter] = useState<{ type: 'Subcategory' | 'Vertical'; name: string; id?: string } | null>(null);

  // New Vertical Form State
  const [newVerticalName, setNewVerticalName] = useState('');
  const [newVerticalColor, setNewVerticalColor] = useState('#3b82f6');
  const [newVerticalDesc, setNewVerticalDesc] = useState('');

  // Announcement Form State
  const [announcementTitle, setAnnouncementTitle] = useState('');
  const [announcementMsg, setAnnouncementMsg] = useState('');
  const [selectedOrgId, setSelectedOrgId] = useState<string>('ALL');

  if (!isOpen) return null;

  const matchingAssets = (allAssets || []).filter(asset => {
    if (!inspectFilter) return false;
    if (inspectFilter.type === 'Subcategory') {
      return (asset.subcategory || asset.categoryId || '').toLowerCase() === inspectFilter.name.toLowerCase();
    }
    if (inspectFilter.type === 'Vertical') {
      return asset.verticals?.some(v => v.id === inspectFilter.id || v.name.toLowerCase() === inspectFilter.name.toLowerCase());
    }
    return false;
  });

  const handleCreateVertical = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newVerticalName.trim()) return;
    setLoading(true);
    try {
      await createVertical({
        name: newVerticalName.trim(),
        color: newVerticalColor,
        description: newVerticalDesc.trim() || undefined,
        icon: 'Shield',
      });
      setStatusMsg({ type: 'success', text: `Vertical "${newVerticalName}" created successfully!` });
      setNewVerticalName('');
      setNewVerticalDesc('');
      onRefreshMeta();
    } catch (err: any) {
      setStatusMsg({ type: 'error', text: err.response?.data?.error || 'Failed to create vertical' });
    } finally {
      setLoading(false);
    }
  };

  const handleDeleteVertical = async (id: string, name: string) => {
    if (!window.confirm(`Are you sure you want to delete vertical "${name}"?`)) return;
    setLoading(true);
    try {
      await deleteVertical(id);
      setStatusMsg({ type: 'success', text: `Vertical "${name}" deleted` });
      onRefreshMeta();
    } catch (err: any) {
      setStatusMsg({ type: 'error', text: 'Failed to delete vertical' });
    } finally {
      setLoading(false);
    }
  };

  const handleSendAnnouncement = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!announcementTitle.trim() || !announcementMsg.trim()) return;
    setLoading(true);
    try {
      await sendAssetAnnouncement({
        title: announcementTitle.trim(),
        message: announcementMsg.trim(),
        targetOrgIds: selectedOrgId === 'ALL' ? ['ALL'] : [selectedOrgId],
      });
      setStatusMsg({ type: 'success', text: 'Announcement dispatched to partner organizations!' });
      setAnnouncementTitle('');
      setAnnouncementMsg('');
    } catch (err: any) {
      setStatusMsg({ type: 'error', text: err.response?.data?.error || 'Failed to send announcement' });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 overflow-y-auto bg-slate-900/60 backdrop-blur-sm flex items-center justify-center p-4">
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-800 shadow-2xl w-full max-w-3xl overflow-hidden flex flex-col max-h-[85vh]">
        
        {/* Modal Header */}
        <div className="px-6 py-5 border-b border-slate-200 dark:border-slate-800 flex items-center justify-between bg-slate-50/50 dark:bg-slate-900/50">
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-xl bg-slate-900 text-white dark:bg-slate-100 dark:text-slate-900 shadow-md">
              <Shield className="w-5 h-5" />
            </div>
            <div>
              <h2 className="text-lg font-bold text-slate-900 dark:text-slate-100">
                Taxonomy & Partner Announcements Control Panel
              </h2>
              <p className="text-xs text-slate-500 dark:text-slate-400">
                Manage industry verticals, taxonomy metadata, and partner communications
              </p>
            </div>
          </div>
          <button
            onClick={onClose}
            className="p-2 text-slate-400 hover:text-slate-600 dark:hover:text-slate-200 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Tab Navigation */}
        <div className="flex border-b border-slate-200 dark:border-slate-800 bg-slate-100/50 dark:bg-slate-800/50 px-6">
          <button
            onClick={() => { setActiveTab('verticals'); setStatusMsg(null); }}
            className={`px-4 py-3 text-xs font-bold border-b-2 flex items-center gap-2 transition-colors ${
              activeTab === 'verticals'
                ? 'border-slate-900 text-slate-900 dark:border-slate-100 dark:text-slate-100'
                : 'border-transparent text-slate-500 hover:text-slate-800 dark:hover:text-slate-200'
            }`}
          >
            <Shield className="w-4 h-4" />
            Industry Verticals ({meta?.verticals.length || 0})
          </button>
          <button
            onClick={() => { setActiveTab('taxonomy'); setStatusMsg(null); }}
            className={`px-4 py-3 text-xs font-bold border-b-2 flex items-center gap-2 transition-colors ${
              activeTab === 'taxonomy'
                ? 'border-slate-900 text-slate-900 dark:border-slate-100 dark:text-slate-100'
                : 'border-transparent text-slate-500 hover:text-slate-800 dark:hover:text-slate-200'
            }`}
          >
            <Tag className="w-4 h-4" />
            Taxonomy Stats ({meta?.totalAssets || 0} Assets)
          </button>
          <button
            onClick={() => { setActiveTab('announcements'); setStatusMsg(null); }}
            className={`px-4 py-3 text-xs font-bold border-b-2 flex items-center gap-2 transition-colors ${
              activeTab === 'announcements'
                ? 'border-slate-900 text-slate-900 dark:border-slate-100 dark:text-slate-100'
                : 'border-transparent text-slate-500 hover:text-slate-800 dark:hover:text-slate-200'
            }`}
          >
            <Bell className="w-4 h-4" />
            Partner Announcements
          </button>
        </div>

        {/* Status Message */}
        {statusMsg && (
          <div
            className={`px-6 py-3 text-xs font-medium flex items-center gap-2 ${
              statusMsg.type === 'success'
                ? 'bg-emerald-50 text-emerald-700 dark:bg-emerald-950/50 dark:text-emerald-300'
                : 'bg-rose-50 text-rose-700 dark:bg-rose-950/50 dark:text-rose-300'
            }`}
          >
            {statusMsg.type === 'success' ? <CheckCircle2 className="w-4 h-4" /> : <AlertCircle className="w-4 h-4" />}
            {statusMsg.text}
          </div>
        )}

        {/* Modal Body */}
        <div className="p-6 overflow-y-auto flex-1 custom-scrollbar">

          {/* TAB 1: Verticals */}
          {activeTab === 'verticals' && (
            <div className="space-y-6">
              {/* Create Vertical Form */}
              <form onSubmit={handleCreateVertical} className="p-4 rounded-xl bg-slate-50 dark:bg-slate-800/50 border border-slate-200 dark:border-slate-700 space-y-4">
                <h3 className="text-xs font-bold uppercase tracking-wider text-slate-700 dark:text-slate-300 flex items-center gap-2">
                  <Plus className="w-4 h-4 text-slate-700 dark:text-slate-300" />
                  Add New Industry Vertical
                </h3>
                <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                  <div className="sm:col-span-2">
                    <label className="block text-[11px] font-semibold text-slate-600 dark:text-slate-400 mb-1">
                      Vertical Name
                    </label>
                    <input
                      type="text"
                      placeholder="e.g. CleanTech & Renewables"
                      value={newVerticalName}
                      onChange={e => setNewVerticalName(e.target.value)}
                      className="w-full px-3 py-2 text-xs rounded-lg border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 text-slate-900 dark:text-slate-100 focus:ring-2 focus:ring-slate-400"
                    />
                  </div>
                  <div>
                    <label className="block text-[11px] font-semibold text-slate-600 dark:text-slate-400 mb-1">
                      Badge Color
                    </label>
                    <div className="flex items-center gap-2">
                      <input
                        type="color"
                        value={newVerticalColor}
                        onChange={e => setNewVerticalColor(e.target.value)}
                        className="w-9 h-9 p-0.5 rounded border border-slate-200 dark:border-slate-700 cursor-pointer"
                      />
                      <input
                        type="text"
                        value={newVerticalColor}
                        onChange={e => setNewVerticalColor(e.target.value)}
                        className="w-full px-2 py-1.5 text-xs font-mono rounded border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800"
                      />
                    </div>
                  </div>
                </div>
                <div>
                  <input
                    type="text"
                    placeholder="Short description of this vertical domain..."
                    value={newVerticalDesc}
                    onChange={e => setNewVerticalDesc(e.target.value)}
                    className="w-full px-3 py-2 text-xs rounded-lg border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 text-slate-900 dark:text-slate-100"
                  />
                </div>
                <div className="flex justify-end">
                  <button
                    type="submit"
                    disabled={loading || !newVerticalName.trim()}
                    className="px-4 py-2 rounded-lg bg-slate-900 hover:bg-slate-800 dark:bg-slate-100 dark:hover:bg-white text-white dark:text-slate-900 text-xs font-bold disabled:opacity-50 transition-all flex items-center gap-1.5"
                  >
                    <Plus className="w-4 h-4" />
                    Create Vertical
                  </button>
                </div>
              </form>

              {/* Verticals Table */}
              <div className="space-y-2">
                <h3 className="text-xs font-bold uppercase tracking-wider text-slate-400">
                  Active Verticals ({meta?.verticals.length || 0})
                </h3>
                <div className="divide-y divide-slate-100 dark:divide-slate-800 border border-slate-200 dark:border-slate-800 rounded-xl overflow-hidden">
                  {(meta?.verticals || []).map(v => (
                    <div key={v.id} className="p-3 bg-white dark:bg-slate-900 flex items-center justify-between text-xs">
                      <div className="flex items-center gap-3">
                        <span className="w-3 h-3 rounded-full shrink-0" style={{ backgroundColor: v.color || '#6366f1' }} />
                        <div>
                          <div className="font-semibold text-slate-900 dark:text-slate-100 flex items-center gap-2">
                            {v.name}
                            <span className="text-[10px] font-mono px-2 py-0.5 rounded-full bg-slate-100 dark:bg-slate-800 text-slate-500">
                              {v._count?.assets ?? 0} assets
                            </span>
                          </div>
                          {v.description && <div className="text-[11px] text-slate-400">{v.description}</div>}
                        </div>
                      </div>
                      <button
                        onClick={() => handleDeleteVertical(v.id, v.name)}
                        className="p-1.5 text-rose-500 hover:bg-rose-50 dark:hover:bg-rose-950/50 rounded-lg transition-colors"
                        title="Delete Vertical"
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}

          {/* TAB 2: Taxonomy Stats */}
          {activeTab === 'taxonomy' && (
            <div className="space-y-6">
              <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                <div className="p-4 rounded-xl bg-slate-50 dark:bg-slate-800/50 border border-slate-200 dark:border-slate-800">
                  <div className="text-2xl font-bold text-slate-900 dark:text-slate-100">{meta?.totalAssets || 0}</div>
                  <div className="text-xs text-slate-500 font-medium">Total Catalog Assets</div>
                </div>
                <div className="p-4 rounded-xl bg-slate-50 dark:bg-slate-800/50 border border-slate-200 dark:border-slate-800">
                  <div className="text-2xl font-bold text-emerald-600">{meta?.verticals.length || 0}</div>
                  <div className="text-xs text-slate-500 font-medium font-mono">Industry Verticals</div>
                </div>
                <div className="p-4 rounded-xl bg-slate-50 dark:bg-slate-800/50 border border-slate-200 dark:border-slate-800">
                  <div className="text-2xl font-bold text-amber-500">{meta?.subcategories.length || 0}</div>
                  <div className="text-xs text-slate-500 font-medium">Subcategories</div>
                </div>
                <div className="p-4 rounded-xl bg-slate-50 dark:bg-slate-800/50 border border-slate-200 dark:border-slate-800">
                  <div className="text-2xl font-bold text-cyan-600">{meta?.tags.length || 0}</div>
                  <div className="text-xs text-slate-500 font-medium">Unique Tags</div>
                </div>
              </div>

              <div>
                <h4 className="text-xs font-bold uppercase tracking-wider text-slate-500 dark:text-slate-400 mb-3">
                  Subcategory Breakdown (Click to Inspect Records)
                </h4>
                <div className="flex flex-wrap gap-2">
                  {(meta?.subcategories || []).map(s => (
                    <button
                      key={s.name}
                      onClick={() => setInspectFilter({ type: 'Subcategory', name: s.name })}
                      className={`px-3 py-1.5 rounded-lg border text-xs font-semibold transition-all cursor-pointer flex items-center gap-1.5 ${
                        inspectFilter?.name === s.name
                          ? 'bg-slate-900 text-white border-slate-900 dark:bg-slate-100 dark:text-slate-900'
                          : 'bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700 text-slate-700 dark:text-slate-300 hover:border-slate-400'
                      }`}
                    >
                      <span>{s.name}</span>
                      <span className="font-extrabold px-1.5 py-0.2 bg-slate-100 dark:bg-slate-700 rounded text-[10px]">
                        {s.count}
                      </span>
                    </button>
                  ))}
                </div>
              </div>

              <div>
                <h4 className="text-xs font-bold uppercase tracking-wider text-slate-500 dark:text-slate-400 mb-3">
                  Vertical Domain Distribution
                </h4>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
                  {(meta?.verticals || []).map(v => (
                    <button
                      key={v.id}
                      onClick={() => setInspectFilter({ type: 'Vertical', name: v.name, id: v.id })}
                      className={`p-3 rounded-xl border text-left transition-all cursor-pointer flex items-center justify-between ${
                        inspectFilter?.name === v.name
                          ? 'bg-slate-900 text-white border-slate-900 dark:bg-slate-100 dark:text-slate-900'
                          : 'bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700 text-slate-800 dark:text-slate-200 hover:border-slate-400'
                      }`}
                    >
                      <div className="flex items-center gap-2.5">
                        <span className="w-3 h-3 rounded-full shrink-0" style={{ backgroundColor: v.color || '#3b82f6' }} />
                        <span className="font-bold text-xs">{v.name}</span>
                      </div>
                      <span className="text-xs font-mono font-bold px-2 py-0.5 rounded bg-slate-100 dark:bg-slate-700">
                        {v._count?.assets ?? 0} assets
                      </span>
                    </button>
                  ))}
                </div>
              </div>

              {/* Inspect Filter Asset List Details */}
              {inspectFilter && (
                <div className="p-4 rounded-xl bg-slate-100 dark:bg-slate-800/80 border border-slate-300 dark:border-slate-700 space-y-3">
                  <div className="flex items-center justify-between">
                    <h5 className="text-xs font-extrabold text-slate-900 dark:text-slate-100 flex items-center gap-2">
                      <Tag className="w-4 h-4 text-amber-500" />
                      Inspecting {inspectFilter.type}: <span className="underline">{inspectFilter.name}</span>
                    </h5>
                    <button
                      onClick={() => setInspectFilter(null)}
                      className="text-[11px] font-bold text-slate-500 hover:text-slate-900 dark:hover:text-slate-100"
                    >
                      Clear Selection
                    </button>
                  </div>
                  <div className="divide-y divide-slate-200 dark:divide-slate-700/60 max-h-48 overflow-y-auto custom-scrollbar bg-white dark:bg-slate-900 rounded-lg border border-slate-200 dark:border-slate-700">
                    {matchingAssets.length === 0 ? (
                      <div className="p-4 text-xs text-center text-slate-500">No assets tagged with this {inspectFilter.type.toLowerCase()} yet.</div>
                    ) : (
                      matchingAssets.map(asset => (
                        <div key={asset.id} className="p-2.5 flex items-center justify-between text-xs hover:bg-slate-50 dark:hover:bg-slate-800/50">
                          <div className="min-w-0 flex-1 pr-3">
                            <div className="font-bold text-slate-900 dark:text-slate-100 truncate">{asset.title}</div>
                            <div className="text-[10px] text-slate-500 font-mono truncate">{asset.subcategory || asset.type} • {asset.url}</div>
                          </div>
                          <a
                            href={asset.url}
                            target="_blank"
                            rel="noreferrer"
                            className="px-2.5 py-1 text-[10px] font-bold bg-slate-100 dark:bg-slate-800 border border-slate-300 dark:border-slate-700 rounded text-slate-800 dark:text-slate-200 hover:bg-slate-200"
                          >
                            View Asset
                          </a>
                        </div>
                      ))
                    )}
                  </div>
                </div>
              )}
            </div>
          )}

          {/* TAB 3: Announcements */}
          {activeTab === 'announcements' && (
            <form onSubmit={handleSendAnnouncement} className="space-y-4">
              <div>
                <label className="block text-xs font-bold text-slate-700 dark:text-slate-300 mb-1">
                  Target Partner Organization
                </label>
                <select
                  value={selectedOrgId}
                  onChange={e => setSelectedOrgId(e.target.value)}
                  className="w-full px-3 py-2 text-xs rounded-lg border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 text-slate-900 dark:text-slate-100"
                >
                  <option value="ALL">All Partner Organizations (Broadcast)</option>
                  {organizations.map(org => (
                    <option key={org.id} value={org.id}>{org.name}</option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-xs font-bold text-slate-700 dark:text-slate-300 mb-1">
                  Announcement Title
                </label>
                <input
                  type="text"
                  placeholder="e.g. New Cybersecurity Case Studies & MVPs Released"
                  value={announcementTitle}
                  onChange={e => setAnnouncementTitle(e.target.value)}
                  className="w-full px-3 py-2 text-xs rounded-lg border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 text-slate-900 dark:text-slate-100"
                />
              </div>

              <div>
                <label className="block text-xs font-bold text-slate-700 dark:text-slate-300 mb-1">
                  Message Body
                </label>
                <textarea
                  rows={5}
                  placeholder="Write announcement details for partners..."
                  value={announcementMsg}
                  onChange={e => setAnnouncementMsg(e.target.value)}
                  className="w-full px-3 py-2 text-xs rounded-lg border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 text-slate-900 dark:text-slate-100 custom-scrollbar"
                />
              </div>

              <div className="flex justify-end pt-2">
                <button
                  type="submit"
                  disabled={loading || !announcementTitle.trim() || !announcementMsg.trim()}
                  className="px-5 py-2.5 rounded-xl bg-slate-900 hover:bg-slate-800 dark:bg-slate-100 dark:hover:bg-white text-white dark:text-slate-900 text-xs font-bold shadow-md disabled:opacity-50 transition-all flex items-center gap-2"
                >
                  <Send className="w-4 h-4" />
                  Dispatch Announcement
                </button>
              </div>
            </form>
          )}

        </div>
      </div>
    </div>
  );
};
