'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';

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 [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 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' && (
            <>
              <Input
                label="PDF/File URL"
                value={content.fileUrl || ''}
                onChange={(e) => setContent({ ...content, fileUrl: e.target.value })}
                placeholder="https://drive.google.com/file/d/.../view"
                required
              />
              <Input
                label="File Name (optional)"
                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>
  );
}
