'use client';
import React, { useState } from 'react';
import type { Options } from 'qr-code-styling';
import dynamic from 'next/dynamic';
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 [destinationUrl, setDestinationUrl] = useState('https://ck-qr.com');
  const [qrName, setQrName] = useState('');
  const [qrType, setQrType] = useState<'dynamic' | 'static'>('dynamic');
  const [customSlug, setCustomSlug] = useState('');
  const [randomSlug, setRandomSlug] = useState('');
  const [isGenerating, setIsGenerating] = useState(false);
  const [userRole, setUserRole] = useState<string>('free');
  const baseUrl = typeof window !== 'undefined' ? (process.env.NEXT_PUBLIC_APP_URL || 'https://qr.houseofwebsites.ai') : 'https://qr.houseofwebsites.ai';
  
  const [qrOptions, setQrOptions] = useState<Options>({
    width: 300,
    height: 300,
    type: 'svg',
    data: `${baseUrl}/l/preview`, // Will be updated in useEffect
    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'
    }
  });

  // Generate random slug on mount to prevent SSR hydration errors
  React.useEffect(() => {
    const generated = Math.random().toString(36).substring(2, 8);
    setRandomSlug(generated);
    if (qrType === 'dynamic') {
      setQrOptions(prev => ({ ...prev, data: `${baseUrl}/l/${generated}` }));
    } else {
      setQrOptions(prev => ({ ...prev, data: destinationUrl }));
    }

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

  // Keep QR data in sync with type and destinationUrl
  React.useEffect(() => {
    if (qrType === 'static') {
      setQrOptions(prev => ({ ...prev, data: destinationUrl }));
    } else {
      setQrOptions(prev => ({ ...prev, data: `${baseUrl}/l/${customSlug || randomSlug}` }));
    }
  }, [qrType, destinationUrl]);

  // Keep QR data in sync with custom slug
  const handleSlugChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const val = e.target.value.replace(/[^a-zA-Z0-9-_]/g, '');
    setCustomSlug(val);
    setQrOptions(prev => ({ ...prev, data: `${baseUrl}/l/${val || randomSlug}` }));
  };

  const handleGenerate = async () => {
    try {
      setIsGenerating(true);
      // Generate Dynamic QR via API
      const response = await api.post('/qr/generate', {
        name: qrName,
        customSlug: qrType === 'dynamic' ? (customSlug || randomSlug) : undefined, // Pass the previewed slug so the backend uses it!
        type: qrType,
        dataType: 'URL',
        destinationUrl: destinationUrl,
        designData: qrOptions
      });
      
      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 {
      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 justify-between items-center mb-8">
        <div>
          <h1 className="text-3xl font-bold text-gray-800">Create QR Code</h1>
          <p className="text-gray-500 mt-1">Design a beautiful, dynamic QR code</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={handleGenerate}
            disabled={isGenerating}
            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"
          >
            {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">
              
              <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-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>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Destination URL</label>
                <input 
                  type="url" 
                  value={destinationUrl}
                  onChange={e => setDestinationUrl(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"
                />
                {qrType === 'dynamic' && (
                  <p className="text-xs text-gray-500 mt-2">This is a dynamic QR. You can change this URL later without reprinting the code.</p>
                )}
                {qrType === 'static' && (
                  <p className="text-xs text-gray-500 mt-2">This URL is embedded directly into the code and cannot be changed later.</p>
                )}
              </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>
  );
}
