'use client';
import { useEffect, useRef, useState } from 'react';
import SignaturePad from 'signature_pad';

interface AgentInitialsPanelProps {
  initialData: string | null;
}

export function AgentInitialsPanel({ initialData }: AgentInitialsPanelProps) {
  const [savedData, setSavedData] = useState<string | null>(initialData);
  const [isDrawing, setIsDrawing] = useState(!initialData);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const sigPadRef = useRef<SignaturePad | null>(null);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!isDrawing || !canvasRef.current) return;
    const canvas = canvasRef.current;
    const ratio = Math.max(window.devicePixelRatio || 1, 1);
    canvas.width = canvas.offsetWidth * ratio;
    canvas.height = canvas.offsetHeight * ratio;
    canvas.getContext('2d')?.scale(ratio, ratio);
    sigPadRef.current = new SignaturePad(canvas, {
      backgroundColor: 'rgba(0,0,0,0)',
      penColor: '#1B2B4B',
    });
    return () => sigPadRef.current?.off();
  }, [isDrawing]);

  async function handleSave() {
    if (!sigPadRef.current || sigPadRef.current.isEmpty()) {
      setError('Please draw your initials first');
      return;
    }
    const dataURL = sigPadRef.current.toDataURL('image/png');
    setSaving(true);
    setError(null);
    try {
      const res = await fetch('/api/agent/initials', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ dataURL }),
      });
      if (res.ok) {
        setSavedData(dataURL);
        setIsDrawing(false);
      } else {
        const data = await res.json().catch(() => ({ error: 'Save failed' }));
        setError(data.error ?? 'Save failed');
      }
    } catch {
      setError('Network error — please try again');
    } finally {
      setSaving(false);
    }
  }

  if (!isDrawing && savedData) {
    return (
      <div className="space-y-4">
        <p className="text-sm text-gray-600">Your saved initials:</p>
        {/* eslint-disable-next-line @next/next/no-img-element */}
        <img
          src={savedData}
          alt="Saved agent initials"
          className="max-h-16 border border-gray-200 rounded bg-white p-2"
        />
        <button
          onClick={() => { setIsDrawing(true); setError(null); }}
          className="px-4 py-2 text-sm bg-white border border-gray-300 rounded hover:bg-gray-50"
        >
          Update Initials
        </button>
      </div>
    );
  }

  return (
    <div className="space-y-3">
      <canvas
        ref={canvasRef}
        className="w-full border border-gray-300 rounded bg-white"
        style={{ height: '80px', touchAction: 'none', display: 'block' }}
      />
      <div className="flex gap-2">
        <button
          onClick={() => sigPadRef.current?.clear()}
          className="px-3 py-2 text-sm bg-white border border-gray-300 rounded hover:bg-gray-50"
        >
          Clear
        </button>
        <button
          onClick={handleSave}
          disabled={saving}
          className="px-4 py-2 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 disabled:opacity-50"
        >
          {saving ? 'Saving...' : (savedData ? 'Save Updated Initials' : 'Save Initials')}
        </button>
        {savedData && (
          <button
            onClick={() => { setIsDrawing(false); setError(null); }}
            className="px-3 py-2 text-sm bg-white border border-gray-300 rounded hover:bg-gray-50"
          >
            Cancel
          </button>
        )}
      </div>
      {error && <p className="text-sm text-red-600">{error}</p>}
    </div>
  );
}
