import React, { useState } from 'react';
import { Upload, FileArchive, CheckCircle2, AlertCircle, RefreshCcw, ArrowRight, ShieldCheck } from 'lucide-react';
import { toast } from 'sonner';
import { motion } from 'framer-motion';

export function CodeImport() {
  const [file, setFile] = useState<File | null>(null);
  const [isUploading, setIsUploading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [status, setStatus] = useState<'idle' | 'uploading' | 'verifying' | 'success' | 'error'>('idle');

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFile = e.target.files?.[0];
    if (selectedFile) {
      if (selectedFile.type !== 'application/zip' && !selectedFile.name.endsWith('.zip')) {
        toast.error('Please select a ZIP file');
        return;
      }
      setFile(selectedFile);
      setStatus('idle');
    }
  };

  const handleUpload = async () => {
    if (!file) {
      toast.error('Please select a file first');
      return;
    }

    setIsUploading(true);
    setStatus('uploading');
    setUploadProgress(0);

    // Simulate upload progress
    const interval = setInterval(() => {
      setUploadProgress(prev => {
        if (prev >= 95) {
          clearInterval(interval);
          return 95;
        }
        return prev + 5;
      });
    }, 100);

    try {
      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      setUploadProgress(100);
      setStatus('verifying');
      
      // Simulate verification
      await new Promise(resolve => setTimeout(resolve, 1500));
      
      setStatus('success');
      toast.success('System update package uploaded and verified successfully');
    } catch (error) {
      setStatus('error');
      toast.error('Failed to upload update package');
    } finally {
      setIsUploading(false);
      clearInterval(interval);
    }
  };

  return (
    <div className="space-y-6">
      <div className="bg-primary/5 rounded-2xl p-6 border border-primary/10 mb-6">
        <div className="flex items-start gap-4">
          <div className="p-3 rounded-xl bg-primary/10 text-primary">
            <ShieldCheck size={24} />
          </div>
          <div>
            <h3 className="text-lg font-bold">System Update & Import</h3>
            <p className="text-sm text-muted-foreground mt-1">
              Upload a ZIP package to update system modules, components, or static assets. 
              Always ensure you have a full database backup before proceeding with system-wide imports.
            </p>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div className="space-y-4">
          <div 
            className={`
              relative border-2 border-dashed rounded-2xl p-10 flex flex-col items-center justify-center transition-all
              ${status === 'success' ? 'border-green-500 bg-green-50' : 'border-border bg-muted/30 hover:border-primary/50'}
            `}
          >
            <input 
              type="file" 
              className="absolute inset-0 opacity-0 cursor-pointer" 
              accept=".zip"
              onChange={handleFileChange}
              disabled={isUploading}
            />
            
            <div className={`p-4 rounded-full mb-4 ${status === 'success' ? 'bg-green-100 text-green-600' : 'bg-primary/10 text-primary'}`}>
              {status === 'success' ? <CheckCircle2 size={40} /> : <FileArchive size={40} />}
            </div>
            
            <div className="text-center">
              <p className="font-semibold text-lg">
                {file ? file.name : 'Click or drag ZIP file here'}
              </p>
              <p className="text-sm text-muted-foreground mt-1">
                {file ? `${(file.size / (1024 * 1024)).toFixed(2)} MB` : 'System package format (.zip) only'}
              </p>
            </div>

            {status === 'uploading' && (
              <div className="absolute inset-x-6 bottom-6">
                <div className="h-1.5 w-full bg-border rounded-full overflow-hidden">
                  <motion.div 
                    initial={{ width: 0 }}
                    animate={{ width: `${uploadProgress}%` }}
                    className="h-full bg-primary"
                  />
                </div>
                <p className="text-[10px] text-center mt-2 font-medium text-primary">
                  Uploading... {uploadProgress}%
                </p>
              </div>
            )}
          </div>

          <div className="flex gap-3">
            <button
              onClick={handleUpload}
              disabled={!file || isUploading || status === 'success'}
              className="flex-1 flex items-center justify-center gap-2 bg-primary text-primary-foreground px-6 py-3 rounded-xl font-bold hover:bg-primary/90 transition-all disabled:opacity-50 shadow-lg shadow-primary/20"
            >
              {isUploading ? <RefreshCcw className="animate-spin" size={18} /> : <Upload size={18} />}
              Push Update Package
            </button>
            {status === 'success' && (
              <button
                onClick={() => { setFile(null); setStatus('idle'); }}
                className="px-6 py-3 rounded-xl font-bold border border-border hover:bg-muted transition-all"
              >
                Reset
              </button>
            )}
          </div>
        </div>

        <div className="space-y-4">
          <h4 className="text-sm font-bold uppercase tracking-wider text-muted-foreground flex items-center gap-2">
            Import History
            <span className="h-1 w-1 rounded-full bg-muted-foreground" />
          </h4>
          
          <div className="space-y-3">
            <div className="p-4 rounded-xl border border-border bg-card flex items-center justify-between">
              <div className="flex items-center gap-3">
                <div className="p-2 rounded-lg bg-green-500/10 text-green-500">
                  <CheckCircle2 size={16} />
                </div>
                <div>
                  <p className="text-sm font-bold">V-2.4.0-Patch.zip</p>
                  <p className="text-[10px] text-muted-foreground">Applied on April 22, 2024</p>
                </div>
              </div>
              <div className="text-right">
                <p className="text-[10px] font-bold text-muted-foreground">Admin-01</p>
                <p className="text-[10px] text-muted-foreground">42.5 MB</p>
              </div>
            </div>

            <div className="p-4 rounded-xl border border-border bg-card flex items-center justify-between">
              <div className="flex items-center gap-3">
                <div className="p-2 rounded-lg bg-green-500/10 text-green-500">
                  <CheckCircle2 size={16} />
                </div>
                <div>
                  <p className="text-sm font-bold">Base_Assets_V1.zip</p>
                  <p className="text-[10px] text-muted-foreground">Applied on April 15, 2024</p>
                </div>
              </div>
              <div className="text-right">
                <p className="text-[10px] font-bold text-muted-foreground">System</p>
                <p className="text-[10px] text-muted-foreground">128.0 MB</p>
              </div>
            </div>

            <div className="p-4 rounded-xl border border-border bg-card flex items-center justify-between opacity-60">
              <div className="flex items-center gap-3">
                <div className="p-2 rounded-lg bg-red-500/10 text-red-500">
                  <AlertCircle size={16} />
                </div>
                <div>
                  <p className="text-sm font-bold">Corrupted_Patch.zip</p>
                  <p className="text-[10px] text-muted-foreground">Failed on April 10, 2024</p>
                </div>
              </div>
              <div className="text-right text-red-500 text-[10px] font-bold">
                INVALID HASH
              </div>
            </div>
          </div>

          <button className="w-full py-2 text-xs font-bold text-primary hover:underline flex items-center justify-center gap-1 mt-2">
            View Detailed System Logs
            <ArrowRight size={12} />
          </button>
        </div>
      </div>
    </div>
  );
}
