'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 [customSlug, setCustomSlug] = useState('');
  const [isGenerating, setIsGenerating] = useState(false);
  
  const [qrOptions, setQrOptions] = useState<Options>({
    width: 300,
    height: 300,
    type: 'svg',
    data: 'https://ck-qr.com',
    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'
    }
  });

  // Keep QR data in sync with URL input
  const handleUrlChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newUrl = e.target.value;
    setDestinationUrl(newUrl);
    setQrOptions(prev => ({ ...prev, data: newUrl || 'https://ck-qr.com' }));
  };

  const handleGenerate = async () => {
    try {
      setIsGenerating(true);
      // Generate Dynamic QR via API
      const response = await api.post('/qr/generate', {
        name: qrName,
        customSlug: customSlug,
        type: 'dynamic',
        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);
    }
  };

  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>
        <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 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">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"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Destination URL</label>
                <input 
                  type="url" 
                  value={destinationUrl}
                  onChange={handleUrlChange}
                  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"
                />
                <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>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Custom Short Link (Optional)</label>
                <div className="flex 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">
                        /l/
                    </span>
                    <input 
                      type="text" 
                      value={customSlug}
                      onChange={e => setCustomSlug(e.target.value.replace(/[^a-zA-Z0-9-_]/g, ''))}
                      placeholder="my-promo"
                      className="flex-1 w-full p-3 focus:outline-none"
                    />
                </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>
  );
}
