import React, { useState, useEffect, useMemo, useRef } from 'react';
import ReactDOM from 'react-dom/client';
import { QRCodeCanvas, QRCodeSVG } from 'qrcode.react';
import { 
  QrCode, 
  Search, 
  Trash2, 
  Plus, 
  Building2, 
  Link as LinkIcon, 
  Calendar,
  AlertCircle,
  Image as ImageIcon,
  Code,
  Pencil,
  X,
  Globe,
  Palette
} from 'lucide-react';

// --- TYPES ---
interface QRRecord {
  id: string;
  companyName: string;
  url: string;
  createdAt: number;
  fgColor?: string;
  bgColor?: string;
  logo?: string; // Base64 string
}

// --- STORAGE SERVICE ---
const STORAGE_KEY = 'qr_manager_db_v1';

const getRecords = (): QRRecord[] => {
  try {
    const data = localStorage.getItem(STORAGE_KEY);
    return data ? JSON.parse(data) : [];
  } catch (error) {
    console.error('Veri okunurken hata oluştu:', error);
    return [];
  }
};

const saveRecord = (record: QRRecord): QRRecord[] => {
  const current = getRecords();
  const updated = [record, ...current];
  localStorage.setItem(STORAGE_KEY, JSON.stringify(updated));
  return updated;
};

const updateRecord = (record: QRRecord): QRRecord[] => {
  const current = getRecords();
  const updated = current.map(item => item.id === record.id ? record : item);
  localStorage.setItem(STORAGE_KEY, JSON.stringify(updated));
  return updated;
};

const deleteRecord = (id: string): QRRecord[] => {
  const current = getRecords();
  const updated = current.filter(item => item.id !== id);
  localStorage.setItem(STORAGE_KEY, JSON.stringify(updated));
  return updated;
};

const generateId = (): string => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2);
};

