'use client';

import { useState, useRef } from 'react';
import { importProducts } from '@/services/products';

export interface ImportDialogProps {
  open: boolean;
  onClose: () => void;
  householdId: string;
  onSuccess: () => void;
}

interface ImportResult {
  imported: number;
  skippedDuplicates: number;
  errors: { row: number; message: string }[];
}

export function ImportDialog({ open, onClose, householdId, onSuccess }: ImportDialogProps) {
  const [file, setFile] = useState<File | null>(null);
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState('');
  const [result, setResult] = useState<ImportResult | null>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  if (!open) return null;

  function handleFileChange(e: React.ChangeEvent<HTMLInputElement>) {
    const selected = e.target.files?.[0] ?? null;
    setFile(selected);
    setError('');
    setResult(null);
  }

  async function handleUpload() {
    if (!file) {
      setError('Please select a file');
      return;
    }
    setUploading(true);
    setError('');
    try {
      const res = await importProducts(householdId, file);
      setResult(res);
      if (res.imported > 0) {
        onSuccess();
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Import failed');
    } finally {
      setUploading(false);
    }
  }

  function handleClose() {
    setFile(null);
    setError('');
    setResult(null);
    onClose();
  }

  const inputStyle: React.CSSProperties = {
    width: '100%',
    padding: '8px 12px',
    borderRadius: 'var(--r-md)',
    border: '1px solid var(--border)',
    background: 'var(--bg-elev)',
    color: 'var(--ink)',
    fontSize: 14,
  };

  return (
    <div
      onClick={handleClose}
      style={{
        position: 'fixed',
        inset: 0,
        background: 'rgba(0,0,0,0.5)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        zIndex: 1000,
        padding: 16,
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          background: 'var(--bg-base, #fff)',
          borderRadius: 'var(--r-lg, 12px)',
          border: '1px solid var(--border)',
          width: '100%',
          maxWidth: 480,
          padding: 24,
        }}
      >
        <h2 style={{ margin: '0 0 20px', fontSize: 18, fontWeight: 600, color: 'var(--ink)' }}>
          Import Products
        </h2>

        {error && <p style={{ color: 'var(--danger)', fontSize: 13, marginBottom: 12 }}>{error}</p>}

        {result ? (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <div
              style={{
                padding: 16,
                borderRadius: 'var(--r-md)',
                background: 'var(--bg-elev)',
                border: '1px solid var(--border)',
              }}
            >
              <p style={{ fontSize: 14, margin: '0 0 8px', color: 'var(--ink)' }}>
                Import complete
              </p>
              <p style={{ fontSize: 13, margin: 0, color: 'var(--ink-muted)' }}>
                Imported: <strong>{result.imported}</strong>
              </p>
              <p style={{ fontSize: 13, margin: 0, color: 'var(--ink-muted)' }}>
                Skipped (duplicates): <strong>{result.skippedDuplicates}</strong>
              </p>
              {result.errors.length > 0 && (
                <div style={{ marginTop: 8 }}>
                  <p style={{ fontSize: 12, color: 'var(--danger)', margin: 0 }}>
                    Errors ({result.errors.length}):
                  </p>
                  <ul
                    style={{
                      margin: '4px 0 0',
                      paddingLeft: 16,
                      fontSize: 12,
                      color: 'var(--danger)',
                      maxHeight: 120,
                      overflowY: 'auto',
                    }}
                  >
                    {result.errors.map((err, i) => (
                      <li key={i}>
                        Row {err.row}: {err.message}
                      </li>
                    ))}
                  </ul>
                </div>
              )}
            </div>

            <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
              <button
                type="button"
                onClick={handleClose}
                style={{
                  padding: '8px 16px',
                  borderRadius: 'var(--r-md)',
                  border: 'none',
                  background: 'var(--brand)',
                  color: '#fff',
                  fontSize: 14,
                  fontWeight: 500,
                  cursor: 'pointer',
                }}
              >
                Close
              </button>
            </div>
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <div>
              <input
                ref={inputRef}
                type="file"
                accept=".csv,.json"
                onChange={handleFileChange}
                style={{ display: 'none' }}
              />
              <button
                type="button"
                onClick={() => inputRef.current?.click()}
                style={{
                  ...inputStyle,
                  cursor: 'pointer',
                  textAlign: 'left',
                  color: file ? 'var(--ink)' : 'var(--ink-muted)',
                }}
              >
                {file ? file.name : 'Choose .csv or .json file...'}
              </button>
              {file && (
                <p style={{ fontSize: 12, color: 'var(--ink-muted)', margin: '4px 0 0' }}>
                  Size: {(file.size / 1024).toFixed(1)} KB
                </p>
              )}
            </div>

            <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
              <button
                type="button"
                onClick={handleClose}
                style={{
                  padding: '8px 16px',
                  borderRadius: 'var(--r-md)',
                  border: '1px solid var(--border)',
                  background: 'transparent',
                  color: 'var(--ink-muted)',
                  fontSize: 14,
                  cursor: 'pointer',
                }}
              >
                Cancel
              </button>
              <button
                type="button"
                onClick={handleUpload}
                disabled={!file || uploading}
                style={{
                  padding: '8px 20px',
                  borderRadius: 'var(--r-md)',
                  border: 'none',
                  background: 'var(--brand)',
                  color: '#fff',
                  fontSize: 14,
                  fontWeight: 500,
                  cursor: !file || uploading ? 'not-allowed' : 'pointer',
                  opacity: !file || uploading ? 0.7 : 1,
                }}
              >
                {uploading ? 'Uploading...' : 'Upload'}
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
