'use client';
import { useEffect, useState, useRef } from 'react';
import { useHRStamp } from '../lib/hrStampStore';
import Link from 'next/link';

export default function DashboardStampWidget() {
  const { stamp, signature, setStamp, setSignature } = useHRStamp();
  const [toast, setToast] = useState('');
  const stampRef = useRef<HTMLInputElement>(null);
  const sigRef = useRef<HTMLInputElement>(null);

  const showToast = (msg: string) => { setToast(msg); setTimeout(() => setToast(''), 3000); };

  const handleFile = (file: File, type: 'stamp' | 'sig') => {
    if (!file || file.size > 2 * 1024 * 1024) { showToast('File too large (max 2MB)'); return; }
    const reader = new FileReader();
    reader.onload = e => {
      const b64 = e.target?.result as string;
      if (type === 'stamp') { setStamp(b64); showToast('Office stamp saved!'); }
      else { setSignature(b64); showToast('Signature saved!'); }
    };
    reader.readAsDataURL(file);
  };

  return (
    <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-5 hover:-translate-y-1 transition-transform duration-200">
      {toast && (
        <div className="fixed top-5 right-5 z-[100] bg-green-600 text-white px-4 py-2.5 rounded-xl shadow-lg text-xs font-medium">
          {toast}
        </div>
      )}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-2">
          <div className="w-8 h-8 rounded-lg flex items-center justify-center bg-purple-600">
            <i className="ri-mark-pen-line text-white text-sm"></i>
          </div>
          <h3 className="font-semibold text-gray-800 text-sm">HR Stamp &amp; Signature</h3>
        </div>
        <Link href="/leave" className="text-xs font-medium hover:underline cursor-pointer" style={{ color: '#b22698' }}>Manage</Link>
      </div>

      <p className="text-xs text-gray-500 mb-4">Upload your office stamp and signature. They will be auto-embedded in all approved leave computation forms.</p>

      <div className="grid grid-cols-2 gap-3">
        <div className="border border-dashed border-gray-200 rounded-xl p-3 text-center">
          {stamp ? (
            <img src={stamp} alt="Stamp" className="h-12 w-auto object-contain mx-auto mb-2" />
          ) : (
            <div className="w-10 h-10 flex items-center justify-center mx-auto mb-2 rounded-lg bg-gray-100">
              <i className="ri-mark-pen-line text-gray-400 text-lg"></i>
            </div>
          )}
          <p className="text-xs font-medium text-gray-600 mb-1.5">Office Stamp</p>
          <div className="flex gap-1 justify-center">
            <button onClick={() => stampRef.current?.click()}
              className="text-xs px-2 py-1 rounded-lg text-white cursor-pointer whitespace-nowrap"
              style={{ background: '#b828a0' }}>
              {stamp ? 'Replace' : 'Upload'}
            </button>
            {stamp && (
              <button onClick={() => setStamp(null)}
                className="text-xs px-2 py-1 rounded-lg text-red-500 bg-red-50 border border-red-200 cursor-pointer whitespace-nowrap">
                Remove
              </button>
            )}
          </div>
          <input ref={stampRef} type="file" accept="image/*" className="hidden"
            onChange={e => { const f = e.target.files?.[0]; if (f) handleFile(f, 'stamp'); e.target.value = ''; }} />
          {stamp && <p className="text-xs text-green-600 mt-1"><i className="ri-checkbox-circle-fill mr-0.5"></i>Active</p>}
        </div>

        <div className="border border-dashed border-gray-200 rounded-xl p-3 text-center">
          {signature ? (
            <img src={signature} alt="Signature" className="h-12 w-auto object-contain mx-auto mb-2" />
          ) : (
            <div className="w-10 h-10 flex items-center justify-center mx-auto mb-2 rounded-lg bg-gray-100">
              <i className="ri-pen-nib-line text-gray-400 text-lg"></i>
            </div>
          )}
          <p className="text-xs font-medium text-gray-600 mb-1.5">HR Signature</p>
          <div className="flex gap-1 justify-center">
            <button onClick={() => sigRef.current?.click()}
              className="text-xs px-2 py-1 rounded-lg text-white cursor-pointer whitespace-nowrap"
              style={{ background: '#2563eb' }}>
              {signature ? 'Replace' : 'Upload'}
            </button>
            {signature && (
              <button onClick={() => setSignature(null)}
                className="text-xs px-2 py-1 rounded-lg text-red-500 bg-red-50 border border-red-200 cursor-pointer whitespace-nowrap">
                Remove
              </button>
            )}
          </div>
          <input ref={sigRef} type="file" accept="image/*" className="hidden"
            onChange={e => { const f = e.target.files?.[0]; if (f) handleFile(f, 'sig'); e.target.value = ''; }} />
          {signature && <p className="text-xs text-green-600 mt-1"><i className="ri-checkbox-circle-fill mr-0.5"></i>Active</p>}
        </div>
      </div>

      <div className="mt-3 bg-amber-50 border border-amber-100 rounded-lg px-3 py-2">
        <p className="text-xs text-amber-700">
          <i className="ri-information-line mr-1"></i>
          {(stamp || signature) ? 'Stamp/signature is active and will appear on computation forms.' : 'No stamp or signature uploaded yet.'}
        </p>
      </div>
    </div>
  );
}