// --- APP COMPONENT ---
const App: React.FC = () => {
  // State
  const [records, setRecords] = useState<QRRecord[]>([]);
  const [companyName, setCompanyName] = useState('');
  const [url, setUrl] = useState('');
  const [fgColor, setFgColor] = useState('#000000');
  const [bgColor, setBgColor] = useState('#ffffff');
  const [logo, setLogo] = useState<string | null>(null);
  
  const [searchTerm, setSearchTerm] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [successMsg, setSuccessMsg] = useState<string | null>(null);
  const [editingId, setEditingId] = useState<string | null>(null);

  const fileInputRef = useRef<HTMLInputElement>(null);

  // Load data on mount
  useEffect(() => {
    setRecords(getRecords());
  }, []);

  // Handle Logo Upload
  const handleLogoUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      if (file.size > 500000) { // 500KB limit
        setError("Logo boyutu çok yüksek. Lütfen 500KB altı bir resim seçin.");
        return;
      }
      const reader = new FileReader();
      reader.onloadend = () => {
        setLogo(reader.result as string);
      };
      reader.readAsDataURL(file);
    }
  };

  const clearLogo = () => {
    setLogo(null);
    if (fileInputRef.current) fileInputRef.current.value = '';
  };

  // Form Submission
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setSuccessMsg(null);

    if (!companyName.trim() || !url.trim()) {
      setError('Lütfen firma adı ve link alanlarını doldurunuz.');
      return;
    }

    // Basic URL validation
    let formattedUrl = url;
    if (!/^https?:\/\//i.test(formattedUrl)) {
      formattedUrl = 'https://' + formattedUrl;
    }

    if (editingId) {
      // Update existing record
      const originalRecord = records.find(r => r.id === editingId);
      const updatedRecord: QRRecord = {
        id: editingId,
        companyName: companyName.trim(),
        url: formattedUrl,
        createdAt: originalRecord ? originalRecord.createdAt : Date.now(),
        fgColor,
        bgColor,
        logo: logo || undefined
      };
      
      const updatedList = updateRecord(updatedRecord);
      setRecords(updatedList);
      setSuccessMsg('Kayıt başarıyla güncellendi.');
      setEditingId(null);
    } else {
      // Create new record
      const newRecord: QRRecord = {
        id: generateId(),
        companyName: companyName.trim(),
        url: formattedUrl,
        createdAt: Date.now(),
        fgColor,
        bgColor,
        logo: logo || undefined
      };

      const updatedRecords = saveRecord(newRecord);
      setRecords(updatedRecords);
      setSuccessMsg('QR Kod başarıyla oluşturuldu ve listeye eklendi.');
    }
    
    // Reset form
    resetForm();
    
    // Auto hide success message
    setTimeout(() => setSuccessMsg(null), 3000);
  };

  const resetForm = () => {
    setCompanyName('');
    setUrl('');
    setFgColor('#000000');
    setBgColor('#ffffff');
    setLogo(null);
    if (fileInputRef.current) fileInputRef.current.value = '';
  };

  // Edit Handler
  const handleEdit = (record: QRRecord) => {
    setEditingId(record.id);
    setCompanyName(record.companyName);
    setUrl(record.url);
    setFgColor(record.fgColor || '#000000');
    setBgColor(record.bgColor || '#ffffff');
    setLogo(record.logo || null);
    setError(null);
    setSuccessMsg(null);
    
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  // Cancel Edit Handler
  const handleCancelEdit = () => {
    setEditingId(null);
    resetForm();
    setError(null);
  };

  // Delete Handler
  const handleDelete = (id: string) => {
    if (window.confirm('Bu kaydı silmek istediğinize emin misiniz?')) {
      const updated = deleteRecord(id);
      setRecords(updated);
      
      if (editingId === id) {
        handleCancelEdit();
      }
    }
  };

  // Download Handlers
  const downloadPNG = (id: string, fileName: string) => {
    const canvas = document.getElementById(`qr-canvas-${id}`) as HTMLCanvasElement;
    if (canvas) {
      const pngUrl = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
      const downloadLink = document.createElement("a");
      downloadLink.href = pngUrl;
      downloadLink.download = `${fileName}.png`;
      document.body.appendChild(downloadLink);
      downloadLink.click();
      document.body.removeChild(downloadLink);
    }
  };

  const downloadSVG = (id: string, fileName: string) => {
    const svgElement = document.getElementById(`qr-svg-${id}`);
    if (svgElement) {
      const serializer = new XMLSerializer();
      const svgString = serializer.serializeToString(svgElement);
      const blob = new Blob([svgString], {type: "image/svg+xml;charset=utf-8"});
      const url = URL.createObjectURL(blob);
      const downloadLink = document.createElement("a");
      downloadLink.href = url;
      downloadLink.download = `${fileName}.svg`;
      document.body.appendChild(downloadLink);
      downloadLink.click();
      document.body.removeChild(downloadLink);
      URL.revokeObjectURL(url);
    }
  };

  // Filtering
  const filteredRecords = useMemo(() => {
    return records.filter(record => 
      record.companyName.toLowerCase().includes(searchTerm.toLowerCase()) ||
      record.url.toLowerCase().includes(searchTerm.toLowerCase())
    );
  }, [records, searchTerm]);

  return (
    <div className="min-h-screen bg-slate-50 text-gray-800 font-sans flex flex-col">
      {/* Header */}
      <header className="bg-white border-b border-gray-200 sticky top-0 z-20 shadow-sm">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 h-16 flex items-center justify-between">
          <div className="flex items-center space-x-3">
            <div className="bg-slate-800 p-2 rounded-lg">
              <QrCode className="text-white w-6 h-6" />
            </div>
            <h1 className="text-xl font-bold text-gray-900 tracking-tight">Gloqr</h1>
          </div>
          <div className="text-sm text-gray-500 hidden sm:block">
            Şirket İçi Link Yöneticisi
          </div>
        </div>
      </header>

      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 flex-grow w-full">
        
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          
          {/* Left Column: Generator Form */}
          <div className="lg:col-span-1">
            <div className={`rounded-xl shadow-sm border p-6 sticky top-24 transition-colors ${editingId ? 'bg-blue-50 border-blue-200' : 'bg-white border-gray-200'}`}>
              <h2 className={`text-lg font-semibold mb-4 flex items-center ${editingId ? 'text-blue-900' : 'text-gray-900'}`}>
                {editingId ? (
                  <>
                    <Pencil className="w-5 h-5 mr-2 text-blue-600" />
                    QR Düzenle
                  </>
                ) : (
                  <>
                    <Plus className="w-5 h-5 mr-2 text-blue-600" />
                    Yeni QR Oluştur
                  </>
                )}
              </h2>
              
              <form onSubmit={handleSubmit} className="space-y-4">
                {/* Text Inputs */}
                <div>
                  <label htmlFor="company" className="block text-sm font-medium text-gray-700 mb-1">
                    Firma / Açıklama
                  </label>
                  <div className="relative">
                    <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                      <Building2 className="h-5 w-5 text-gray-400" />
                    </div>
                    <input
                      type="text"
                      id="company"
                      value={companyName}
                      onChange={(e) => setCompanyName(e.target.value)}
                      className="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-lg focus:ring-blue-500 focus:border-blue-500 sm:text-sm transition-colors"
                      placeholder="Örn: Pazarlama Sunumu"
                    />
                  </div>
                </div>

                <div>
                  <label htmlFor="url" className="block text-sm font-medium text-gray-700 mb-1">
                    Hedef Link (URL)
                  </label>
                  <div className="relative">
                    <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                      <LinkIcon className="h-5 w-5 text-gray-400" />
                    </div>
                    <input
                      type="text"
                      id="url"
                      value={url}
                      onChange={(e) => setUrl(e.target.value)}
                      className="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-lg focus:ring-blue-500 focus:border-blue-500 sm:text-sm transition-colors"
                      placeholder="www.globalmedia.com/dosya"
                    />
                  </div>
                </div>

                {/* Customization Section */}
                <div className="bg-slate-50 p-3 rounded-lg border border-slate-200 space-y-3">
                  <div className="flex items-center space-x-2 mb-2">
                    <Palette className="w-4 h-4 text-slate-500" />
                    <span className="text-sm font-medium text-slate-700">Görsel Özelleştirme</span>
                  </div>
                  
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <label className="block text-xs text-gray-500 mb-1">QR Rengi</label>
                      <div className="flex items-center space-x-2">
                        <input 
                          type="color" 
                          value={fgColor}
                          onChange={(e) => setFgColor(e.target.value)}
                          className="h-8 w-full rounded cursor-pointer border-0 p-0"
                        />
                      </div>
                    </div>
                    <div>
                      <label className="block text-xs text-gray-500 mb-1">Arka Plan</label>
                      <div className="flex items-center space-x-2">
                         <input 
                          type="color" 
                          value={bgColor}
                          onChange={(e) => setBgColor(e.target.value)}
                          className="h-8 w-full rounded cursor-pointer border-0 p-0"
                        />
                      </div>
                    </div>
                  </div>

                  <div>
                    <label className="block text-xs text-gray-500 mb-1">Logo Ekle (İsteğe Bağlı)</label>
                    <div className="flex items-center space-x-2">
                      <input 
                        type="file" 
                        accept="image/*"
                        ref={fileInputRef}
                        onChange={handleLogoUpload}
                        className="block w-full text-xs text-slate-500 file:mr-2 file:py-1 file:px-2 file:rounded-md file:border-0 file:text-xs file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100"
                      />
                      {logo && (
                        <button type="button" onClick={clearLogo} className="text-red-500 hover:text-red-700">
                          <X className="w-4 h-4" />
                        </button>
                      )}
                    </div>
                    {logo && (
                      <div className="mt-2 flex justify-center bg-white p-2 border rounded">
                        <img src={logo} alt="Preview" className="h-8 w-auto object-contain" />
                      </div>
                    )}
                  </div>
                </div>

                {/* Messages */}
                {error && (
                  <div className="flex items-center p-3 text-sm text-red-800 bg-red-50 rounded-lg border border-red-100">
                    <AlertCircle className="w-4 h-4 mr-2 flex-shrink-0" />
                    {error}
                  </div>
                )}

                {successMsg && (
                  <div className="flex items-center p-3 text-sm text-green-800 bg-green-50 rounded-lg border border-green-100">
                    <QrCode className="w-4 h-4 mr-2 flex-shrink-0" />
                    {successMsg}
                  </div>
                )}

                {/* Actions */}
                <div className="flex space-x-2 pt-2">
                  <button
                    type="submit"
                    className="flex-1 flex justify-center items-center py-2.5 px-4 border border-transparent rounded-lg shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors"
                  >
                    {editingId ? 'Güncelle' : 'Oluştur'}
                  </button>
                  
                  {editingId && (
                    <button
                      type="button"
                      onClick={handleCancelEdit}
                      className="flex-none flex justify-center items-center py-2.5 px-3 border border-gray-300 rounded-lg shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors"
                      title="Vazgeç"
                    >
                      <X className="w-5 h-5" />
                    </button>
                  )}
                </div>
              </form>

              <div className="mt-6 pt-6 border-t border-gray-100 text-xs text-gray-500 leading-relaxed">
                <p>
                  <strong>Not:</strong> Gloqr tamamen tarayıcınızda çalışır. 
                  Resimler ve veriler sunucuya gitmez, tarayıcıda saklanır.
                </p>
              </div>
            </div>
          </div>

          {/* Right Column: List & Search */}
          <div className="lg:col-span-2 space-y-6">
            
            {/* Search Bar */}
            <div className="bg-white p-4 rounded-xl shadow-sm border border-gray-200">
              <div className="relative">
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <Search className="h-5 w-5 text-gray-400" />
                </div>
                <input
                  type="text"
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="block w-full pl-10 pr-3 py-3 border-gray-200 rounded-lg focus:ring-blue-500 focus:border-blue-500 sm:text-sm bg-slate-50 border"
                  placeholder="Firma adı veya link ara..."
                />
              </div>
            </div>

            {/* List */}
            {filteredRecords.length === 0 ? (
              <div className="text-center py-12 bg-white rounded-xl border border-dashed border-gray-300">
                <div className="mx-auto h-12 w-12 text-gray-300">
                  <QrCode className="h-12 w-12" />
                </div>
                <h3 className="mt-2 text-sm font-medium text-gray-900">Kayıt Bulunamadı</h3>
                <p className="mt-1 text-sm text-gray-500">
                  {searchTerm ? 'Aradığınız kriterlere uygun kayıt yok.' : 'Henüz hiç QR kod oluşturmadınız.'}
                </p>
              </div>
            ) : (
              <div className="grid grid-cols-1 gap-4">
                {filteredRecords.map((record) => (
                  <div 
                    key={record.id} 
                    className={`bg-white rounded-xl p-4 sm:p-6 shadow-sm border transition-all duration-200 flex flex-col sm:flex-row gap-6 ${editingId === record.id ? 'ring-2 ring-blue-500 border-blue-500' : 'border-gray-200 hover:shadow-md'}`}
                  >
                    {/* QR Code Display */}
                    <div className="flex-shrink-0 flex flex-col items-center justify-center bg-gray-50 p-3 rounded-lg border border-gray-100">
                      <div className="bg-white p-2 rounded shadow-sm">
                        <QRCodeCanvas
                          id={`qr-canvas-${record.id}`}
                          value={record.url}
                          size={120}
                          level={"H"}
                          includeMargin={true}
                          fgColor={record.fgColor || '#000000'}
                          bgColor={record.bgColor || '#ffffff'}
                          imageSettings={record.logo ? {
                            src: record.logo,
                            height: 24,
                            width: 24,
                            excavate: true,
                          } : undefined}
                          className="rounded-md"
                        />
                      </div>
                      {/* Hidden SVG for downloading */}
                      <div className="hidden">
                        <QRCodeSVG
                          id={`qr-svg-${record.id}`}
                          value={record.url}
                          size={300} 
                          level={"H"}
                          includeMargin={true}
                          fgColor={record.fgColor || '#000000'}
                          bgColor={record.bgColor || '#ffffff'}
                          imageSettings={record.logo ? {
                            src: record.logo,
                            height: 60,
                            width: 60,
                            excavate: true,
                          } : undefined}
                        />
                      </div>
                      
                      {/* Download Buttons Group */}
                      <div className="mt-3 flex space-x-1 w-full">
                        <button
                          onClick={() => downloadPNG(record.id, record.companyName)}
                          className="flex-1 flex items-center justify-center px-2 py-1.5 text-xs font-medium text-blue-700 bg-blue-50 rounded hover:bg-blue-100 transition-colors"
                          title="PNG İndir"
                        >
                          <ImageIcon className="w-3 h-3" />
                        </button>
                        <button
                          onClick={() => downloadSVG(record.id, record.companyName)}
                          className="flex-1 flex items-center justify-center px-2 py-1.5 text-xs font-medium text-blue-700 bg-blue-50 rounded hover:bg-blue-100 transition-colors"
                          title="SVG İndir"
                        >
                          <Code className="w-3 h-3" />
                        </button>
                      </div>
                      <div className="text-[10px] text-gray-400 mt-1 uppercase tracking-wider">İndir</div>
                    </div>

                    {/* Content */}
                    <div className="flex-1 flex flex-col justify-between min-w-0">
                      <div>
                        <div className="flex items-center justify-between mb-2">
                          <h3 className="text-lg font-bold text-gray-900 truncate" title={record.companyName}>
                            {record.companyName}
                          </h3>
                          <span className="flex-shrink-0 inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
                            <Calendar className="w-3 h-3 mr-1" />
                            {new Date(record.createdAt).toLocaleDateString('tr-TR')}
                          </span>
                        </div>
                        
                        <div className="flex items-center text-sm text-gray-500 mb-4 break-all bg-gray-50 p-2 rounded border border-gray-100">
                          <LinkIcon className="w-4 h-4 mr-2 flex-shrink-0" />
                          <a href={record.url} target="_blank" rel="noopener noreferrer" className="hover:text-blue-600 hover:underline">
                            {record.url}
                          </a>
                        </div>

                        {/* Visual Tags */}
                        {(record.fgColor !== '#000000' || record.bgColor !== '#ffffff' || record.logo) && (
                          <div className="flex space-x-2 mb-2">
                             {record.logo && <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-purple-100 text-purple-800">Logo Var</span>}
                             {(record.fgColor !== '#000000' || record.bgColor !== '#ffffff') && <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-pink-100 text-pink-800">Özel Renk</span>}
                          </div>
                        )}
                      </div>

                      <div className="flex items-center justify-end space-x-3 mt-2 sm:mt-0">
                        <button
                          onClick={() => handleEdit(record)}
                          disabled={editingId === record.id}
                          className={`inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md transition-colors ${editingId === record.id ? 'text-gray-400 bg-gray-100 cursor-not-allowed' : 'text-blue-700 bg-blue-50 hover:bg-blue-100 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500'}`}
                        >
                          <Pencil className="w-4 h-4 mr-1.5" />
                          Düzenle
                        </button>
                        
                        <button
                          onClick={() => handleDelete(record.id)}
                          className="inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md text-red-700 bg-red-50 hover:bg-red-100 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 transition-colors"
                        >
                          <Trash2 className="w-4 h-4 mr-1.5" />
                          Sil
                        </button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
            
            {/* Footer Summary */}
            <div className="text-center text-sm text-gray-400 py-4">
              Toplam {filteredRecords.length} kayıt listeleniyor
            </div>

          </div>
        </div>
      </main>
      
      {/* Footer */}
      <footer className="bg-white border-t border-gray-200 py-6 mt-auto">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 flex flex-col items-center justify-center space-y-2">
          <div className="flex items-center text-slate-700 font-semibold">
            <Globe className="w-4 h-4 mr-2" />
            Global Media iştirakidir
          </div>
          <p className="text-xs text-gray-400">© {new Date().getFullYear()} Gloqr. Tüm hakları saklıdır.</p>
        </div>
      </footer>
    </div>
  );
};

// --- INITIALIZATION ---
const rootElement = document.getElementById('root');
if (!rootElement) {
  throw new Error("Could not find root element to mount to");
}

const root = ReactDOM.createRoot(rootElement);
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);