import { useRef, useState } from 'react';
import { api } from '../../api';
import { useQueryClient } from '@tanstack/react-query';

interface Props {
  onUploaded?: (id: number) => void;
}

export default function PHD2UploadZone({ onUploaded }: Props) {
  const inputRef = useRef<HTMLInputElement>(null);
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [duplicate, setDuplicate] = useState<{ id: number; message: string } | null>(null);
  const [result, setResult] = useState<{ 
    rms_total: number; 
    rms_ra: number; 
    rms_dec: number;
    duration_min?: number;
    camera_name?: string;
    exposure_ms?: number;
    mount_name?: string;
    session_date?: string;
  } | null>(null);
  const qc = useQueryClient();

  const handleFile = async (file: File) => {
    setUploading(true);
    setError(null);
    setDuplicate(null);
    setResult(null);
    const fd = new FormData();
    fd.append('file', file);

    try {
      const res = await api.phd2.upload(fd);
      
      if (res.duplicate) {
        setDuplicate({ 
          id: res.duplicate_id || 0, 
          message: res.message || `Duplicate session detected (ID: ${res.duplicate_id})` 
        });
        setResult(null);
      } else {
        const analysis = res.analysis as any;
        setResult({ 
          rms_total: analysis.rms_total_arcsec,
          rms_ra: analysis.rms_ra_arcsec,
          rms_dec: analysis.rms_dec_arcsec,
          duration_min: analysis.duration_min,
          camera_name: analysis.camera_name,
          exposure_ms: analysis.exposure_ms,
          mount_name: analysis.mount_name,
        });
        qc.invalidateQueries({ queryKey: ['phd2'] });
        onUploaded?.(res.id);
      }
    } catch (e) {
      setError(`Parse failed: ${e instanceof Error ? e.message : 'Unknown error'}`);
    }
    setUploading(false);
  };

  return (
    <div>
      <div
        onClick={() => inputRef.current?.click()}
        style={{
          border: '1px dashed var(--border)',
          borderRadius: 3,
          padding: '10px 14px',
          cursor: 'pointer',
          color: 'var(--text-lo)',
          fontFamily: 'var(--font-mono)',
          fontSize: 11,
          background: 'var(--bg-deep)',
        }}
      >
        {uploading ? 'Parsing PHD2 log...' : '↑ Upload PHD2 log (.log)'}
      </div>
      <input
        ref={inputRef}
        type="file"
        accept=".log,.csv"
        style={{ display: 'none' }}
        onChange={e => e.target.files?.[0] && handleFile(e.target.files[0])}
      />
      {error && <div style={{ color: 'var(--danger)', fontSize: 11, marginTop: 4 }}>{error}</div>}
      {duplicate && (
        <div style={{ color: 'var(--warn)', fontSize: 11, marginTop: 4, fontFamily: 'var(--font-mono)' }}>
          ⚠ {duplicate.message}
        </div>
      )}
      {result && (
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--good)', marginTop: 4, lineHeight: '1.5' }}>
          <div>✓ RMS Total: {result.rms_total.toFixed(2)}″ (RA: {result.rms_ra.toFixed(2)}″ Dec: {result.rms_dec.toFixed(2)}″)</div>
          {result.session_date && (
            <div style={{ color: 'var(--text-mid)', marginTop: 4 }}>Date: {result.session_date}</div>
          )}
          {result.duration_min !== undefined && (
            <div style={{ color: 'var(--text-mid)', marginTop: result.session_date ? 2 : 6 }}>Duration: {result.duration_min}m</div>
          )}
          {(result.camera_name || result.mount_name) && (
            <div style={{ color: 'var(--text-lo)', marginTop: 4 }}>
              {result.camera_name && <div>Camera: {result.camera_name}</div>}
              {result.mount_name && <div>Mount: {result.mount_name}</div>}
              {result.exposure_ms && <div>Exposure: {result.exposure_ms}ms</div>}
            </div>
          )}
        </div>
      )}
    </div>
  );
}
