'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 } from 'next/navigation';

export default function CreateQRPage() {
  const router = useRouter();
  const [qrName, setQrName] = useState('');
  const [qrType, setQrType] = useState('dynamic'); // 'static' or 'dynamic'
  const [dataType, setDataType] = useState('URL');
  const [customSlug, setCustomSlug] = useState('');
  const [randomSlug, setRandomSlug] = useState('');
  const [isGenerating, setIsGenerating] = useState(false);
  const [userRole, setUserRole] = useState('free');
  const [tags, setTags] = useState<string[]>([]);
  const [tagInput, setTagInput] = useState('');
  
  // Data Type States
  const [urlData, setUrlData] = useState('https://example.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(() => {
    const generated = Math.random().toString(36).substring(2, 8);
    setRandomSlug(generated);
    api.get('/auth/me').then(res => {
      if (res.data?.user?.role) setUserRole(res.data.user.role);
    }).catch(() => {});
  }, []);

  // Update QR Data when inputs change
  useEffect(() => {
    let payload = '';
    
    // Force static for WiFi
    if (dataType === 'Wi-Fi' && qrType !== 'static') {
      setQrType('static');
      alert('Wi-Fi QR Codes must be Static.');
    }
    // Force dynamic for App Store
    if (dataType === 'App Store' && qrType !== 'dynamic') {
      setQrType('dynamic');
      alert('App Store QR Codes must be 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; // fallback
    } else {
      payload = `${baseUrl}/l/${customSlug || randomSlug}`;
    }

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

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

  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 handleGenerate = async () => {
    try {
      setIsGenerating(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.post('/qr/generate', {
        name: qrName,
        customSlug: qrType === 'dynamic' ? (customSlug || randomSlug) : undefined,
        type: qrType,
        dataType: dataType,
        destinationUrl: dataType === 'URL' ? urlData : undefined,
        routingData: routingData,
        designData: qrOptions,
        tags: tags
      });
      
      alert('QR Code Successfully Generated & Saved!');
      router.push('/dashboard');
    } catch (err) {
      console.error(err);
      alert('Failed to generate QR Code. Ensure you are logged in.');
    } finally {
      setIsGenerating(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');
    }
  };

  return (
    <div className="p-8 max-w-7xl mx-auto h-full">
      <div className="flex items-center gap-4 mb-8 justify-between">
        <div className="flex items-center gap-4">
          <button onClick={() => router.back()} className="p-2 hover:bg-gray-100 rounded-full transition-colors">
            <svg className="w-6 h-6 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" /></svg>
          </button>
          <div>
              <h1 className="text-3xl font-extrabold text-gray-900 tracking-tight">Create QR Code</h1>
              <p className="text-gray-500 mt-1">Design and configure a new QR code.</p>
          </div>
        </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={handleGenerate}
            disabled={isGenerating || !qrName}
            className={`px-8 py-2.5 rounded-lg font-bold shadow-sm transition-all text-white ${
              (isGenerating || !qrName) ? 'bg-indigo-400 cursor-not-allowed' : 'bg-indigo-600 hover:bg-indigo-700'
            }`}
          >
            {isGenerating ? 'Saving...' : 'Save QR Code'}
          </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="flex gap-4">
                  <label className="flex items-center gap-2 cursor-pointer">
                    <input 
                      type="radio" 
                      name="qrType" 
                      value="dynamic" 
                      checked={qrType === 'dynamic'}
                      onChange={() => setQrType('dynamic')}
                      className="text-indigo-600 focus:ring-indigo-500"
                    />
                    <span className="text-gray-900 font-medium">Dynamic (Trackable & Editable)</span>
                  </label>
                  <label className="flex items-center gap-2 cursor-pointer">
                    <input 
                      type="radio" 
                      name="qrType" 
                      value="static" 
                      checked={qrType === 'static'}
                      onChange={() => setQrType('static')}
                      className="text-indigo-600 focus:ring-indigo-500"
                    />
                    <span className="text-gray-900 font-medium">Static (Permanent)</span>
                  </label>
                </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 (Optional)</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">
                          {(process.env.NEXT_PUBLIC_APP_URL || 'https://qr.houseofwebsites.ai').replace(/^https?:\/\//, '')}/l/
                      </span>
                      <input 
                        type="text" 
                        value={customSlug}
                        onChange={handleSlugChange}
                        placeholder={randomSlug || "my-promo"}
                        className="flex-1 w-full p-3 focus:outline-none text-gray-900 bg-white"
                      />
                  </div>
                  <p className="text-xs text-gray-500 mt-2">Leave blank to auto-generate a random link.</p>
                </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>
  );
}
