import React, { useState, useCallback } from 'react';
import { useDropzone } from 'react-dropzone';
import Lottie from 'lottie-react';
import uploadAnimation from '../assets/animations/Animation.json';
import uploadProcessingAnimation from '../assets/animations/UploadProcessing.json';
import './FileUploader.css';
import '@mdi/font/css/materialdesignicons.min.css';
import AnalysisResults from './AnalysisResults';

const FileUploader = () => {
  const [files, setFiles] = useState([]);
  const [uploading, setUploading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [error, setError] = useState('');
  const [computerCode, setComputerCode] = useState('');
  const [isMedicalDocument, setIsMedicalDocument] = useState(false);
  const [documentType, setDocumentType] = useState('');
  const [analysisResults, setAnalysisResults] = useState([]);
  const [showResults, setShowResults] = useState(false);
  const [mobileNumber, setMobileNumber] = useState('');
  const [verificationCode, setVerificationCode] = useState('');
  const [showVerificationCode, setShowVerificationCode] = useState(false);
  const [timer, setTimer] = useState(0);
  const [isVerified, setIsVerified] = useState(false);
  const [verificationError, setVerificationError] = useState('');

  const allowedFileTypes = {
    // فرمت‌های فشرده‌سازی
    'application/zip': true,
    'application/x-7z-compressed': true,
    // فرمت‌های آفیس
    'application/msword': true, // doc
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document': true, // docx
    'application/vnd.ms-excel': true, // xls
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': true, // xlsx
    'application/vnd.ms-powerpoint': true, // ppt
    'application/vnd.openxmlformats-officedocument.presentationml.presentation': true, // pptx
    // فرمت PDF
    'application/pdf': true,
    // فرمت‌های تصویر
    'image/jpeg': true,
    'image/png': true,
    'image/gif': true,
    'image/bmp': true,
    'image/webp': true,
    // فرمت متنی
    'text/plain': true,
  };

  const onDrop = useCallback(async (acceptedFiles) => {
    console.log('Dropped files:', acceptedFiles.map(f => ({ name: f.name, type: f.type })));
    
    const isValidFile = (file) => {
      // برای فایل‌های ZIP و 7Z فقط برای شماره خاص و در صورت تایید
      if (file.name.toLowerCase().endsWith('.zip') || file.name.toLowerCase().endsWith('.7z')) {
        return mobileNumber === '09127169609' && isVerified;
      }
      
      // برای فایل‌های TXT
      if (file.name.toLowerCase().endsWith('.txt')) {
        return true;
      }
      
      // برای سایر فایل‌های مجاز
      return allowedFileTypes[file.type];
    };

    const invalidFiles = acceptedFiles.filter(file => !isValidFile(file));
    
    if (invalidFiles.length > 0) {
      if (mobileNumber !== '09127169609' || !isVerified) {
        setError('فایل‌های ZIP و 7ZIP فقط برای کاربران مجاز قابل آپلود است.');
      } else {
        setError('فقط فایل‌های ZIP، 7ZIP، TXT، اسناد Office و تصاویر مجاز هستند.');
      }
      setTimeout(() => setError(''), 5000);
      return;
    }

    setError('');
    setUploading(true);
    setUploadProgress(0);
    
    for (let progress = 0; progress <= 100; progress += 10) {
      await new Promise(resolve => setTimeout(resolve, 200));
      setUploadProgress(progress);
    }
    
    setFiles(prev => [...prev, ...acceptedFiles]);
    setUploading(false);
    setUploadProgress(0);
  }, [mobileNumber, isVerified]);

  const { getRootProps, getInputProps, isDragActive } = useDropzone({ 
    onDrop,
    accept: {
      'application/zip': ['.zip'],
      'application/x-7z-compressed': ['.7z'],
      'application/msword': ['.doc'],
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document': ['.docx'],
      'application/vnd.ms-excel': ['.xls'],
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': ['.xlsx'],
      'application/vnd.ms-powerpoint': ['.ppt'],
      'application/vnd.openxmlformats-officedocument.presentationml.presentation': ['.pptx'],
      'application/pdf': ['.pdf'],
      'image/*': ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'],
      'text/plain': ['.txt']
    },
    multiple: true
  });

  const getFileIcon = (fileType) => {
    // فایل‌های فشرده
    if (fileType === 'application/zip' || fileType === 'application/x-7z-compressed') {
      return 'mdi mdi-zip-box';
    }
    
    // فایل‌های Word
    if (fileType === 'application/msword' || 
        fileType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
      return 'mdi mdi-microsoft-word';
    }
    
    // فایل‌های Excel
    if (fileType === 'application/vnd.ms-excel' || 
        fileType === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
      return 'mdi mdi-microsoft-excel';
    }
    
    // فایل‌های PowerPoint
    if (fileType === 'application/vnd.ms-powerpoint' || 
        fileType === 'application/vnd.openxmlformats-officedocument.presentationml.presentation') {
      return 'mdi mdi-microsoft-powerpoint';
    }
    
    // فایل PDF
    if (fileType === 'application/pdf') {
      return 'mdi mdi-file-pdf-box';
    }
    
    // فایل‌های تصویری
    if (fileType.startsWith('image/')) {
      return 'mdi mdi-file-image';
    }
    
    // فایل‌های اجرایی
    if (fileType === 'application/x-msdownload') {
      return 'mdi mdi-application';
    }
    
    return 'mdi mdi-file-document';
  };

  const getFileColor = (fileType) => {
    // فایل‌های فشرده
    if (fileType === 'application/zip' || fileType === 'application/x-7z-compressed') {
      return 'bg-primary';
    }
    
    // فایل‌های Word
    if (fileType === 'application/msword' || 
        fileType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
      return 'bg-info';
    }
    
    // فایل‌های Excel
    if (fileType === 'application/vnd.ms-excel' || 
        fileType === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
      return 'bg-success';
    }
    
    // فایل‌های PowerPoint
    if (fileType === 'application/vnd.ms-powerpoint' || 
        fileType === 'application/vnd.openxmlformats-officedocument.presentationml.presentation') {
      return 'bg-warning';
    }
    
    // فایل PDF
    if (fileType === 'application/pdf') {
      return 'bg-danger';
    }
    
    // فایل‌های تصویری
    if (fileType.startsWith('image/')) {
      return 'bg-primary';
    }
    
    // فایل‌های اجرایی
    if (fileType === 'application/x-msdownload') {
      return 'bg-danger';
    }
    
    return 'bg-secondary';
  };

  const handleRemoveFile = (indexToRemove) => {
    setFiles(prevFiles => prevFiles.filter((_, index) => index !== indexToRemove));
  };

  const handleComputerCodeChange = (e) => {
    const value = e.target.value.toUpperCase();
    
    // برای اولین کاراکتر فقط S مجاز است
    if (value.length === 1) {
      if (value === 'S') {
        setComputerCode(value);
        setDocumentType('manual');
      }
      return;
    }

    // برای دومین کاراکتر فقط 1 یا 2 مجاز است
    if (value.length === 2) {
      if (value.startsWith('S') && ['1', '2'].includes(value[1])) {
        setComputerCode(value);
        setDocumentType('manual');
      }
      return;
    }

    if (value.length <= 5) {
      const regex = /^S[12]\d{0,3}$/;
      if (regex.test(value)) {
        setComputerCode(value);
        setDocumentType('manual');
      }
    }
  };

  const uploadFile = async (file) => {
    console.log('Uploading file:', file.name);
    
    const formData = new FormData();
    formData.append('files', file);

    const url = new URL('http://fileshare.ikid.ir:44310/api/FileAnalysis/upload');
    url.searchParams.append('computerCode', computerCode);
    url.searchParams.append('documentType', documentType);
    url.searchParams.append('phoneNumber', mobileNumber);

    try {
      const response = await fetch(url.toString(), {
        method: 'POST',
        body: formData,
        credentials: 'include'
      });

      if (!response.ok) {
        const errorText = await response.text();
        console.error('Server error:', errorText);
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const result = await response.json();
      console.log('Server Response:', result);
      
      // بررسی نتیجه اولین آیتم از آرایه پاسخ
      const scanResult = result[0];
      
      return {
        ...scanResult,
        fileName: file.name,
        status: scanResult.isMalicious ? 'malicious' : 
                scanResult.isClean ? 'clean' : 'error',
        threatDetails: scanResult.detectedThreats.length > 0 ? {
          count: scanResult.detectedThreats.length,
          name: scanResult.threatName
        } : null
      };
    } catch (error) {
      console.error('Error in uploadFile:', error);
      return {
        fileName: file.name,
        status: 'error',
        isSuccess: false,
        errorMessage: error.message
      };
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    console.log('Submit button clicked');

    if (files.length === 0) {
      setError('لطفاً حداقل یک فایل انتخاب کنید');
      setTimeout(() => setError(''), 5000);
      return;
    }

    if (!computerCode) {
      setError('لطفاً کد کامپیوتر را وارد کنید');
      setTimeout(() => setError(''), 5000);
      return;
    }

    if (!documentType) {
      setError('نوع سند مشخص نشده است');
      setTimeout(() => setError(''), 5000);
      return;
    }

    setUploading(true);
    setShowResults(true);

    try {
      // کپی از آرایه فایل‌ها می‌گیریم تا بتوانیم در حلقه تغییرش دهیم
      const filesToProcess = [...files];
      
      while (filesToProcess.length > 0) {
        const file = filesToProcess[0]; // اولین فایل از لیست
        const result = await uploadFile(file);
        
        // اضافه کردن نتیجه به لیست نتایج
        setAnalysisResults(prevResults => [...prevResults, result]);
        
        // حذف فایل از لیست اصلی فایل‌ها
        setFiles(prevFiles => prevFiles.filter(f => f !== file));
        
        // حذف فایل از لیست موقت
        filesToProcess.shift();
        
        // آپدیت درصد پیشرفت
        setUploadProgress(((files.length - filesToProcess.length) / files.length) * 100);
      }
    } catch (error) {
      console.error('Error in handleSubmit:', error);
    }

    setUploading(false);
    setUploadProgress(0);
  };

  const handleMobileNumberChange = (e) => {
    const value = e.target.value;
    // فقط اجازه ورود اعداد
    if (/^\d*$/.test(value)) {
      if (value === '' || value === '0' || value.startsWith('09')) {
        setMobileNumber(value);
      }
    }
  };

  const handleVerificationCodeChange = (e) => {
    const value = e.target.value;
    // فقط اجازه ورود 6 رقم عدد
    if (/^\d{0,6}$/.test(value)) {
      setVerificationCode(value);
    }
  };

  const handleSendSMS = async () => {
    if (mobileNumber.length === 11) {
      try {
        const response = await fetch('http://fileshare.ikid.ir:44310/api/SmsVerification/send', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ phoneNumber: mobileNumber }),
          credentials: 'include'
        });

        if (!response.ok) {
          throw new Error('خطا در ارسال پیامک');
        }

        setShowVerificationCode(true);
        setTimer(60);
        setVerificationError('');

        // Start countdown timer
        const interval = setInterval(() => {
          setTimer((prevTimer) => {
            if (prevTimer <= 1) {
              clearInterval(interval);
              return 0;
            }
            return prevTimer - 1;
          });
        }, 1000);

      } catch (error) {
        setVerificationError('خطا در ارسال پیامک. لطفا مجددا تلاش کنید.');
      }
    }
  };

  const handleVerifyCode = async () => {
    try {
      const response = await fetch('http://fileshare.ikid.ir:44310/api/SmsVerification/verify', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ 
          phoneNumber: mobileNumber,
          code: verificationCode 
        }),
        credentials: 'include'
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.message || 'کد تایید نامعتبر است');
      }

      setIsVerified(true);
      setVerificationError('');
      setTimer(0);

    } catch (error) {
      setVerificationError(error.message);
      setIsVerified(false);
    }
  };

  return (
    <div className="page-container">
      <div className="header-titles">
        <h1 className="title-line1">واحد سیستم‌ها و انفورماتیک</h1>
        <h1 className="title-line2">اداره مهندسی سامانه‌های کاربردی</h1>
        <h1 className="title-line3">سامانه انتقال امن اشتراک فایل</h1>
      </div>
      <div className="panel">
        <div {...getRootProps()} className={`upload-box ${isDragActive ? 'active' : ''}`}>
          <input {...getInputProps()} />
          <div className="lottie-container">
            <Lottie
              animationData={uploading ? uploadProcessingAnimation : uploadAnimation}
              loop={true}
              autoplay={true}
              style={{ height: 200, width: 200 }}
            />
          </div>
        </div>
        <p style={{ 
          textAlign: 'center', 
          fontSize: '12px',
          fontFamily: 'IRANSansWeb(FaNum)',
          color: '#1a237e',
          marginTop: '-15px'
        }}>
          برای انتخاب فایل روی باکس بالا کلیک کنید یا فایل خود را اینجا رها کنید
        </p>
        
        {uploading && (
          <>
            <div className="upload-progress">
              <div 
                className="progress-bar" 
                style={{ width: `${uploadProgress}%` }}
              />
            </div>
            <div className="upload-status">
              در حال آپلود... {uploadProgress}%
            </div>
          </>
        )}
        
        {files.length > 0 && (
          <div className="files-container">
            <h6 className="files-title">فایل های پیوست شده</h6>
            <div className="tags">
              {files.map((file, index) => (
                <span 
                  key={index} 
                  className={`tag tag-attachments`}
                >
                  <span className="me-2">
                    <i className={`${getFileIcon(file.type)} tx-24`} style={{ verticalAlign: 'middle' }}></i>
                  </span>
                  {file.name}
                  <button 
                    className="delete-btn"
                    onClick={() => handleRemoveFile(index)}
                    title="حذف فایل"
                  >
                    ×
                  </button>
                </span>
              ))}
            </div>
          </div>
          
        )}
        
        {error && (
          <div className="error-message">
            {error}
          </div>
        )}
           {!isMedicalDocument && (
             <div style={{ 
               display: 'flex', 
               flexDirection: 'row-reverse',
               alignItems: 'center', 
               justifyContent: 'flex-start',
               marginTop: '15px',
               fontFamily: 'IRANSansWeb(FaNum)',
               fontSize: '14px',
               color: '#1a237e'
             }}>
               <label 
                 htmlFor="computerCode" 
                 style={{ 
                   marginLeft: '8px',
                   marginBottom: 0
                 }}
               >
                 :کد کامپیوتر
               </label>
               <input
                 type="text"
                 id="computerCode"
                 value={computerCode}
                 onChange={handleComputerCodeChange}
                 placeholder="S1234"
                 style={{ 
                   width: '80px',
                   padding: '4px 8px',
                   direction: 'ltr',
                   textTransform: 'uppercase',
                   letterSpacing: '1px',
                   border: '1px solid #ddd',
                   borderRadius: '4px',
                   fontSize: '14px'
                 }}
                 maxLength="5"
                 autoComplete="off"
               />
             </div>
           )}
        <div style={{ 
          display: 'flex', 
          flexDirection: 'row-reverse',
          alignItems: 'center', 
          justifyContent: 'flex-start',
          marginTop: '10px',
          fontFamily: 'IRANSansWeb(FaNum)',
          fontSize: '14px',
          color: '#1a237e'
        }}>
          <label 
            style={{ 
              marginLeft: '8px',
              marginBottom: 0,
              cursor: 'pointer'
            }}
          >
            ارسال مدارک پزشکی
            <input
              type="checkbox"
              checked={documentType === 'medical'}
              onChange={(e) => {
                if (e.target.checked) {
                  setDocumentType('medical');
                  setIsMedicalDocument(true);
                  setComputerCode('S1371');
                } else {
                  setDocumentType('');
                  setIsMedicalDocument(false);
                  setComputerCode('');
                }
              }}
              style={{ marginRight: '8px' }}
            />
          </label>
          <label 
            style={{ 
              marginLeft: '8px',
              marginBottom: 0,
              cursor: 'pointer'
            }}
          >
            ارسال مدارک استعلاجی
            <input
              type="checkbox"
              checked={documentType === 'sick-leave'}
              onChange={(e) => {
                if (e.target.checked) {
                  setDocumentType('sick-leave');
                  setIsMedicalDocument(true);
                  setComputerCode('S1912');
                } else {
                  setDocumentType('');
                  setIsMedicalDocument(false);
                  setComputerCode('');
                }
              }}
              style={{ marginRight: '8px' }}
            />
          </label>
        </div>

        <div className="mobile-verification-container">
          <div className="input-group">
            <div style={{ 
              display: 'flex', 
              flexDirection: 'row-reverse',
              alignItems: 'center',
              gap: '8px',
              marginTop: '15px',
              fontFamily: 'IRANSansWeb(FaNum)',
              fontSize: '14px',
              color: '#1a237e'
            }}>
              <label 
                htmlFor="mobileNumber" 
                style={{ 
                  marginLeft: '8px',
                  marginBottom: 0
                }}
              >
                :شماره همراه
              </label>
              <input
                type="tel"
                id="mobileNumber"
                value={mobileNumber}
                onChange={handleMobileNumberChange}
                placeholder="09123456789"
                maxLength="11"
                disabled={isVerified}
                style={{
                  width: '120px',
                  padding: '6px 12px',
                  border: '1px solid #ddd',
                  borderRadius: '4px',
                  fontSize: '14px',
                  direction: 'ltr',
                  textAlign: 'left',
                  backgroundColor: isVerified ? '#f5f5f5' : 'white',
                  cursor: isVerified ? 'not-allowed' : 'text'
                }}
              />
              {!isVerified && (
                <button 
                  onClick={handleSendSMS}
                  disabled={mobileNumber.length !== 11 || timer > 0}
                  title={timer > 0 ? `${timer} ثانیه تا ارسال مجدد` : "ارسال کد تایید"}
                  style={{
                    backgroundColor: timer > 0 ? '#e0e0e0' : '#1a237e',
                    color: timer > 0 ? '#666' : 'white',
                    border: 'none',
                    borderRadius: '4px',
                    padding: '6px 12px',
                    fontSize: '14px',
                    cursor: timer > 0 ? 'not-allowed' : 'pointer',
                    display: 'flex',
                    alignItems: 'center',
                    gap: '4px',
                    transition: 'all 0.3s ease'
                  }}
                >
                  {timer > 0 ? `${timer} ثانیه` : 'ارسال کد'}
                </button>
              )}
            </div>
          </div>

          {showVerificationCode && (
            <div style={{ 
              display: 'flex', 
              flexDirection: 'row-reverse',
              alignItems: 'center',
              gap: '8px',
              marginTop: '10px',
              fontFamily: 'IRANSansWeb(FaNum)',
              fontSize: '14px',
              color: '#1a237e'
            }}>
              <label 
                htmlFor="verificationCode"
                style={{ 
                  marginLeft: '8px',
                  marginBottom: 0
                }}
              >
                :کد تایید
              </label>
              <input
                type="text"
                id="verificationCode"
                value={verificationCode}
                onChange={handleVerificationCodeChange}
                placeholder="کد 6 رقمی"
                maxLength="6"
                style={{
                  width: '100px',
                  padding: '6px 12px',
                  border: '1px solid #ddd',
                  borderRadius: '4px',
                  fontSize: '14px',
                  direction: 'ltr',
                  textAlign: 'center',
                  letterSpacing: '2px'
                }}
              />
              <button 
                onClick={handleVerifyCode}
                disabled={verificationCode.length !== 6 || isVerified}
                style={{
                  backgroundColor: isVerified ? '#4caf50' : '#1a237e',
                  color: 'white',
                  border: 'none',
                  borderRadius: '4px',
                  padding: '6px 16px',
                  fontSize: '14px',
                  cursor: isVerified ? 'not-allowed' : 'pointer',
                  display: 'flex',
                  alignItems: 'center',
                  gap: '4px',
                  transition: 'all 0.3s ease'
                }}
              >
                {isVerified ? (
                  <>
                    <i className="mdi mdi-check"></i>
                    تایید شد
                  </>
                ) : (
                  'ثبت کد تایید'
                )}
              </button>
            </div>
          )}

          {verificationError && (
            <div style={{
              color: '#f44336',
              fontSize: '12px',
              marginTop: '8px',
              textAlign: 'right',
              fontFamily: 'IRANSansWeb(FaNum)'
            }}>
              {verificationError}
            </div>
          )}
        </div>

        {/* دکمه جدید ارسال */}
        <div style={{
          display: 'flex',
          justifyContent: 'center',
          marginTop: '20px'
        }}>
          <button
            className="persian-button"
            onClick={handleSubmit}
            disabled={!isVerified}
            style={{
              backgroundColor: !isVerified ? '#e0e0e0' : '#1a237e',
              color: !isVerified ? '#666' : 'white',
              border: 'none',
              borderRadius: '8px',
              padding: '10px 25px',
              fontSize: '14px',
              cursor: !isVerified ? 'not-allowed' : 'pointer',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'flex-end',
              gap: '8px',
              transition: 'background-color 0.3s'
            }}
          >
            ارسال اطلاعات
            <i className="mdi mdi-send" style={{ fontSize: '18px' }}></i>
          </button>
        </div>
      </div>
      
      {showResults && (
        <div className="analysis-results-box">
          <AnalysisResults results={analysisResults} />
        </div>
      )}
    </div>
  );
};

export default FileUploader;