import { mdiArrowLeft, mdiFileUploadOutline, mdiCheckCircle, mdiAlertCircle } from '@mdi/js';
import Head from 'next/head';
import React, { ReactElement, useState } from 'react';
import { useRouter } from 'next/router';
import CardBox from '../../components/CardBox';
import LayoutAuthenticated from '../../layouts/Authenticated';
import SectionMain from '../../components/SectionMain';
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton';
import { getPageTitle } from '../../config';
import BaseButton from '../../components/BaseButton';
import BaseIcon from '../../components/BaseIcon';

const ImportUpload = () => {
  const router = useRouter();
  const { code } = router.query;
  const [file, setFile] = useState<File | null>(null);
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      const selectedFile = e.target.files[0];
      if (selectedFile.name.endsWith('.csv') || selectedFile.name.endsWith('.xls') || selectedFile.name.endsWith('.xlsx')) {
        setFile(selectedFile);
        setError(null);
      } else {
        setError('Please select a valid CSV or Excel file.');
        setFile(null);
      }
    }
  };

  const handleUpload = async () => {
    if (!file) return;
    setUploading(true);
    // In a real app, we would upload the file here.
    // For now, we'll simulate a successful upload and redirect to a mapping page (next task)
    setTimeout(() => {
      setUploading(false);
      alert('File uploaded successfully! Next: Column Mapping (Coming Soon)');
      router.push('/imports');
    }, 1500);
  };

  return (
    <>
      <Head>
        <title>{getPageTitle(`Upload ${code}`)}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiFileUploadOutline} title={`Upload ${code} Data`} main>
          <BaseButton href="/imports" icon={mdiArrowLeft} label="Back" color="white" />
        </SectionTitleLineWithButton>

        <CardBox className="max-w-2xl mx-auto">
          <div className="space-y-6">
            <div className="text-center p-8 border-2 border-dashed border-gray-300 rounded-lg bg-gray-50">
              <BaseIcon path={mdiFileUploadOutline} size={48} className="mx-auto text-gray-400 mb-4" />
              <p className="text-lg font-medium text-gray-700">Select file to import for {code}</p>
              <p className="text-sm text-gray-500 mb-6">Supported formats: CSV, XLS, XLSX</p>
              
              <input
                type="file"
                id="file-upload"
                className="hidden"
                accept=".csv, .xls, .xlsx"
                onChange={handleFileChange}
              />
              <label
                htmlFor="file-upload"
                className="cursor-pointer bg-white py-2 px-4 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
              >
                Browse Files
              </label>
              
              {file && (
                <div className="mt-4 flex items-center justify-center text-indigo-600 font-medium">
                  <BaseIcon path={mdiCheckCircle} size={20} className="mr-2" />
                  {file.name}
                </div>
              )}
              
              {error && (
                <div className="mt-4 flex items-center justify-center text-red-600 font-medium">
                  <BaseIcon path={mdiAlertCircle} size={20} className="mr-2" />
                  {error}
                </div>
              )}
            </div>

            <div className="bg-blue-50 p-4 rounded-md">
              <h4 className="text-blue-800 font-bold mb-1">Import Rules for {code}:</h4>
              <ul className="text-blue-700 text-sm list-disc list-inside">
                <li>File must include a header row.</li>
                <li>Required fields must not be empty.</li>
                <li>Data will be validated against tenant-specific rules.</li>
              </ul>
            </div>

            <BaseButton
              color="info"
              label={uploading ? "Uploading..." : "Process File"}
              disabled={!file || uploading}
              className="w-full"
              onClick={handleUpload}
            />
          </div>
        </CardBox>
      </SectionMain>
    </>
  );
};

ImportUpload.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated>{page}</LayoutAuthenticated>;
};

export default ImportUpload;
