/**
 * Bulk Marks Page (teacher/admin)
 *
 * CSV upload → POST /api/marks/bulk (multipart, field "file")
 * Server returns { inserted, updated, errors: [{ row, reason, data }], total_rows }
 * UI renders per-row errors below.
 */

import { useRef, useState } from 'react';
import { useMarksStore, BulkMarksResult } from '../../store/marks';
import {
  Upload, FileText, CheckCircle2, XCircle, AlertTriangle,
  ChevronRight, Sparkles, Download, X,
} from 'lucide-react';
import { ProgressBar } from '../../components/ui/ProgressBar';

const SAMPLE_CSV = `assignment_id,student_id,score,feedback
1,4,85,"Great work on the algebra section"
1,5,72,"Solid effort, review quadratic equations"
1,6,,`;

export function BulkMarksPage() {
  const {
    uploadBulkMarks,
    lastResult,
    isUploading,
    uploadProgress,
    error,
  } = useMarksStore();
  const fileRef = useRef<HTMLInputElement | null>(null);
  const [filename, setFilename] = useState<string | null>(null);

  const handleFile = (e: React.ChangeEvent<HTMLInputElement>) => {
    const f = e.target.files?.[0];
    if (f) {
      setFilename(f.name);
    }
  };

  const handleUpload = async () => {
    const f = fileRef.current?.files?.[0];
    if (!f) return;
    try {
      await uploadBulkMarks(f);
    } catch {
      // error stored in store
    }
  };

  const handleDownloadSample = () => {
    const blob = new Blob([SAMPLE_CSV], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'bulk-marks-sample.csv';
    a.click();
    URL.revokeObjectURL(url);
  };

  const handleReset = () => {
    if (fileRef.current) fileRef.current.value = '';
    setFilename(null);
    useMarksStore.getState().reset();
  };

  return (
    <div className="space-y-8 animate-in fade-in duration-700 pb-10 max-w-4xl mx-auto">
      {/* Header */}
      <div>
        <h1 className="text-3xl font-black text-text tracking-tight uppercase">
          Bulk Marks Upload
        </h1>
        <nav className="flex text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted gap-2 items-center mt-1">
          <span>Academics</span>
          <ChevronRight size={12} className="text-text-muted/30" />
          <span className="text-primary">CSV Importer</span>
        </nav>
      </div>

      {/* Upload card */}
      <div className="bg-card border border-border rounded-[2rem] overflow-hidden">
        <div className="p-6 bg-muted/30 border-b border-border flex items-center justify-between">
          <h2 className="text-sm font-black uppercase tracking-widest text-primary flex items-center gap-2">
            <Upload size={16} /> Upload CSV
          </h2>
          <button
            onClick={handleDownloadSample}
            className="flex items-center gap-1.5 text-[0.6rem] font-black uppercase tracking-widest text-primary hover:underline"
          >
            <Download size={12} /> Sample CSV
          </button>
        </div>

        <div className="p-8 space-y-6">
          {/* CSV format hint */}
          <div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-100 dark:border-blue-900/30 rounded-2xl p-4 flex items-start gap-3">
            <Sparkles className="text-blue-600 dark:text-blue-400 shrink-0 mt-0.5" size={18} />
            <div className="text-[0.7rem] text-blue-700 dark:text-blue-300">
              <p className="font-black uppercase tracking-widest mb-1">
                Expected columns
              </p>
              <p className="font-mono">
                assignment_id, student_id, score, feedback
              </p>
              <p className="mt-2 text-[0.65rem] text-blue-600 dark:text-blue-400">
                Max 5 MB. Score must be numeric and ≤ assignment.max_score.
                Per-row errors are reported individually — successful rows are
                still committed.
              </p>
            </div>
          </div>

          {/* File picker */}
          <div>
            <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1 mb-1.5 block">
              CSV file
            </label>
            <div className="flex items-center gap-3">
              <input
                ref={fileRef}
                type="file"
                accept=".csv,text/csv,application/vnd.ms-excel,text/plain"
                onChange={handleFile}
                className="flex-1 block w-full text-sm text-text file:mr-4 file:py-2.5 file:px-4 file:rounded-xl file:border-0 file:text-[0.65rem] file:font-black file:uppercase file:tracking-widest file:bg-primary file:text-white hover:file:bg-primary/90 file:cursor-pointer cursor-pointer bg-muted/30 border border-border rounded-2xl"
              />
              <button
                onClick={handleReset}
                className="p-3 bg-card border border-border text-text-muted hover:text-rose-500 rounded-xl"
                title="Reset"
              >
                <X size={16} />
              </button>
            </div>
            {filename && (
              <p className="text-[0.65rem] text-text-muted mt-2 flex items-center gap-2">
                <FileText size={12} /> {filename}
              </p>
            )}
          </div>

          {/* Upload progress bar */}
          {isUploading && (
            <ProgressBar
              progress={uploadProgress}
              label={`Uploading ${filename || 'marks CSV'}...`}
              sublabel="Parsing records and updating student mark submissions..."
              color="emerald"
            />
          )}

          {/* Error */}
          {error && (
            <div className="bg-rose-50 dark:bg-rose-900/20 border border-rose-100 dark:border-rose-900/30 rounded-2xl p-4 flex items-center gap-3">
              <XCircle className="text-rose-600 dark:text-rose-400 shrink-0" size={18} />
              <span className="text-rose-700 dark:text-rose-300 text-sm font-bold">{error}</span>
            </div>
          )}

          {/* Upload button */}
          <div className="flex justify-end">
            <button
              onClick={handleUpload}
              disabled={!filename || isUploading}
              className="flex items-center gap-2 px-8 py-3 bg-primary text-white rounded-2xl font-black text-[0.7rem] uppercase tracking-widest hover:bg-primary/90 transition-all shadow-lg active:scale-95 disabled:opacity-50 cursor-pointer"
            >
              {isUploading ? (
                <>
                  Processing...
                </>
              ) : (
                <>
                  <Upload size={14} /> Upload Marks
                </>
              )}
            </button>
          </div>
        </div>
      </div>

      {/* Result */}
      {lastResult && <ResultPanel result={lastResult} />}
    </div>
  );
}

// ---------- result panel ----------

function ResultPanel({ result }: { result: BulkMarksResult }) {
  const totalOk = result.inserted + result.updated;
  return (
    <div className="bg-card border border-border rounded-[2rem] overflow-hidden animate-in slide-in-from-bottom-4 duration-300">
      <div className="p-6 bg-muted/30 border-b border-border">
        <h2 className="text-sm font-black uppercase tracking-widest text-primary">
          Upload Result
        </h2>
      </div>

      <div className="p-8 space-y-6">
        {/* Top stats */}
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
          <StatCard
            label="Total Rows"
            value={result.total_rows}
            color="blue"
            icon={FileText}
          />
          <StatCard
            label="Inserted"
            value={result.inserted}
            color="emerald"
            icon={CheckCircle2}
          />
          <StatCard
            label="Updated"
            value={result.updated}
            color="amber"
            icon={CheckCircle2}
          />
          <StatCard
            label="Errors"
            value={result.errors.length}
            color={result.errors.length > 0 ? 'rose' : 'muted'}
            icon={result.errors.length > 0 ? AlertTriangle : CheckCircle2}
          />
        </div>

        {/* Banner */}
        {totalOk === result.total_rows && result.errors.length === 0 && (
          <div className="bg-emerald-50 dark:bg-emerald-900/20 border border-emerald-100 dark:border-emerald-900/30 rounded-2xl p-4 flex items-center gap-3">
            <CheckCircle2 className="text-emerald-600 dark:text-emerald-400" size={20} />
            <span className="text-emerald-700 dark:text-emerald-300 font-bold text-sm">
              All {result.total_rows} row{result.total_rows === 1 ? '' : 's'}{' '}
              imported successfully.
            </span>
          </div>
        )}

        {/* Errors */}
        {result.errors.length > 0 && (
          <div className="bg-rose-50/10 dark:bg-rose-950/10 border border-rose-100 dark:border-rose-900/20 rounded-2xl overflow-hidden">
            <div className="px-5 py-3 bg-rose-50 dark:bg-rose-900/20 border-b border-rose-100 dark:border-rose-900/30 flex items-center gap-2">
              <AlertTriangle className="text-rose-600 dark:text-rose-400" size={16} />
              <h3 className="text-[0.7rem] font-black uppercase tracking-widest text-rose-700 dark:text-rose-300">
                {result.errors.length} row
                {result.errors.length === 1 ? '' : 's'} failed
              </h3>
            </div>
            <div className="overflow-x-auto max-h-96">
              <table className="w-full text-left text-sm">
                <thead className="sticky top-0 bg-card">
                  <tr className="border-b border-border">
                    <th className="px-5 py-3 text-[0.6rem] font-black text-primary uppercase tracking-widest w-16">
                      Row
                    </th>
                    <th className="px-5 py-3 text-[0.6rem] font-black text-primary uppercase tracking-widest">
                      Reason
                    </th>
                    <th className="px-5 py-3 text-[0.6rem] font-black text-primary uppercase tracking-widest">
                      Data
                    </th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-border">
                  {result.errors.map((err, i) => (
                    <tr key={i} className="hover:bg-muted/30">
                      <td className="px-5 py-3 font-black text-rose-600">
                        #{err.row}
                      </td>
                      <td className="px-5 py-3 text-text-secondary">
                        {err.reason}
                      </td>
                      <td className="px-5 py-3 text-[0.7rem] font-mono text-text-muted">
                        {err.data
                          ? Object.entries(err.data)
                              .map(([k, v]) => `${k}=${v ?? ''}`)
                              .join(' · ')
                          : '—'}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function StatCard({
  label,
  value,
  color,
  icon: Icon,
}: {
  label: string;
  value: number;
  color: 'blue' | 'emerald' | 'amber' | 'rose' | 'muted';
  icon: any;
}) {
  const palette: Record<string, string> = {
    blue: 'bg-blue-50 dark:bg-blue-950/30 text-blue-600 dark:text-blue-400 border-blue-100 dark:border-blue-900/30',
    emerald: 'bg-emerald-50 dark:bg-emerald-950/30 text-emerald-600 dark:text-emerald-400 border-emerald-100 dark:border-emerald-900/30',
    amber: 'bg-amber-50 dark:bg-amber-950/30 text-amber-600 dark:text-amber-400 border-amber-100 dark:border-amber-900/30',
    rose: 'bg-rose-50 dark:bg-rose-950/30 text-rose-600 dark:text-rose-400 border-rose-100 dark:border-rose-900/30',
    muted: 'bg-muted text-text-muted border-border',
  };
  const p = palette[color];
  return (
    <div className={`bg-card border border-border rounded-2xl p-4 flex items-center gap-3`}>
      <div
        className={`w-11 h-11 rounded-xl flex items-center justify-center border ${p}`}
      >
        <Icon size={20} />
      </div>
      <div>
        <p className="text-[0.6rem] font-black uppercase tracking-widest text-text-muted">
          {label}
        </p>
        <p className="text-2xl font-black text-text leading-tight">{value}</p>
      </div>
    </div>
  );
}

export default BulkMarksPage;
