'use client';
import { useState } from 'react';

export default function AdminSPSDTPage() {
  const [file, setFile] = useState<File | null>(null);
  const [password, setPassword] = useState('');
  const [status, setStatus] = useState<{ loading: boolean; message: string; type: 'idle' | 'success' | 'error' }>({
    loading: false,
    message: '',
    type: 'idle'
  });

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!file || !password) {
      setStatus({ loading: false, message: 'Please provide both the password and a file.', type: 'error' });
      return;
    }

    setStatus({ loading: true, message: 'Uploading and parsing data...', type: 'idle' });

    const formData = new FormData();
    formData.append('file', file);
    formData.append('password', password);

    try {
      const response = await fetch('/api/spsdt/admin/upload', {
        method: 'POST',
        body: formData,
      });

      const data = await response.json();

      if (response.ok) {
        setStatus({ loading: false, message: data.message || 'Upload successful', type: 'success' });
      } else {
        setStatus({ loading: false, message: data.error || 'Upload failed', type: 'error' });
      }
    } catch (err: any) {
      setStatus({ loading: false, message: err.message || 'An unexpected error occurred.', type: 'error' });
    }
  };

  return (
    <div className="flex flex-col w-full min-h-screen bg-surface-container-low text-on-surface p-8">
      <div className="max-w-3xl mx-auto w-full mt-12 bg-white p-8 rounded-[2rem] shadow-lg border border-white/60">
        <h1 className="text-3xl font-headline font-bold text-primary mb-4 tracking-tight uppercase">SPSDT Data Management</h1>
        <p className="text-on-surface-variant font-body mb-8">
          Upload a new `spsdt_data.xlsx` file to completely overwrite the current Speciality Demand Database. 
          The uploaded file must contain a `NATIONAL` sheet or be the first sheet, possessing the exact preconfigured column headers.
        </p>
        
        {status.type !== 'idle' && (
          <div className={`p-4 rounded-lg mb-6 font-body text-sm font-medium ${status.type === 'error' ? 'bg-error-container text-on-error-container' : 'bg-green-100 text-green-800'}`}>
            {status.message}
          </div>
        )}

        <form onSubmit={handleSubmit} className="flex flex-col gap-6">
          <div className="flex flex-col gap-2">
            <label className="font-headline font-bold text-sm tracking-wide text-primary">Admin Password</label>
            <input 
              type="password" 
              className="p-3 border border-slate-300 rounded-lg focus:ring-2 focus:ring-[#861F41] outline-none"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="Enter authorization password"
            />
          </div>

          <div className="flex flex-col gap-2">
            <label className="font-headline font-bold text-sm tracking-wide text-primary">Data File (.xlsx)</label>
            <input 
              type="file" 
              accept=".xlsx, .xls"
              className="p-3 border border-slate-300 rounded-lg bg-slate-50 focus:ring-2 focus:ring-[#861F41] outline-none file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-[#861F41]/10 file:text-[#861F41] hover:file:bg-[#861F41]/20"
              onChange={(e) => setFile(e.target.files?.[0] || null)}
            />
            <p className="text-xs text-slate-500 font-body">Uploading unformatted data will cause public tool failures.</p>
          </div>

          <button 
            type="submit" 
            disabled={status.loading}
            className="mt-4 bg-[#861F41] hover:bg-[#6c1733] text-white font-headline font-bold py-4 px-8 rounded-lg transition-all shadow-md active:scale-95 disabled:opacity-50 disabled:active:scale-100 flex justify-center uppercase tracking-wider"
          >
            {status.loading ? 'Processing...' : 'Upload & Overwrite Data'}
          </button>
        </form>
      </div>
    </div>
  );
}
