'use client';

import React, { useState, useEffect } from 'react';
import { useRouter, useParams } from 'next/navigation';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/Card';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { showToast } from '@/components/ui/Toast';
import { useCsrf } from '@/hooks/useCsrf';
import { Upload, FileText, HelpCircle } from 'lucide-react';

// Tooltip component for form field help
const Tooltip = ({ text }: { text: string }) => (
  <div className="group relative inline-block ml-1">
    <HelpCircle className="w-4 h-4 text-gray-400 cursor-help" />
    <div className="absolute bottom-full left-1/2 -translate-x-1/2 mb-2 px-3 py-2 bg-gray-900 text-white text-xs rounded-lg opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 z-50 w-48 text-center">
      {text}
      <div className="absolute top-full left-1/2 -translate-x-1/2 border-4 border-transparent border-t-gray-900"></div>
    </div>
  </div>
);

export default function EditQRPage() {
  const router = useRouter();
  const params = useParams();
  const qrId = params.id as string;
  const { fetchWithCsrf, loading: csrfLoading } = useCsrf();

  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [qrCode, setQrCode] = useState<any>(null);
  const [title, setTitle] = useState('');
  const [content, setContent] = useState<any>({});

  useEffect(() => {
    const fetchQRCode = async () => {
      try {
        const response = await fetch(`/api/qrs/${qrId}`);
        if (response.ok) {
          const data = await response.json();
          setQrCode(data);
          setTitle(data.title);
          setContent(data.content || {});
        } else {
          showToast('Failed to load QR code', 'error');
          router.push('/dashboard');
        }
      } catch (error) {
        console.error('Error fetching QR code:', error);
        showToast('Failed to load QR code', 'error');
        router.push('/dashboard');
      } finally {
        setLoading(false);
      }
    };

    fetchQRCode();
  }, [qrId, router]);

  const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    // 10MB limit
    if (file.size > 10 * 1024 * 1024) {
      showToast('File size too large (max 10MB)', 'error');
      return;
    }

    setUploading(true);
    const formData = new FormData();
    formData.append('file', file);

    try {
      const response = await fetch('/api/upload', {
        method: 'POST',
        body: formData,
      });
      const data = await response.json();

      if (response.ok) {
        setContent({ ...content, fileUrl: data.url, fileName: data.filename });
        showToast('File uploaded successfully!', 'success');
      } else {
        showToast(data.error || 'Upload failed', 'error');
      }
    } catch (error) {
      console.error('Upload error:', error);
      showToast('Error uploading file', 'error');
    } finally {
      setUploading(false);
    }
  };

  const handleSave = async () => {
    setSaving(true);

    try {
      const response = await fetchWithCsrf(`/api/qrs/${qrId}`, {
        method: 'PATCH',
        body: JSON.stringify({
          title,
          content,
        }),
      });

      if (response.ok) {
        showToast('QR code updated successfully!', 'success');
        router.push('/dashboard');
      } else {
        const error = await response.json();
        showToast(error.error || 'Failed to update QR code', 'error');
      }
    } catch (error) {
      console.error('Error updating QR code:', error);
      showToast('Failed to update QR code', 'error');
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600 mx-auto mb-4"></div>
          <p className="text-gray-600">Loading QR code...</p>
        </div>
      </div>
    );
  }

  if (!qrCode) {
    return null;
  }

  // Static QR codes cannot be edited
  if (qrCode.type === 'STATIC') {
    return (
      <div className="max-w-2xl mx-auto mt-12">
        <Card>
          <CardContent className="p-12 text-center">
            <div className="w-20 h-20 bg-warning-100 rounded-full flex items-center justify-center mx-auto mb-6">
              <svg className="w-10 h-10 text-warning-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
              </svg>
            </div>
            <h2 className="text-2xl font-bold text-gray-900 mb-2">Static QR Code</h2>
            <p className="text-gray-600 mb-8">
              Static QR codes cannot be edited because their content is embedded directly in the QR code image.
            </p>
            <Button onClick={() => router.push('/dashboard')}>
              Back to Dashboard
            </Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="max-w-3xl mx-auto">
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-gray-900">Edit QR Code</h1>
        <p className="text-gray-600 mt-2">Update your dynamic QR code content</p>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>QR Code Details</CardTitle>
        </CardHeader>
        <CardContent className="space-y-6">
          <Input
            label="Title"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            placeholder="Enter QR code title"
            required
          />

          {qrCode.contentType === 'URL' && (
            <Input
              label="URL"
              type="url"
              value={content.url || ''}
              onChange={(e) => setContent({ ...content, url: e.target.value })}
              placeholder="https://example.com"
              required
            />
          )}

          {qrCode.contentType === 'PHONE' && (
            <Input
              label="Phone Number"
              type="tel"
              value={content.phone || ''}
              onChange={(e) => setContent({ ...content, phone: e.target.value })}
              placeholder="+1234567890"
              required
            />
          )}

          {qrCode.contentType === 'VCARD' && (
            <>
              <Input
                label="First Name"
                value={content.firstName || ''}
                onChange={(e) => setContent({ ...content, firstName: e.target.value })}
                placeholder="John"
                required
              />
              <Input
                label="Last Name"
                value={content.lastName || ''}
                onChange={(e) => setContent({ ...content, lastName: e.target.value })}
                placeholder="Doe"
                required
              />
              <Input
                label="Email"
                type="email"
                value={content.email || ''}
                onChange={(e) => setContent({ ...content, email: e.target.value })}
                placeholder="john@example.com"
              />
              <Input
                label="Phone"
                value={content.phone || ''}
                onChange={(e) => setContent({ ...content, phone: e.target.value })}
                placeholder="+1234567890"
              />
              <Input
                label="Organization"
                value={content.organization || ''}
                onChange={(e) => setContent({ ...content, organization: e.target.value })}
                placeholder="Company Name"
              />
              <Input
                label="Job Title"
                value={content.title || ''}
                onChange={(e) => setContent({ ...content, title: e.target.value })}
                placeholder="CEO"
              />
            </>
          )}

          {qrCode.contentType === 'GEO' && (
            <>
              <Input
                label="Latitude"
                type="number"
                step="any"
                value={content.latitude || ''}
                onChange={(e) => setContent({ ...content, latitude: parseFloat(e.target.value) || 0 })}
                placeholder="37.7749"
                required
              />
              <Input
                label="Longitude"
                type="number"
                step="any"
                value={content.longitude || ''}
                onChange={(e) => setContent({ ...content, longitude: parseFloat(e.target.value) || 0 })}
                placeholder="-122.4194"
                required
              />
              <Input
                label="Location Label (Optional)"
                value={content.label || ''}
                onChange={(e) => setContent({ ...content, label: e.target.value })}
                placeholder="Golden Gate Bridge"
              />
            </>
          )}

          {qrCode.contentType === 'TEXT' && (
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Text Content
              </label>
              <textarea
                value={content.text || ''}
                onChange={(e) => setContent({ ...content, text: e.target.value })}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                rows={4}
                placeholder="Enter your text content"
                required
              />
            </div>
          )}

          {qrCode.contentType === 'PDF' && (
            <>
              <div>
                <div className="flex items-center mb-1">
                  <label className="block text-sm font-medium text-gray-700">Upload Menu / PDF</label>
                  <Tooltip text="Upload your menu PDF (Max 10MB). Hosted securely." />
                </div>

                <div className="mt-2 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-lg hover:bg-gray-50 transition-colors relative">
                  <div className="space-y-1 text-center">
                    {uploading ? (
                      <div className="flex flex-col items-center">
                        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-500 mb-2"></div>
                        <p className="text-sm text-gray-500">Uploading...</p>
                      </div>
                    ) : content.fileUrl ? (
                      <div className="flex flex-col items-center">
                        <div className="mx-auto h-12 w-12 text-primary-500 bg-primary-50 rounded-full flex items-center justify-center mb-2">
                          <FileText className="h-6 w-6" />
                        </div>
                        <p className="text-sm text-green-600 font-medium mb-1">Upload Complete!</p>
                        <a href={content.fileUrl} target="_blank" rel="noopener noreferrer" className="text-xs text-primary-500 hover:underline break-all max-w-xs mb-3 block">
                          {content.fileName || 'View File'}
                        </a>
                        <label htmlFor="file-upload" className="cursor-pointer bg-white py-2 px-3 border border-gray-300 rounded-md shadow-sm text-sm leading-4 font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500">
                          <span>Replace File</span>
                          <input id="file-upload" name="file-upload" type="file" className="sr-only" accept=".pdf,image/*" onChange={handleFileUpload} />
                        </label>
                      </div>
                    ) : (
                      <>
                        <Upload className="mx-auto h-12 w-12 text-gray-400" />
                        <div className="flex text-sm text-gray-600 justify-center">
                          <label htmlFor="file-upload" className="relative cursor-pointer bg-white rounded-md font-medium text-primary-600 hover:text-primary-500 focus-within:outline-none focus-within:ring-2 focus-within:ring-offset-2 focus-within:ring-primary-500">
                            <span>Upload a file</span>
                            <input id="file-upload" name="file-upload" type="file" className="sr-only" accept=".pdf,image/*" onChange={handleFileUpload} />
                          </label>
                          <p className="pl-1">or drag and drop</p>
                        </div>
                        <p className="text-xs text-gray-500">PDF, PNG, JPG up to 10MB</p>
                      </>
                    )}
                  </div>
                </div>
              </div>

              {content.fileUrl && (
                <Input
                  label="File Name / Menu Title"
                  value={content.fileName || ''}
                  onChange={(e) => setContent({ ...content, fileName: e.target.value })}
                  placeholder="Product Catalog 2026"
                />
              )}
            </>
          )}

          {qrCode.contentType === 'APP' && (
            <>
              <Input
                label="iOS App Store URL"
                value={content.iosUrl || ''}
                onChange={(e) => setContent({ ...content, iosUrl: e.target.value })}
                placeholder="https://apps.apple.com/app/..."
              />
              <Input
                label="Android Play Store URL"
                value={content.androidUrl || ''}
                onChange={(e) => setContent({ ...content, androidUrl: e.target.value })}
                placeholder="https://play.google.com/store/apps/..."
              />
              <Input
                label="Fallback URL (Desktop)"
                value={content.fallbackUrl || ''}
                onChange={(e) => setContent({ ...content, fallbackUrl: e.target.value })}
                placeholder="https://yourapp.com"
              />
            </>
          )}

          {qrCode.contentType === 'COUPON' && (
            <>
              <Input
                label="Coupon Code"
                value={content.code || ''}
                onChange={(e) => setContent({ ...content, code: e.target.value })}
                placeholder="SUMMER20"
                required
              />
              <Input
                label="Discount"
                value={content.discount || ''}
                onChange={(e) => setContent({ ...content, discount: e.target.value })}
                placeholder="20% OFF"
                required
              />
              <Input
                label="Title"
                value={content.title || ''}
                onChange={(e) => setContent({ ...content, title: e.target.value })}
                placeholder="Summer Sale 2026"
              />
              <Input
                label="Description (optional)"
                value={content.description || ''}
                onChange={(e) => setContent({ ...content, description: e.target.value })}
                placeholder="Valid on all products"
              />
              <Input
                label="Expiry Date (optional)"
                type="date"
                value={content.expiryDate || ''}
                onChange={(e) => setContent({ ...content, expiryDate: e.target.value })}
              />
              <Input
                label="Redeem URL (optional)"
                value={content.redeemUrl || ''}
                onChange={(e) => setContent({ ...content, redeemUrl: e.target.value })}
                placeholder="https://shop.example.com"
              />
            </>
          )}

          {qrCode.contentType === 'FEEDBACK' && (
            <>
              <Input
                label="Business Name"
                value={content.businessName || ''}
                onChange={(e) => setContent({ ...content, businessName: e.target.value })}
                placeholder="Your Restaurant Name"
                required
              />
              <Input
                label="Google Review URL (optional)"
                value={content.googleReviewUrl || ''}
                onChange={(e) => setContent({ ...content, googleReviewUrl: e.target.value })}
                placeholder="https://search.google.com/local/writereview?placeid=..."
              />
              <Input
                label="Thank You Message"
                value={content.thankYouMessage || ''}
                onChange={(e) => setContent({ ...content, thankYouMessage: e.target.value })}
                placeholder="Thanks for your feedback!"
              />
            </>
          )}

          <div className="flex justify-end space-x-4 pt-4">
            <Button
              variant="outline"
              onClick={() => router.push('/dashboard')}
            >
              Cancel
            </Button>
            <Button
              onClick={handleSave}
              loading={saving}
              disabled={csrfLoading || saving}
            >
              {csrfLoading ? 'Loading...' : 'Save Changes'}
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
