'use client';
import React, { useState, useEffect } from 'react';
import type { Options } from 'qr-code-styling';
import dynamic from 'next/dynamic';
import type { ExtendedOptions } from '@/components/qr-editor/LivePreview';
const LivePreview = dynamic(() => import('@/components/qr-editor/LivePreview'), { ssr: false });
import DesignPanel from '@/components/qr-editor/DesignPanel';
import api from '@/lib/api';
import { useRouter, useParams } from 'next/navigation';
import Link from 'next/link';

export default function EditQRPage() {
  const router = useRouter();
  const params = useParams();
  const qrId = params.id as string;
  
  const [loading, setLoading] = useState(true);
  const [qrName, setQrName] = useState('');
  const [qrType, setQrType] = useState<'dynamic' | 'static'>('dynamic');
  const [dataType, setDataType] = useState('URL');
  const [customSlug, setCustomSlug] = useState('');
  const [isSaving, setIsSaving] = useState(false);
  const [userRole, setUserRole] = useState<string>('free');
  const [tags, setTags] = useState<string[]>([]);
  const [tagInput, setTagInput] = useState('');
  
  // Data Type States
  const [urlData, setUrlData] = useState('https://ck-qr.com');
  const [vcardData, setVcardData] = useState({ firstName: '', lastName: '', phone: '', email: '', company: '', title: '' });
  const [emailData, setEmailData] = useState({ email: '', subject: '', body: '' });
  const [smsData, setSmsData] = useState({ phone: '', message: '' });
  const [wifiData, setWifiData] = useState({ ssid: '', password: '', encryption: 'WPA' });
  const [appStoreData, setAppStoreData] = useState({ ios: '', android: '', fallback: '' });

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

  
  const [qrOptions, setQrOptions] = useState<ExtendedOptions>({
    width: 300,
    height: 300,
    type: 'svg',
    data: `${baseUrl}/l/preview`,
    margin: 10,
    qrOptions: { typeNumber: 0, mode: 'Byte', errorCorrectionLevel: 'Q' },
    imageOptions: { hideBackgroundDots: true, imageSize: 0.4, margin: 5 },
    dotsOptions: { color: '#4f46e5', type: 'rounded' },
    backgroundOptions: { color: '#ffffff' },
    cornersSquareOptions: { color: '#4f46e5', type: 'extra-rounded' }
  });

  useEffect(() => {
    // Fetch user role
    api.get('/auth/me').then(res => {
      if (res.data?.user?.role) {
        setUserRole(res.data.user.role);
      }
    }).catch(() => {});

    // Fetch existing QR Data
    api.get(`/qr/${qrId}`).then(res => {
      const qr = res.data.qr_code;
      setQrName(qr.name);
      setQrType(qr.type);
      setDataType(qr.data_type || 'URL');
      setCustomSlug(qr.short_url_id || '');
      setTags(qr.tags || []);
      
      if (qr.data_type === 'URL' || !qr.data_type) setUrlData(qr.destination_url || '');
      else if (qr.data_type === 'vCard') setVcardData(qr.routing_data || {});
      else if (qr.data_type === 'Email') setEmailData(qr.routing_data || {});
      else if (qr.data_type === 'SMS') setSmsData(qr.routing_data || {});
      else if (qr.data_type === 'Wi-Fi') setWifiData(qr.routing_data || {});
      else if (qr.data_type === 'App Store') setAppStoreData(qr.routing_data || {});
      
      if (qr.design_data) {
        setQrOptions({
          ...qr.design_data,
          data: qr.type === 'static' ? qr.destination_url : `${baseUrl}/l/${qr.short_url_id}`
        });
      }
      setLoading(false);
    }).catch(err => {
      console.error(err);
      alert('Failed to load QR code');
      router.push('/dashboard');
    });
  }, [qrId, baseUrl, router]);

  // Keep QR data in sync with inputs
  useEffect(() => {
    if (loading) return;
    let payload = '';
    
    if (dataType === 'Wi-Fi' && qrType !== 'static') setQrType('static');
    if (dataType === 'App Store' && qrType !== 'dynamic') setQrType('dynamic');

    if (qrType === 'static') {
      if (dataType === 'URL') payload = urlData;
      else if (dataType === 'Wi-Fi') payload = `WIFI:T:${wifiData.encryption};S:${wifiData.ssid};P:${wifiData.password};;`;
      else if (dataType === 'Email') payload = `mailto:${emailData.email}?subject=${encodeURIComponent(emailData.subject)}&body=${encodeURIComponent(emailData.body)}`;
      else if (dataType === 'SMS') payload = `smsto:${smsData.phone}:${smsData.message}`;
      else if (dataType === 'vCard') payload = `BEGIN:VCARD\nVERSION:3.0\nN:${vcardData.lastName};${vcardData.firstName}\nFN:${vcardData.firstName} ${vcardData.lastName}\nORG:${vcardData.company}\nTITLE:${vcardData.title}\nTEL:${vcardData.phone}\nEMAIL:${vcardData.email}\nEND:VCARD`;
      else payload = urlData;
    } else {
      payload = `${baseUrl}/l/${customSlug}`;
    }

    setQrOptions(prev => ({ ...prev, data: payload || 'preview' }));
  }, [qrType, dataType, urlData, vcardData, emailData, smsData, wifiData, appStoreData, customSlug, baseUrl, loading]);

  const handleSlugChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (qrType === 'static') return;
    const val = e.target.value.replace(/[^a-zA-Z0-9-_]/g, '');
    setCustomSlug(val);
  };

  const handleAddTag = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter' || e.key === ',') {
      e.preventDefault();
      const val = tagInput.trim().replace(/,/g, '');
      if (val && !tags.includes(val)) {
        setTags([...tags, val]);
      }
      setTagInput('');
    }
  };
  const removeTag = (t: string) => setTags(tags.filter(tag => tag !== t));

  const handleSave = async () => {
    try {
      setIsSaving(true);
      
      let routingData = null;
      if (dataType === 'vCard') routingData = vcardData;
      else if (dataType === 'Email') routingData = emailData;
      else if (dataType === 'SMS') routingData = smsData;
      else if (dataType === 'Wi-Fi') routingData = wifiData;
      else if (dataType === 'App Store') routingData = appStoreData;

      await api.put(`/qr/${qrId}`, {
        name: qrName,
        dataType: dataType,
        destinationUrl: dataType === 'URL' ? urlData : undefined,
        routingData: routingData,
        shortUrlId: qrType === 'dynamic' ? customSlug : undefined,
        designData: qrOptions,
        tags: tags
      });
      
      alert('QR Code Successfully Updated!');
      router.push('/dashboard');
    } catch (err) {
      console.error(err);
      alert('Failed to update QR Code.');
    } finally {
      setIsSaving(false);
    }
  };

  const handleDownload = async (extension: 'png' | 'svg' = 'png') => {
    try {
      if (qrOptions.frameOptions?.enabled) {
        if (extension === 'svg') {
          alert("SVG export is not supported when a Frame is enabled.");
          return;
        }
        const { toPng } = await import('html-to-image');
        const node = document.getElementById('qr-preview-container');
        if (node) {
          const dataUrl = await toPng(node, { quality: 1, pixelRatio: 3 });
          const link = document.createElement('a');
          link.download = `${qrName || 'QR-Code'}.png`;
          link.href = dataUrl;
          link.click();
        }
      } else {
        const QRCodeStyling = (await import('qr-code-styling')).default;
        const qrCode = new QRCodeStyling(qrOptions);
        qrCode.download({ name: qrName || 'QR-Code', extension });
      }
    } catch (err) {
      console.error('Download failed', err);
      alert('Failed to download QR code');
    }
  };

  if (loading) {
    return <div className="p-12 text-center text-gray-500 font-sans">Loading Editor...</div>;
  }

  return (
    <div className="p-8 max-w-7xl mx-auto h-full font-sans">
      <div className="flex justify-between items-center mb-8">
        <div>
          <Link href="/dashboard" className="text-sm font-bold text-indigo-600 hover:underline mb-2 inline-block">
             &larr; Back to Dashboard
          </Link>
          <h1 className="text-3xl font-bold text-gray-800">Edit QR Code</h1>
          <p className="text-gray-500 mt-1">Update your QR destination and visual design</p>
        </div>
        <div className="flex gap-3">
          <div className="flex gap-2">
            <button 
              onClick={() => handleDownload('png')} 
              className="bg-white border border-gray-300 text-gray-700 px-6 py-2.5 rounded-lg hover:bg-gray-50 transition-colors font-semibold shadow-sm"
            >
              Download PNG
            </button>
            <button 
              onClick={() => handleDownload('svg')} 
              disabled={userRole === 'free' || userRole === 'free_trial'}
              className={`px-6 py-2.5 rounded-lg font-semibold shadow-sm transition-colors border border-gray-300 ${userRole === 'free' || userRole === 'free_trial' ? 'bg-gray-100 text-gray-400 cursor-not-allowed' : 'bg-white text-gray-700 hover:bg-gray-50'}`}
              title={userRole === 'free' || userRole === 'free_trial' ? 'SVG export is for Pro users' : 'Download SVG'}
            >
              {userRole === 'free' || userRole === 'free_trial' ? 'Download SVG (Pro)' : 'Download SVG'}
            </button>
          </div>
          <button 
            onClick={handleSave}
            disabled={isSaving}
            className="bg-indigo-600 text-white px-6 py-2.5 rounded-lg hover:bg-indigo-700 transition-colors font-semibold shadow-sm disabled:opacity-50"
          >
            {isSaving ? 'Saving...' : 'Save Changes'}
          </button>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 h-[calc(100vh-180px)]">
        {/* Left Column - Controls */}
        <div className="lg:col-span-7 xl:col-span-8 space-y-6 overflow-y-auto pr-2 pb-10">
          
          {/* Data Input Panel */}
          <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
            <h2 className="text-xl font-bold text-gray-800 border-b pb-4 mb-6">QR Content</h2>
            <div className="flex flex-col gap-6">
              
              {/* Type Selection */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">QR Type</label>
                <div className="p-3 bg-gray-50 rounded-lg border border-gray-200 text-gray-600 font-medium text-sm">
                  {qrType === 'dynamic' ? 'Dynamic (Trackable & Editable)' : 'Static (Permanent - Cannot change URL)'}
                  <span className="ml-2 text-xs text-gray-400 font-normal">(Type cannot be changed after creation)</span>
                </div>
              </div>
              {qrType === 'dynamic' && (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6 pt-4 border-t border-gray-100">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">Custom Short Link <span className="text-indigo-600 font-bold ml-1 text-xs px-2 py-0.5 bg-indigo-50 rounded-full border border-indigo-100">PRO</span></label>
                    <div className="flex rounded-md shadow-sm">
                      <span className="inline-flex items-center px-3 rounded-l-md border border-r-0 border-gray-300 bg-gray-50 text-gray-500 sm:text-sm">
                        ck-qr.com/l/
                      </span>
                      <input
                        type="text"
                        value={customSlug}
                        onChange={handleSlugChange}
                        disabled={userRole === 'free' || userRole === 'free_trial'}
                        className={`flex-1 min-w-0 block w-full px-3 py-3 rounded-none rounded-r-md border border-gray-300 focus:ring-indigo-500 focus:border-indigo-500 text-gray-900 sm:text-sm ${userRole === 'free' || userRole === 'free_trial' ? 'bg-gray-100 cursor-not-allowed' : ''}`}
                      />
                    </div>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">Tags</label>
                    <div className="flex flex-col gap-2">
                      <input
                        type="text"
                        value={tagInput}
                        onChange={e => setTagInput(e.target.value)}
                        onKeyDown={handleAddTag}
                        placeholder="Type and press Enter"
                        className="w-full border-gray-300 rounded-lg shadow-sm p-3 border focus:ring-indigo-500 focus:border-indigo-500 text-gray-900 sm:text-sm"
                      />
                      {tags.length > 0 && (
                        <div className="flex flex-wrap gap-2">
                          {tags.map(tag => (
                            <span key={tag} className="inline-flex items-center px-2 py-1 rounded-md text-xs font-medium bg-gray-100 text-gray-700">
                              {tag}
                              <button type="button" onClick={() => removeTag(tag)} className="ml-1 text-gray-400 hover:text-red-500">
                                <svg className="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" /></svg>
                              </button>
                            </span>
                          ))}
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              )}

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Data Type</label>
                <div className="flex flex-wrap gap-2">
                  {['URL', 'vCard', 'Email', 'SMS', 'Wi-Fi', 'App Store'].map(type => (
                    <button
                      key={type}
                      type="button"
                      onClick={() => setDataType(type)}
                      className={`px-3 py-1.5 text-sm rounded-lg border font-medium transition-colors ${dataType === type ? 'bg-indigo-50 border-indigo-200 text-indigo-700' : 'bg-white border-gray-200 text-gray-600 hover:bg-gray-50'}`}
                    >
                      {type}
                    </button>
                  ))}
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Internal Name</label>
                <input 
                  type="text" 
                  value={qrName}
                  onChange={e => setQrName(e.target.value)}
                  placeholder="e.g. Front Door Menu"
                  className="w-full border-gray-300 rounded-lg shadow-sm p-3 border focus:ring-indigo-500 focus:border-indigo-500 text-gray-900 bg-white"
                />
              </div>

              {/* Dynamic Forms based on dataType */}
              <div className="bg-gray-50 p-4 rounded-xl border border-gray-100">
                {dataType === 'URL' && (
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">Destination URL</label>
                    <input 
                      type="url" 
                      value={urlData}
                      onChange={e => setUrlData(e.target.value)}
                      placeholder="https://your-website.com"
                      className="w-full border-gray-300 rounded-lg shadow-sm p-3 border focus:ring-indigo-500 focus:border-indigo-500 text-gray-900 bg-white"
                    />
                  </div>
                )}

                {dataType === 'vCard' && (
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-xs font-medium text-gray-700 mb-1">First Name</label>
                      <input type="text" value={vcardData.firstName} onChange={e => setVcardData({...vcardData, firstName: e.target.value})} className="w-full border-gray-300 rounded-lg shadow-sm p-2 border focus:ring-indigo-500 text-gray-900 text-sm" />
                    </div>
                    <div>
                      <label className="block text-xs font-medium text-gray-700 mb-1">Last Name</label>
                      <input type="text" value={vcardData.lastName} onChange={e => setVcardData({...vcardData, lastName: e.target.value})} className="w-full border-gray-300 rounded-lg shadow-sm p-2 border focus:ring-indigo-500 text-gray-900 text-sm" />
                    </div>
                    <div>
                      <label className="block text-xs font-medium text-gray-700 mb-1">Phone</label>
                      <input type="tel" value={vcardData.phone} onChange={e => setVcardData({...vcardData, phone: e.target.value})} className="w-full border-gray-300 rounded-lg shadow-sm p-2 border focus:ring-indigo-500 text-gray-900 text-sm" />
                    </div>
                    <div>
                      <label className="block text-xs font-medium text-gray-700 mb-1">Email</label>
                      <input type="email" value={vcardData.email} onChange={e => setVcardData({...vcardData, email: e.target.value})} className="w-full border-gray-300 rounded-lg shadow-sm p-2 border focus:ring-indigo-500 text-gray-900 text-sm" />
                    </div>
                    <div>
                      <label className="block text-xs font-medium text-gray-700 mb-1">Company</label>
                      <input type="text" value={vcardData.company} onChange={e => setVcardData({...vcardData, company: e.target.value})} className="w-full border-gray-300 rounded-lg shadow-sm p-2 border focus:ring-indigo-500 text-gray-900 text-sm" />
                    </div>
                    <div>
                      <label className="block text-xs font-medium text-gray-700 mb-1">Title</label>
                      <input type="text" value={vcardData.title} onChange={e => setVcardData({...vcardData, title: e.target.value})} className="w-full border-gray-300 rounded-lg shadow-sm p-2 border focus:ring-indigo-500 text-gray-900 text-sm" />
                    </div>
                  </div>
                )}

                {dataType === 'Email' && (
                  <div className="space-y-3">
                    <div>
                      <label className="block text-xs font-medium text-gray-700 mb-1">Email To</label>
                      <input type="email" value={emailData.email} onChange={e => setEmailData({...emailData, email: e.target.value})} className="w-full border-gray-300 rounded-lg shadow-sm p-2 border focus:ring-indigo-500 text-gray-900 text-sm" />
                    </div>
                    <div>
                      <label className="block text-xs font-medium text-gray-700 mb-1">Subject</label>
                      <input type="text" value={emailData.subject} onChange={e => setEmailData({...emailData, subject: e.target.value})} className="w-full border-gray-300 rounded-lg shadow-sm p-2 border focus:ring-indigo-500 text-gray-900 text-sm" />
                    </div>
                    <div>
                      <label className="block text-xs font-medium text-gray-700 mb-1">Body</label>
                      <textarea value={emailData.body} onChange={e => setEmailData({...emailData, body: e.target.value})} className="w-full border-gray-300 rounded-lg shadow-sm p-2 border focus:ring-indigo-500 text-gray-900 text-sm h-20" />
                    </div>
                  </div>
                )}

                {dataType === 'SMS' && (
                  <div className="space-y-3">
                    <div>
                      <label className="block text-xs font-medium text-gray-700 mb-1">Phone Number</label>
                      <input type="tel" value={smsData.phone} onChange={e => setSmsData({...smsData, phone: e.target.value})} className="w-full border-gray-300 rounded-lg shadow-sm p-2 border focus:ring-indigo-500 text-gray-900 text-sm" />
                    </div>
                    <div>
                      <label className="block text-xs font-medium text-gray-700 mb-1">Message</label>
                      <textarea value={smsData.message} onChange={e => setSmsData({...smsData, message: e.target.value})} className="w-full border-gray-300 rounded-lg shadow-sm p-2 border focus:ring-indigo-500 text-gray-900 text-sm h-20" />
                    </div>
                  </div>
                )}

                {dataType === 'Wi-Fi' && (
                  <div className="space-y-3">
                    <div>
                      <label className="block text-xs font-medium text-gray-700 mb-1">Network Name (SSID)</label>
                      <input type="text" value={wifiData.ssid} onChange={e => setWifiData({...wifiData, ssid: e.target.value})} className="w-full border-gray-300 rounded-lg shadow-sm p-2 border focus:ring-indigo-500 text-gray-900 text-sm" />
                    </div>
                    <div>
                      <label className="block text-xs font-medium text-gray-700 mb-1">Password</label>
                      <input type="text" value={wifiData.password} onChange={e => setWifiData({...wifiData, password: e.target.value})} className="w-full border-gray-300 rounded-lg shadow-sm p-2 border focus:ring-indigo-500 text-gray-900 text-sm" />
                    </div>
                    <div>
                      <label className="block text-xs font-medium text-gray-700 mb-1">Encryption</label>
                      <select value={wifiData.encryption} onChange={e => setWifiData({...wifiData, encryption: e.target.value})} className="w-full border-gray-300 rounded-lg shadow-sm p-2 border focus:ring-indigo-500 text-gray-900 text-sm">
                        <option value="WPA">WPA/WPA2/WPA3</option>
                        <option value="WEP">WEP</option>
                        <option value="nopass">None</option>
                      </select>
                    </div>
                  </div>
                )}

                {dataType === 'App Store' && (
                  <div className="space-y-3">
                    <div>
                      <label className="block text-xs font-medium text-gray-700 mb-1">Apple App Store URL</label>
                      <input type="url" value={appStoreData.ios} onChange={e => setAppStoreData({...appStoreData, ios: e.target.value})} placeholder="https://apps.apple.com/..." className="w-full border-gray-300 rounded-lg shadow-sm p-2 border focus:ring-indigo-500 text-gray-900 text-sm" />
                    </div>
                    <div>
                      <label className="block text-xs font-medium text-gray-700 mb-1">Google Play Store URL</label>
                      <input type="url" value={appStoreData.android} onChange={e => setAppStoreData({...appStoreData, android: e.target.value})} placeholder="https://play.google.com/..." className="w-full border-gray-300 rounded-lg shadow-sm p-2 border focus:ring-indigo-500 text-gray-900 text-sm" />
                    </div>
                    <div>
                      <label className="block text-xs font-medium text-gray-700 mb-1">Fallback URL (Desktop)</label>
                      <input type="url" value={appStoreData.fallback} onChange={e => setAppStoreData({...appStoreData, fallback: e.target.value})} placeholder="https://your-website.com" className="w-full border-gray-300 rounded-lg shadow-sm p-2 border focus:ring-indigo-500 text-gray-900 text-sm" />
                    </div>
                  </div>
                )}
              </div>

              {qrType === 'dynamic' && (
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Custom Short Link</label>
                  <div className="flex flex-col sm:flex-row shadow-sm rounded-lg overflow-hidden border border-gray-300 focus-within:ring-2 focus-within:ring-indigo-500">
                      <span className="inline-flex items-center px-4 bg-gray-50 text-gray-500 border-r border-gray-300 text-sm whitespace-nowrap">
                          {baseUrl.replace(/^https?:\/\//, '')}/l/
                      </span>
                      <input 
                        type="text" 
                        value={customSlug}
                        onChange={handleSlugChange}
                        className="flex-1 w-full p-3 focus:outline-none text-gray-900 bg-white"
                      />
                  </div>
                </div>
              )}

            </div>
          </div>

          {/* Design Panel */}
          <DesignPanel options={qrOptions} onChange={setQrOptions} />

        </div>

        {/* Right Column - Live Preview Sticky */}
        <div className="lg:col-span-5 xl:col-span-4 relative hidden lg:block">
          <div className="sticky top-0 pt-4">
            <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6 flex flex-col items-center">
              <h3 className="font-semibold text-gray-700 mb-4 self-start">Live Preview</h3>
              <LivePreview options={qrOptions} />
              <p className="text-xs text-gray-400 mt-4 text-center">Scan to preview the destination</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}