'use client';
import React, { useEffect, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import api from '@/lib/api';
import LiveThumbnail from '@/components/qr-editor/LiveThumbnail';

interface QRCode {
  id: string;
  name: string;
  destination_url: string;
  short_url_id: string;
  created_at: string;
  scans: number;
  design_data: any;
  folder_id: string | null;
  data_type?: string;
  tags?: string[];
}

interface Folder {
  id: string;
  name: string;
}

export default function DashboardPage() {
  const router = useRouter();
  const [qrs, setQrs] = useState<QRCode[]>([]);
  const [folders, setFolders] = useState<Folder[]>([]);
  const [selectedFolder, setSelectedFolder] = useState<string | 'all' | 'default'>('all');
  const [tagFilter, setTagFilter] = useState('');
  const [loading, setLoading] = useState(true);
  const [userRole, setUserRole] = useState<string>('free');
  
  // Folder Creation State
  const [showFolderModal, setShowFolderModal] = useState(false);
  const [newFolderName, setNewFolderName] = useState('');
  
  // Move Folder State
  const [moveQrId, setMoveQrId] = useState<string | null>(null);

  const fetchFolders = async () => {
    try {
      const res = await api.get('/folders');
      setFolders(res.data.folders || []);
    } catch (err) {
      console.error("Failed to fetch folders", err);
    }
  };

  const fetchQRs = async () => {
    try {
      setLoading(true);
      let url = '/qr';
      if (selectedFolder !== 'all') {
        url += `?folderId=${selectedFolder}`;
      }
      
      const [res, authRes] = await Promise.all([
        api.get(url),
        api.get('/auth/me').catch(() => null)
      ]);
      setQrs(res.data.qr_codes || []);
      if (authRes?.data?.user?.role) {
        setUserRole(authRes.data.user.role);
      }
    } catch (err) {
      console.error("Failed to fetch data", err);
    } finally {
      setLoading(false);
    }
  };

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

  useEffect(() => {
    fetchQRs();
  }, [selectedFolder]);

  const handleCreateFolder = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newFolderName.trim()) return;
    try {
      const res = await api.post('/folders', { name: newFolderName });
      setFolders([res.data.folder, ...folders]);
      setShowFolderModal(false);
      setNewFolderName('');
      setSelectedFolder(res.data.folder.id);
    } catch (err) {
      alert('Failed to create folder');
    }
  };

  const handleDeleteFolder = async (id: string) => {
    if (!confirm('Are you sure? QRs in this folder will be moved to the default folder.')) return;
    try {
      await api.delete(`/folders/${id}`);
      setFolders(folders.filter(f => f.id !== id));
      if (selectedFolder === id) setSelectedFolder('all');
      fetchQRs(); // refresh QRs just in case
    } catch (err) {
      alert('Failed to delete folder');
    }
  };

  const handleMoveQr = async (folderId: string | 'default') => {
    if (!moveQrId) return;
    try {
      await api.put(`/qr/${moveQrId}`, { folderId });
      setMoveQrId(null);
      fetchQRs();
    } catch (err) {
      alert('Failed to move QR code');
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm('Are you sure you want to delete this QR code? The link will immediately stop working.')) return;
    try {
      await api.delete(`/qr/${id}`);
      setQrs(qrs.filter(qr => qr.id !== id));
    } catch (err) {
      alert('Failed to delete QR code');
    }
  };

  const handleDownload = async (qr: QRCode, extension: 'png' | 'svg' = 'png') => {
    try {
      const QRCodeStyling = (await import('qr-code-styling')).default;
      const baseUrl = process.env.NEXT_PUBLIC_APP_URL || 'https://qr.houseofwebsites.ai';
      const shortUrl = `${baseUrl}/l/${qr.short_url_id}`;
      
      const qrCode = new QRCodeStyling({
        ...qr.design_data,
        data: shortUrl
      });
      qrCode.download({ name: qr.name || 'QR-Code', extension: extension });
    } catch (err) {
      console.error('Failed to download QR code', err);
      alert('Failed to download QR code');
    }
  };

  const baseUrl = typeof window !== 'undefined' ? window.location.origin : (process.env.NEXT_PUBLIC_APP_URL || 'https://qr.houseofwebsites.ai');

  // Bulk Actions
  const [selectedQrs, setSelectedQrs] = useState<string[]>([]);
  const toggleSelectAll = () => {
    if (selectedQrs.length === qrs.length) setSelectedQrs([]);
    else setSelectedQrs(qrs.map(qr => qr.id));
  };
  const toggleSelectQr = (id: string) => {
    setSelectedQrs(prev => prev.includes(id) ? prev.filter(q => q !== id) : [...prev, id]);
  };
  
  const handleBulkDelete = async () => {
    if (!confirm(`Are you sure you want to delete ${selectedQrs.length} QR codes?`)) return;
    try {
      await api.post('/qr/bulk-delete', { ids: selectedQrs });
      setQrs(qrs.filter(qr => !selectedQrs.includes(qr.id)));
      setSelectedQrs([]);
    } catch (err) {
      alert('Failed to delete QR codes');
    }
  };

  const handleBulkMove = async (folderId: string | 'default') => {
    try {
      await api.post('/qr/bulk-move', { ids: selectedQrs, folderId });
      fetchQRs();
      setSelectedQrs([]);
    } catch (err) {
      alert('Failed to move QR codes');
    }
  };

  return (
    <div className="p-8 max-w-7xl mx-auto font-sans relative flex gap-8 flex-col md:flex-row">
      
      {/* Sidebar Folders */}
      <div className="w-full md:w-64 flex-shrink-0">
        <div className="bg-white rounded-2xl shadow-sm border border-gray-200 p-4 sticky top-8">
            <h2 className="text-lg font-bold text-gray-900 mb-4 px-2">Folders</h2>
            <div className="space-y-1 mb-6">
                <button 
                  onClick={() => setSelectedFolder('all')}
                  className={`w-full text-left px-3 py-2 rounded-lg transition-colors text-sm font-medium ${selectedFolder === 'all' ? 'bg-indigo-50 text-indigo-700' : 'text-gray-700 hover:bg-gray-100'}`}
                >
                  All QR Codes
                </button>
                <button 
                  onClick={() => setSelectedFolder('default')}
                  className={`w-full text-left px-3 py-2 rounded-lg transition-colors text-sm font-medium ${selectedFolder === 'default' ? 'bg-indigo-50 text-indigo-700' : 'text-gray-700 hover:bg-gray-100'}`}
                >
                  Default Folder
                </button>
                
                {folders.map(folder => (
                  <div key={folder.id} className="flex group">
                    <button 
                      onClick={() => setSelectedFolder(folder.id)}
                      className={`flex-1 text-left px-3 py-2 rounded-l-lg transition-colors text-sm font-medium truncate ${selectedFolder === folder.id ? 'bg-indigo-50 text-indigo-700' : 'text-gray-700 hover:bg-gray-100 group-hover:bg-gray-100'}`}
                    >
                      {folder.name}
                    </button>
                    <button onClick={() => handleDeleteFolder(folder.id)} className={`px-2 rounded-r-lg text-gray-400 hover:text-red-600 transition-colors ${selectedFolder === folder.id ? 'bg-indigo-50' : 'hover:bg-gray-100 group-hover:bg-gray-100'}`}>
                        <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" /></svg>
                    </button>
                  </div>
                ))}
            </div>
            
            <button 
              onClick={() => setShowFolderModal(true)}
              className="w-full flex items-center justify-center gap-2 bg-gray-50 border border-gray-200 text-gray-700 py-2 rounded-lg hover:bg-gray-100 transition-colors text-sm font-bold"
            >
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" /></svg>
              New Folder
            </button>
        </div>
      </div>

      <div className="flex-1 min-w-0">
          {/* Header */}
          <div className="flex justify-between items-center mb-6 bg-white p-6 rounded-2xl shadow-sm border border-gray-200">
            <div>
              <h1 className="text-3xl font-extrabold text-gray-900 tracking-tight">My QR Codes</h1>
              <p className="text-gray-500 mt-1">Manage, track, and dynamically route your active links.</p>
            </div>
            <div className="flex gap-4 items-center">
                <div className="relative">
                  <input
                    type="text"
                    placeholder="Filter by tag..."
                    value={tagFilter}
                    onChange={(e) => setTagFilter(e.target.value)}
                    className="pl-9 pr-4 py-2 border border-gray-300 rounded-lg text-sm focus:ring-indigo-500 focus:border-indigo-500 bg-gray-50 text-gray-900"
                  />
                  <svg className="w-4 h-4 text-gray-400 absolute left-3 top-2.5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" /></svg>
                </div>
                <Link 
                href="/dashboard/analytics" 
                className="bg-white border border-gray-300 text-gray-700 px-5 py-2.5 rounded-lg hover:bg-gray-50 transition-colors font-semibold flex items-center gap-2 shadow-sm"
                >
                <svg className="w-5 h-5 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" /></svg>
                Analytics
                </Link>
            </div>
          </div>

          {/* Bulk Actions Toolbar */}
          {selectedQrs.length > 0 && (
            <div className="bg-indigo-50 border border-indigo-100 rounded-xl p-3 mb-4 flex justify-between items-center animate-fade-in">
              <span className="text-indigo-700 font-semibold px-2">{selectedQrs.length} Selected</span>
              <div className="flex gap-2 relative">
                <div className="group relative">
                  <button className="bg-white border border-indigo-200 text-indigo-700 px-4 py-2 rounded-lg font-medium text-sm hover:bg-indigo-50 transition-colors">
                    Move to Folder
                  </button>
                  <div className="absolute right-0 mt-1 w-48 bg-white rounded-xl shadow-xl border border-gray-100 py-2 hidden group-hover:block z-20">
                    <button onClick={() => handleBulkMove('default')} className="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-indigo-50 hover:text-indigo-700">Default Folder</button>
                    {folders.map(f => (
                      <button key={f.id} onClick={() => handleBulkMove(f.id)} className="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-indigo-50 hover:text-indigo-700">{f.name}</button>
                    ))}
                  </div>
                </div>
                <button onClick={handleBulkDelete} className="bg-red-50 border border-red-200 text-red-600 px-4 py-2 rounded-lg font-medium text-sm hover:bg-red-100 transition-colors">
                  Delete
                </button>
              </div>
            </div>
          )}

          {/* Select All Row */}
          {qrs.length > 0 && (
            <div className="flex items-center px-6 py-2 mb-2 bg-white rounded-xl border border-gray-100 shadow-sm">
               <input 
                 type="checkbox" 
                 checked={selectedQrs.length === qrs.length && qrs.length > 0} 
                 onChange={toggleSelectAll} 
                 className="w-4 h-4 text-indigo-600 border-gray-300 rounded focus:ring-indigo-500 cursor-pointer" 
               />
               <span className="ml-3 text-sm font-medium text-gray-700">Select All</span>
            </div>
          )}

          {/* List View */}
          <div className="space-y-4">
            {loading ? (
              <div className="p-12 text-center text-gray-500 bg-white rounded-2xl shadow-sm border border-gray-200">Loading your dynamic links...</div>
            ) : qrs.filter(qr => !tagFilter || qr.tags?.some(tag => tag.toLowerCase().includes(tagFilter.toLowerCase()))).length === 0 ? (
              <div className="bg-white rounded-2xl shadow-sm border border-gray-200 p-16 text-center">
                <div className="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
                  <svg className="w-8 h-8 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1" /></svg>
                </div>
                <h3 className="text-xl font-bold text-gray-900 mb-2">No QR codes found</h3>
                <p className="text-gray-500 mb-6 max-w-sm mx-auto">Create a new QR code or adjust your filters.</p>
                <Link href="/dashboard/create" className="inline-block bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-3 px-8 rounded-xl transition-colors shadow-sm">Create New QR Code</Link>
              </div>
            ) : (
              qrs.filter(qr => !tagFilter || qr.tags?.some(tag => tag.toLowerCase().includes(tagFilter.toLowerCase()))).map((qr) => (
                <div key={qr.id} className={`bg-white rounded-2xl shadow-sm border p-6 flex flex-col md:flex-row items-center gap-8 hover:shadow-md transition-all relative group ${selectedQrs.includes(qr.id) ? 'border-indigo-400 ring-1 ring-indigo-400' : 'border-gray-200'}`}>
                    
                    {/* Checkbox */}
                    <div className="absolute top-6 left-6 md:relative md:top-0 md:left-0 z-10 bg-white md:bg-transparent p-1 md:p-0 rounded-md">
                      <input 
                        type="checkbox" 
                        checked={selectedQrs.includes(qr.id)}
                        onChange={() => toggleSelectQr(qr.id)}
                        className="w-5 h-5 text-indigo-600 border-gray-300 rounded focus:ring-indigo-500 cursor-pointer shadow-sm" 
                      />
                    </div>

                    {/* QR Image Custom Thumbnail */}
                    <div className="w-32 h-32 flex-shrink-0 flex items-center justify-center relative border border-gray-100 rounded-xl overflow-hidden bg-gray-50 mt-4 md:mt-0">
                       <LiveThumbnail options={{ ...qr.design_data, data: `${baseUrl}/l/${qr.short_url_id}` }} />
                    </div>

                    {/* Info Area */}
                    <div className="flex-1 min-w-0 w-full mt-4 md:mt-0">
                        <div className="flex items-center gap-3 mb-2">
                            <h3 className="text-xl font-bold text-gray-900 truncate">{qr.name}</h3>
                            <Link href={`/dashboard/edit/${qr.id}`} className="text-gray-400 hover:text-indigo-600 transition-colors" title="Edit QR settings">
                               <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z" /></svg>
                            </Link>
                        </div>
                        
                        <div className="mb-4">
                            <a href={`${baseUrl}/l/${qr.short_url_id}`} target="_blank" rel="noopener noreferrer" className="text-indigo-600 font-bold hover:underline flex items-center gap-1 text-sm bg-indigo-50 inline-flex px-3 py-1.5 rounded-lg border border-indigo-100 truncate max-w-full">
                                {baseUrl}/l/{qr.short_url_id}
                                <svg className="w-3 h-3 ml-1 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" /></svg>
                            </a>
                        </div>
                        
                        <div className="flex items-center gap-6 text-sm text-gray-500">
                            <div className="flex items-center gap-1">
                                <span className="font-semibold text-gray-700">Type:</span> {qr.data_type || 'URL'}
                            </div>
                            <div className="flex items-center gap-1">
                                <span className="font-semibold text-gray-700">Created:</span> {new Date(qr.created_at).toLocaleDateString()}
                            </div>
                        </div>

                        {qr.tags && qr.tags.length > 0 && (
                            <div className="flex flex-wrap gap-2 mt-3">
                                {qr.tags.map(tag => (
                                    <span key={tag} className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-gray-100 text-gray-600 border border-gray-200">
                                        #{tag}
                                    </span>
                                ))}
                            </div>
                        )}
                    </div>

                    {/* Metrics & Actions */}
                    <div className="flex flex-col sm:flex-row items-center gap-8 w-full md:w-auto">
                        <div className="text-center md:text-right">
                            <div className="text-3xl font-black text-gray-900">{qr.scans.toLocaleString()}</div>
                            <div className="text-sm text-gray-500 uppercase tracking-wider font-semibold">Scans</div>
                        </div>
                        
                        <div className="flex flex-col gap-2 w-full sm:w-48">
                            <div className="flex gap-2 w-full">
                                <button 
                                  onClick={() => handleDownload(qr, 'png')}
                                  className="flex-1 bg-green-500 hover:bg-green-600 text-white font-bold py-2 px-2 rounded-lg transition-colors flex justify-center items-center text-sm shadow-sm"
                                  title="Download PNG"
                                >
                                    PNG
                                </button>
                                <button 
                                  onClick={() => handleDownload(qr, 'svg')}
                                  disabled={userRole === 'free' || userRole === 'free_trial'}
                                  className={`flex-1 font-bold py-2 px-2 rounded-lg transition-colors flex justify-center items-center text-sm shadow-sm ${
                                    userRole === 'free' || userRole === 'free_trial' 
                                    ? 'bg-gray-200 text-gray-500 cursor-not-allowed' 
                                    : 'bg-green-500 hover:bg-green-600 text-white'
                                  }`}
                                  title={userRole === 'free' || userRole === 'free_trial' ? 'SVG export is for Pro users' : 'Download SVG'}
                                >
                                    {userRole === 'free' || userRole === 'free_trial' ? 'SVG (Pro)' : 'SVG'}
                                </button>
                            </div>
                            
                            <div className="flex gap-2">
                                <Link href={`/dashboard/edit/${qr.id}`} className="flex-1 bg-white border border-gray-300 hover:bg-gray-50 text-gray-700 font-semibold py-2 px-3 rounded-lg transition-colors text-sm text-center">
                                    Edit QR Code
                                </Link>
                                
                                {/* Move Folder Dropdown Toggle */}
                                <div className="relative">
                                  <button onClick={() => setMoveQrId(moveQrId === qr.id ? null : qr.id)} className="bg-white border border-gray-300 hover:bg-gray-50 text-gray-700 font-semibold py-2 px-3 rounded-lg transition-colors h-full">
                                      <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" /></svg>
                                  </button>
                                  {moveQrId === qr.id && (
                                    <div className="absolute right-0 mt-2 w-48 bg-white rounded-xl shadow-xl border border-gray-100 py-2 z-10">
                                      <div className="px-3 py-1 text-xs font-bold text-gray-400 uppercase tracking-wider">Move to Folder</div>
                                      <button onClick={() => handleMoveQr('default')} className="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-indigo-50 hover:text-indigo-700">Default Folder</button>
                                      {folders.map(f => (
                                        <button key={f.id} onClick={() => handleMoveQr(f.id)} className="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-indigo-50 hover:text-indigo-700">{f.name}</button>
                                      ))}
                                    </div>
                                  )}
                                </div>

                                <button onClick={() => handleDelete(qr.id)} className="bg-white border border-gray-300 hover:bg-red-50 hover:text-red-600 hover:border-red-200 text-gray-700 font-semibold py-2 px-3 rounded-lg transition-colors">
                                    <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" /></svg>
                                </button>
                            </div>
                        </div>
                    </div>

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

      {/* Folder Creation Modal */}
      {showFolderModal && (
          <div className="fixed inset-0 bg-gray-900/60 backdrop-blur-sm z-50 flex items-center justify-center p-4">
              <div className="bg-white rounded-2xl shadow-xl border border-gray-200 w-full max-w-md overflow-hidden transform transition-all">
                  <div className="px-6 py-5 border-b border-gray-100 flex justify-between items-center bg-gray-50">
                      <h3 className="text-lg font-bold text-gray-900">Create Folder</h3>
                      <button onClick={() => setShowFolderModal(false)} className="text-gray-400 hover:text-gray-600 transition-colors">
                          <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" /></svg>
                      </button>
                  </div>
                  
                  <form onSubmit={handleCreateFolder} className="p-6 space-y-5">
                      <div>
                          <label className="block text-sm font-bold text-gray-700 mb-2">Folder Name</label>
                          <input 
                            type="text" 
                            required
                            value={newFolderName}
                            onChange={e => setNewFolderName(e.target.value)}
                            className="w-full bg-white border border-gray-300 rounded-xl px-4 py-3 text-gray-900 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all shadow-sm"
                            placeholder="e.g., Summer Campaign"
                          />
                      </div>
                      <div className="pt-4 flex gap-3 border-t border-gray-100">
                          <button 
                            type="button" 
                            onClick={() => setShowFolderModal(false)}
                            className="flex-1 bg-white border border-gray-300 text-gray-700 font-bold py-3 px-4 rounded-xl hover:bg-gray-50 transition-colors"
                          >
                              Cancel
                          </button>
                          <button 
                            type="submit" 
                            className="flex-1 bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-3 px-4 rounded-xl transition-colors shadow-sm"
                          >
                              Create Folder
                          </button>
                      </div>
                  </form>
              </div>
          </div>
      )}

    </div>
  );
}