'use client';
import React, { useEffect, useState } from 'react';
import Link from 'next/link';
import api from '@/lib/api';

interface QRCode {
  id: string;
  name: string;
  destination_url: string;
  short_url_id: string;
  created_at: string;
  scans: number;
}

export default function DashboardPage() {
  const [qrs, setQrs] = useState<QRCode[]>([]);
  const [loading, setLoading] = useState(true);
  
  // Edit Modal State
  const [editingQr, setEditingQr] = useState<QRCode | null>(null);
  const [editName, setEditName] = useState('');
  const [editUrl, setEditUrl] = useState('');
  const [editSlug, setEditSlug] = useState('');
  const [editError, setEditError] = useState('');
  const [editLoading, setEditLoading] = useState(false);

  const fetchQRs = async () => {
    try {
      const res = await api.get('/qr');
      setQrs(res.data.qr_codes || []);
    } catch (err) {
      console.error("Failed to fetch QRs", err);
    } finally {
      setLoading(false);
    }
  };

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

  const openEditModal = (qr: QRCode) => {
    setEditingQr(qr);
    setEditName(qr.name);
    setEditUrl(qr.destination_url);
    setEditSlug(qr.short_url_id);
    setEditError('');
  };

  const handleEditSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!editingQr) return;
    setEditLoading(true);
    setEditError('');

    try {
      await api.put(`/qr/${editingQr.id}`, {
        name: editName,
        destinationUrl: editUrl,
        shortUrlId: editSlug
      });
      // Refresh list
      await fetchQRs();
      setEditingQr(null);
    } catch (err: any) {
      setEditError(err.response?.data?.error || 'Failed to update QR code');
    } finally {
      setEditLoading(false);
    }
  };

  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 totalScans = qrs.reduce((sum, qr) => sum + Number(qr.scans), 0);
  const baseUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:4001';

  return (
    <div className="p-8 max-w-7xl mx-auto font-sans relative">
      
      {/* Header */}
      <div className="flex justify-between items-center mb-8 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">
            <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"
            >
            <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>

      {/* Verification Warning (Mock ME-QR style) */}
      <div className="bg-red-50 border-l-4 border-red-500 p-4 mb-8 rounded-r-xl flex justify-between items-center shadow-sm">
         <div>
            <h3 className="text-red-800 font-bold">WARNING!</h3>
            <p className="text-red-700 text-sm">Your email should be verified to prevent link expiration.</p>
         </div>
         <button className="bg-green-500 hover:bg-green-600 text-white font-bold py-2 px-6 rounded-lg transition-colors">
            Verify Email
         </button>
      </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.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 yet</h3>
            <p className="text-gray-500 mb-6 max-w-sm mx-auto">Create your first dynamic link to generate a trackable QR code.</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.map((qr) => (
            <div key={qr.id} className="bg-white rounded-2xl shadow-sm border border-gray-200 p-6 flex flex-col md:flex-row items-center gap-8 hover:shadow-md transition-shadow relative group">
                
                {/* QR Image Placeholder (In real app, fetch from backend) */}
                <div className="w-32 h-32 bg-gray-100 rounded-xl border border-gray-200 flex-shrink-0 flex items-center justify-center p-2">
                   <img src={`https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=${encodeURIComponent(baseUrl + '/l/' + qr.short_url_id)}`} alt="QR" className="w-full h-full object-contain" />
                </div>

                {/* Info Area */}
                <div className="flex-1 min-w-0 w-full">
                    <div className="flex items-center gap-3 mb-2">
                        <h3 className="text-xl font-bold text-gray-900 truncate">{qr.name}</h3>
                        <button onClick={() => openEditModal(qr)} className="text-gray-400 hover:text-indigo-600 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="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>
                        </button>
                    </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">
                            {baseUrl}/l/{qr.short_url_id}
                            <svg className="w-3 h-3 ml-1" 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> Link
                        </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>
                </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">
                        <button className="w-full bg-green-500 hover:bg-green-600 text-white font-bold py-2.5 px-4 rounded-lg transition-colors flex justify-center items-center gap-2 shadow-sm border border-transparent">
                            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" /></svg>
                            Download
                        </button>
                        
                        <div className="flex gap-2">
                            <button onClick={() => openEditModal(qr)} 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">
                                Edit Link
                            </button>
                            <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>

      {/* Edit Modal Overlay */}
      {editingQr && (
          <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-lg 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">Edit Dynamic Link</h3>
                      <button onClick={() => setEditingQr(null)} 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={handleEditSubmit} className="p-6 space-y-5">
                      {editError && (
                          <div className="bg-red-50 text-red-600 p-3 rounded-lg text-sm border border-red-100 font-medium">
                              {editError}
                          </div>
                      )}
                      
                      <div>
                          <label className="block text-sm font-bold text-gray-700 mb-2">QR Title (Internal)</label>
                          <input 
                            type="text" 
                            required
                            value={editName}
                            onChange={e => setEditName(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"
                          />
                      </div>

                      <div>
                          <label className="block text-sm font-bold text-gray-700 mb-2">Destination URL</label>
                          <input 
                            type="url" 
                            required
                            value={editUrl}
                            onChange={e => setEditUrl(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="https://yourwebsite.com/new-campaign"
                          />
                          <p className="text-xs text-gray-500 mt-2">Where should scanners be instantly redirected?</p>
                      </div>

                      <div>
                          <label className="block text-sm font-bold text-gray-700 mb-2">Custom Short Slug</label>
                          <div className="flex flex-col sm:flex-row shadow-sm rounded-xl overflow-hidden border border-gray-300 focus-within:ring-2 focus-within:ring-indigo-500 focus-within:border-transparent transition-all">
                              <span className="inline-flex items-center px-4 bg-gray-50 text-gray-500 font-medium text-sm sm:border-r border-gray-300">
                                  {baseUrl.replace(/^https?:\/\//, '')}/l/
                              </span>
                              <input 
                                type="text" 
                                required
                                value={editSlug}
                                onChange={e => setEditSlug(e.target.value.replace(/[^a-zA-Z0-9-_]/g, ''))}
                                className="flex-1 bg-white px-4 py-3 text-gray-900 focus:outline-none font-bold"
                                placeholder="my-custom-slug"
                              />
                          </div>
                          <p className="text-xs text-gray-500 mt-2">Only letters, numbers, hyphens, and underscores.</p>
                      </div>

                      <div className="pt-4 flex gap-3 border-t border-gray-100">
                          <button 
                            type="button" 
                            onClick={() => setEditingQr(null)}
                            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" 
                            disabled={editLoading}
                            className="flex-1 bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-3 px-4 rounded-xl transition-colors shadow-sm disabled:opacity-50"
                          >
                              {editLoading ? 'Saving...' : 'Save Changes'}
                          </button>
                      </div>
                  </form>
              </div>
          </div>
      )}

    </div>
  );
}
