/**
 * Import page for {{ model_name }}.
 *
 * ✅ YOUR CODE - Safe to modify, will not be overwritten.
 * This file was generated once by Prism and is yours to customize.
 */

import React, { useState, useCallback } from 'react';
import type { JSX } from 'react';
import { useNavigate } from 'react-router-dom';
import { use{{ model_name }}Mutations } from '../../hooks/use{{ model_name }}';

type ImportRow = Record<string, unknown>;

function parseCSV(text: string): ImportRow[] {
  const lines = text.trim().split('\n');
  if (lines.length < 2) return [];
  const headers = lines[0].split(',').map((h) => h.trim().replace(/^"|"$/g, ''));
  return lines.slice(1).map((line) => {
    const values = line.split(',').map((v) => v.trim().replace(/^"|"$/g, ''));
    const row: ImportRow = {};
    headers.forEach((h, i) => {
      row[h] = values[i] ?? '';
    });
    return row;
  });
}

function parseJSON(text: string): ImportRow[] {
  const parsed = JSON.parse(text);
  return Array.isArray(parsed) ? parsed : [parsed];
}

export default function {{ model_name }}ImportPage(): JSX.Element {
  const navigate = useNavigate();
  const { create, loading } = use{{ model_name }}Mutations();
  const [rows, setRows] = useState<ImportRow[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [imported, setImported] = useState(0);

  const handleFileUpload = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setError(null);

    const reader = new FileReader();
    reader.onload = (event) => {
      try {
        const text = event.target?.result as string;
        if (file.name.endsWith('.json')) {
          setRows(parseJSON(text));
        } else {
          setRows(parseCSV(text));
        }
      } catch (err) {
        setError(`Failed to parse file: ${(err as Error).message}`);
      }
    };
    reader.readAsText(file);
  }, []);

  const handleImport = useCallback(async () => {
    setError(null);
    let count = 0;
    for (const row of rows) {
      try {
        await create(row);
        count++;
      } catch (err) {
        setError(`Failed at row ${count + 1}: ${(err as Error).message}`);
        break;
      }
    }
    setImported(count);
    if (count === rows.length) {
      setRows([]);
    }
  }, [rows, create]);

  return (
    <div className="page-container">
      <header className="page-header flex items-center justify-between">
        <div>
          <h1 className="page-title">Import {{ plural_name }}</h1>
          <p className="page-subtitle">Upload a CSV or JSON file to import records</p>
        </div>
        <button onClick={() => navigate('/{{ plural_kebab }}')} className="btn-secondary">
          Back to list
        </button>
      </header>

      {error && (
        <div className="alert-error mb-4">
          <p>{error}</p>
        </div>
      )}

      {imported > 0 && (
        <div className="bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded-nordic mb-4">
          <p>Successfully imported {imported} record{imported !== 1 ? 's' : ''}.</p>
        </div>
      )}

      <div className="card p-6 space-y-4">
        <div>
          <label className="block text-sm font-medium text-foreground mb-2">
            Upload file (CSV or JSON)
          </label>
          <input
            type="file"
            accept=".csv,.json"
            onChange={handleFileUpload}
            className="block w-full text-sm text-muted file:mr-4 file:py-2 file:px-4 file:rounded-nordic file:border-0 file:text-sm file:font-medium file:bg-surface-sunken file:text-foreground hover:file:bg-surface"
          />
        </div>

        {rows.length > 0 && (
          <>
            <div className="border border-border rounded-nordic overflow-hidden">
              <div className="px-4 py-2 bg-surface-sunken border-b border-border">
                <p className="text-sm font-medium text-foreground">
                  Preview ({rows.length} row{rows.length !== 1 ? 's' : ''})
                </p>
              </div>
              <div className="overflow-x-auto max-h-64">
                <table className="w-full text-sm">
                  <thead className="bg-surface-sunken">
                    <tr>
                      {Object.keys(rows[0]).map((key) => (
                        <th key={key} className="px-3 py-2 text-left text-xs font-medium text-muted">
                          {key}
                        </th>
                      ))}
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border">
                    {rows.slice(0, 10).map((row, i) => (
                      <tr key={i}>
                        {Object.values(row).map((val, j) => (
                          <td key={j} className="px-3 py-2 text-foreground whitespace-nowrap">
                            {String(val ?? '')}
                          </td>
                        ))}
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
              {rows.length > 10 && (
                <div className="px-4 py-2 bg-surface-sunken border-t border-border">
                  <p className="text-xs text-muted">Showing 10 of {rows.length} rows</p>
                </div>
              )}
            </div>

            <button
              onClick={handleImport}
              disabled={loading}
              className="btn-primary disabled:opacity-50"
            >
              {loading ? 'Importing...' : `Import ${rows.length} record${rows.length !== 1 ? 's' : ''}`}
            </button>
          </>
        )}
      </div>
    </div>
  );
}
