'use client';

import { useState } from 'react';
import { QRCalculatorData, QRGenerationResponse } from '@/src/types';
import { Download, Copy, Check, Loader2, QrCode } from 'lucide-react';

export default function QRTestPage() {
  // Form state
  const [calculationType, setCalculationType] = useState<'fuel' | 'distance' | 'custom'>('distance');
  const [distance, setDistance] = useState('100');
  const [speed, setSpeed] = useState('12');
  const [fuelRate, setFuelRate] = useState('100');
  const [fuelAmount, setFuelAmount] = useState('500');
  const [fuelUnit, setFuelUnit] = useState<'liters' | 'gallons'>('liters');
  const [customAmount, setCustomAmount] = useState('50');
  const [vesselName, setVesselName] = useState('');
  const [imo, setImo] = useState('');

  // Response state
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [response, setResponse] = useState<QRGenerationResponse | null>(null);
  const [copiedUrl, setCopiedUrl] = useState(false);
  const [copiedSvg, setCopiedSvg] = useState(false);

  // Example presets
  const presets = {
    distance: {
      calculationType: 'distance' as const,
      distance: 100,
      speed: 12,
      fuelRate: 100,
    },
    fuel: {
      calculationType: 'fuel' as const,
      fuelAmount: 500,
      fuelUnit: 'liters' as const,
    },
    custom: {
      calculationType: 'custom' as const,
      customAmount: 100,
    },
  };

  const loadPreset = (preset: keyof typeof presets) => {
    const data = presets[preset];
    setCalculationType(data.calculationType);

    if ('distance' in data) {
      setDistance(data.distance.toString());
      setSpeed(data.speed!.toString());
      setFuelRate(data.fuelRate!.toString());
    }
    if ('fuelAmount' in data) {
      setFuelAmount(data.fuelAmount.toString());
      setFuelUnit(data.fuelUnit!);
    }
    if ('customAmount' in data) {
      setCustomAmount(data.customAmount.toString());
    }
  };

  const handleGenerate = async () => {
    setIsLoading(true);
    setError(null);
    setResponse(null);
    setCopiedUrl(false);
    setCopiedSvg(false);

    try {
      // Build request data based on calculator type
      const requestData: QRCalculatorData = {
        calculationType,
        timestamp: new Date().toISOString(),
        source: 'qr-test-page',
        vessel: vesselName || imo ? {
          name: vesselName || undefined,
          imo: imo || undefined,
        } : undefined,
      };

      if (calculationType === 'distance') {
        requestData.distance = parseFloat(distance);
        requestData.speed = parseFloat(speed);
        requestData.fuelRate = parseFloat(fuelRate);
      } else if (calculationType === 'fuel') {
        requestData.fuelAmount = parseFloat(fuelAmount);
        requestData.fuelUnit = fuelUnit;
      } else if (calculationType === 'custom') {
        requestData.customAmount = parseFloat(customAmount);
      }

      // Call API
      const res = await fetch('/api/qr-code/generate', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(requestData),
      });

      // Check HTTP status first
      if (!res.ok) {
        let errorMessage = `HTTP ${res.status}: ${res.statusText}`;
        try {
          const errorData = await res.json();
          if (errorData.error) {
            errorMessage = errorData.error;
          }
        } catch {
          // Not JSON, use status text
        }
        throw new Error(errorMessage);
      }

      const result = await res.json();

      if (!result.success) {
        throw new Error(result.error || 'Failed to generate QR code');
      }

      setResponse(result.data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unknown error occurred');
    } finally {
      setIsLoading(false);
    }
  };

  const copyToClipboard = async (text: string, type: 'url' | 'svg') => {
    try {
      await navigator.clipboard.writeText(text);
      if (type === 'url') {
        setCopiedUrl(true);
        setTimeout(() => setCopiedUrl(false), 2000);
      } else {
        setCopiedSvg(true);
        setTimeout(() => setCopiedSvg(false), 2000);
      }
    } catch (err) {
      console.error('Failed to copy:', err);
    }
  };

  const downloadQR = (dataURL: string, format: 'png' | 'svg') => {
    const link = document.createElement('a');
    link.href = format === 'png' ? dataURL : `data:image/svg+xml;base64,${btoa(response!.qrCodeSVG)}`;
    link.download = `qr-code-${calculationType}-${Date.now()}.${format}`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  return (
    <div className="min-h-screen bg-gradient-to-b from-blue-50 to-green-50 py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-6xl mx-auto">
        {/* Header */}
        <div className="text-center mb-12">
          <div className="flex items-center justify-center mb-4">
            <QrCode className="w-12 h-12 text-blue-600 mr-3" />
            <h1 className="text-4xl font-bold text-gray-900">QR Code API Test Page</h1>
          </div>
          <p className="text-lg text-gray-600">
            Test the QR code generation API for the carbon calculator
          </p>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
          {/* Left Column - Input Form */}
          <div className="bg-white rounded-lg shadow-lg p-6">
            <h2 className="text-2xl font-bold text-gray-900 mb-6">Generator Configuration</h2>

            {/* Example Presets */}
            <div className="mb-6">
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Quick Presets
              </label>
              <div className="flex flex-wrap gap-2">
                <button
                  onClick={() => loadPreset('distance')}
                  className="px-4 py-2 bg-blue-100 text-blue-700 rounded-lg hover:bg-blue-200 transition-colors text-sm font-medium"
                >
                  Distance Example
                </button>
                <button
                  onClick={() => loadPreset('fuel')}
                  className="px-4 py-2 bg-green-100 text-green-700 rounded-lg hover:bg-green-200 transition-colors text-sm font-medium"
                >
                  Fuel Example
                </button>
                <button
                  onClick={() => loadPreset('custom')}
                  className="px-4 py-2 bg-purple-100 text-purple-700 rounded-lg hover:bg-purple-200 transition-colors text-sm font-medium"
                >
                  Custom Example
                </button>
              </div>
            </div>

            {/* Calculator Type */}
            <div className="mb-6">
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Calculator Type
              </label>
              <select
                value={calculationType}
                onChange={(e) => setCalculationType(e.target.value as any)}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              >
                <option value="distance">Distance-based</option>
                <option value="fuel">Fuel-based</option>
                <option value="custom">Custom Amount</option>
              </select>
            </div>

            {/* Conditional Fields */}
            {calculationType === 'distance' && (
              <div className="space-y-4 mb-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Distance (nautical miles)
                  </label>
                  <input
                    type="number"
                    value={distance}
                    onChange={(e) => setDistance(e.target.value)}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Speed (knots)
                  </label>
                  <input
                    type="number"
                    value={speed}
                    onChange={(e) => setSpeed(e.target.value)}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Fuel Rate (liters/hour)
                  </label>
                  <input
                    type="number"
                    value={fuelRate}
                    onChange={(e) => setFuelRate(e.target.value)}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  />
                </div>
              </div>
            )}

            {calculationType === 'fuel' && (
              <div className="space-y-4 mb-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Fuel Amount
                  </label>
                  <input
                    type="number"
                    value={fuelAmount}
                    onChange={(e) => setFuelAmount(e.target.value)}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Fuel Unit
                  </label>
                  <select
                    value={fuelUnit}
                    onChange={(e) => setFuelUnit(e.target.value as any)}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  >
                    <option value="liters">Liters</option>
                    <option value="gallons">Gallons</option>
                  </select>
                </div>
              </div>
            )}

            {calculationType === 'custom' && (
              <div className="mb-6">
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Custom Amount (USD)
                </label>
                <input
                  type="number"
                  value={customAmount}
                  onChange={(e) => setCustomAmount(e.target.value)}
                  placeholder="e.g., 100"
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                />
                <p className="mt-1 text-xs text-gray-500">
                  Monetary amount to spend on carbon offsets (calculator will convert to CO₂)
                </p>
              </div>
            )}

            {/* Vessel Information - Optional Metadata */}
            <details className="mb-6">
              <summary className="cursor-pointer text-sm font-medium text-gray-500 hover:text-gray-700 mb-3 flex items-center">
                <span>Optional: Vessel Information (metadata only - not used in calculations)</span>
              </summary>
              <div className="mt-3 p-4 bg-gray-50 rounded-lg border border-gray-200">
                <p className="text-xs text-gray-600 mb-3 italic">
                  Note: Vessel name and IMO are stored as metadata only. They are not used in carbon calculations.
                </p>
                <div className="space-y-3">
                  <div>
                    <label className="block text-xs font-medium text-gray-600 mb-1">
                      Vessel Name
                    </label>
                    <input
                      type="text"
                      value={vesselName}
                      onChange={(e) => setVesselName(e.target.value)}
                      placeholder="e.g., My Yacht (optional)"
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm"
                    />
                  </div>
                  <div>
                    <label className="block text-xs font-medium text-gray-600 mb-1">
                      IMO Number
                    </label>
                    <input
                      type="text"
                      value={imo}
                      onChange={(e) => setImo(e.target.value)}
                      placeholder="e.g., 1234567 (optional)"
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm"
                    />
                  </div>
                </div>
              </div>
            </details>

            {/* Generate Button */}
            <button
              onClick={handleGenerate}
              disabled={isLoading}
              className="w-full py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors font-semibold disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center"
            >
              {isLoading ? (
                <>
                  <Loader2 className="w-5 h-5 mr-2 animate-spin" />
                  Generating...
                </>
              ) : (
                'Generate QR Code'
              )}
            </button>

            {/* Error Display */}
            {error && (
              <div className="mt-4 p-4 bg-red-50 border border-red-200 rounded-lg">
                <p className="text-red-800 text-sm font-medium">Error: {error}</p>
              </div>
            )}
          </div>

          {/* Right Column - Results */}
          <div className="bg-white rounded-lg shadow-lg p-6">
            <h2 className="text-2xl font-bold text-gray-900 mb-6">Generated QR Code</h2>

            {!response && !isLoading && (
              <div className="flex flex-col items-center justify-center h-96 text-gray-400">
                <QrCode className="w-24 h-24 mb-4" />
                <p className="text-lg">No QR code generated yet</p>
                <p className="text-sm mt-2">Fill the form and click Generate</p>
              </div>
            )}

            {isLoading && (
              <div className="flex flex-col items-center justify-center h-96">
                <Loader2 className="w-16 h-16 text-blue-600 animate-spin mb-4" />
                <p className="text-gray-600">Generating QR code...</p>
              </div>
            )}

            {response && (
              <div className="space-y-6">
                {/* QR Code Display */}
                <div className="flex justify-center p-8 bg-gray-50 rounded-lg">
                  <img
                    src={response.qrCodeDataURL}
                    alt="Generated QR Code"
                    className="max-w-full h-auto"
                  />
                </div>

                {/* Download Buttons */}
                <div className="flex gap-3">
                  <button
                    onClick={() => downloadQR(response.qrCodeDataURL, 'png')}
                    className="flex-1 py-2 px-4 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors font-medium flex items-center justify-center"
                  >
                    <Download className="w-4 h-4 mr-2" />
                    Download PNG
                  </button>
                  <button
                    onClick={() => downloadQR(response.qrCodeDataURL, 'svg')}
                    className="flex-1 py-2 px-4 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors font-medium flex items-center justify-center"
                  >
                    <Download className="w-4 h-4 mr-2" />
                    Download SVG
                  </button>
                </div>

                {/* URL Display */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Generated URL
                  </label>
                  <div className="flex gap-2">
                    <input
                      type="text"
                      value={response.url}
                      readOnly
                      className="flex-1 px-4 py-2 border border-gray-300 rounded-lg bg-gray-50 text-sm font-mono"
                    />
                    <button
                      onClick={() => copyToClipboard(response.url, 'url')}
                      className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center"
                    >
                      {copiedUrl ? (
                        <>
                          <Check className="w-4 h-4 mr-1" />
                          Copied!
                        </>
                      ) : (
                        <>
                          <Copy className="w-4 h-4 mr-1" />
                          Copy
                        </>
                      )}
                    </button>
                  </div>
                </div>

                {/* SVG Code */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    SVG Code
                  </label>
                  <div className="relative">
                    <textarea
                      value={response.qrCodeSVG}
                      readOnly
                      rows={6}
                      className="w-full px-4 py-2 border border-gray-300 rounded-lg bg-gray-50 text-xs font-mono resize-none"
                    />
                    <button
                      onClick={() => copyToClipboard(response.qrCodeSVG, 'svg')}
                      className="absolute top-2 right-2 px-3 py-1 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors text-xs flex items-center"
                    >
                      {copiedSvg ? (
                        <>
                          <Check className="w-3 h-3 mr-1" />
                          Copied!
                        </>
                      ) : (
                        <>
                          <Copy className="w-3 h-3 mr-1" />
                          Copy
                        </>
                      )}
                    </button>
                  </div>
                </div>

                {/* Metadata */}
                <div className="p-4 bg-gray-50 rounded-lg text-sm">
                  <h3 className="font-semibold text-gray-900 mb-2">Metadata</h3>
                  <div className="space-y-1 text-gray-600">
                    <p><span className="font-medium">Expires:</span> {new Date(response.expiresAt).toLocaleString()}</p>
                    <p><span className="font-medium">Type:</span> {calculationType}</p>
                  </div>
                </div>

                {/* Test Link */}
                <a
                  href={response.url}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="block w-full py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors font-semibold text-center"
                >
                  Test QR Code Link →
                </a>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
