'use client';

import React, { useRef, useState } from 'react';
import { UploadCloud, FileText, X, AlertCircle } from 'lucide-react';
import { cn } from '@/lib/utils';

interface FileUploadProps {
  value?: string; // Can be a URL, base64 or file name
  onChange: (value: string, fileName?: string) => void;
  accept?: string; // e.g. "application/pdf,image/*"
  maxSizeMb?: number;
  label?: string;
  error?: string;
}

export function FileUpload({
  value,
  onChange,
  accept = 'application/pdf,image/png,image/jpeg',
  maxSizeMb = 2,
  label = 'Unggah Dokumen Pendukung',
  error,
}: FileUploadProps) {
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [fileName, setFileName] = useState<string>('');
  const [isDragActive, setIsDragActive] = useState(false);
  const [validationError, setValidationError] = useState<string | null>(null);

  const handleFile = (file: File) => {
    setValidationError(null);

    // Validate size
    if (file.size > maxSizeMb * 1024 * 1024) {
      setValidationError(`Ukuran file maksimal adalah ${maxSizeMb} MB.`);
      return;
    }

    // Validate type
    const acceptedTypes = accept.split(',').map((type) => type.trim());
    const fileType = file.type;
    const fileExt = `.${file.name.split('.').pop()?.toLowerCase()}`;
    
    const isAccepted = acceptedTypes.some((type) => {
      if (type.endsWith('/*')) {
        const baseType = type.split('/')[0];
        return fileType.startsWith(`${baseType}/`);
      }
      return fileType === type || fileExt === type;
    });

    if (!isAccepted) {
      setValidationError(`Tipe file tidak didukung. Harap unggah: ${accept}`);
      return;
    }

    setFileName(file.name);

    // Simulate reading file to base64
    const reader = new FileReader();
    reader.onloadend = () => {
      onChange(reader.result as string, file.name);
    };
    reader.readAsDataURL(file);
  };

  const handleDrag = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.type === 'dragenter' || e.type === 'dragover') {
      setIsDragActive(true);
    } else if (e.type === 'dragleave') {
      setIsDragActive(false);
    }
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragActive(false);
    if (e.dataTransfer.files && e.dataTransfer.files[0]) {
      handleFile(e.dataTransfer.files[0]);
    }
  };

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      handleFile(e.target.files[0]);
    }
  };

  const clearFile = () => {
    setFileName('');
    onChange('', '');
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  return (
    <div className="space-y-2">
      <label className="block text-sm font-semibold text-text-primary">{label}</label>

      {value ? (
        <div className="flex items-center justify-between p-4 bg-card border border-primary/20 rounded-2xl shadow-sm">
          <div className="flex items-center gap-3 overflow-hidden">
            <div className="p-3 bg-primary/10 text-primary rounded-xl flex-shrink-0">
              <FileText className="h-6 w-6" />
            </div>
            <div className="flex flex-col overflow-hidden">
              <span className="text-sm font-semibold text-text-primary truncate">
                {fileName || 'dokumen_pendukung.pdf'}
              </span>
              <span className="text-xs text-text-muted">Dokumen terunggah</span>
            </div>
          </div>
          <button
            type="button"
            onClick={clearFile}
            className="p-2 text-danger hover:bg-danger/5 rounded-xl transition-colors"
            title="Remove file"
          >
            <X className="h-5 w-5" />
          </button>
        </div>
      ) : (
        <div
          onDragEnter={handleDrag}
          onDragOver={handleDrag}
          onDragLeave={handleDrag}
          onDrop={handleDrop}
          onClick={() => fileInputRef.current?.click()}
          className={cn(
            'flex flex-col items-center justify-center border-2 border-dashed border-text-muted/20 hover:border-primary/50 rounded-2xl p-8 cursor-pointer transition-all duration-300 bg-card text-center gap-3',
            isDragActive && 'border-primary bg-primary/5 scale-[0.99]',
            (error || validationError) && 'border-danger bg-danger/5'
          )}
        >
          <input
            type="file"
            ref={fileInputRef}
            onChange={handleFileSelect}
            accept={accept}
            className="hidden"
          />

          <div className="p-4 bg-primary/5 text-primary rounded-2xl">
            <UploadCloud className="h-8 w-8" />
          </div>

          <div className="space-y-1">
            <p className="text-sm font-semibold text-text-primary">
              Seret & letakkan file di sini, atau <span className="text-primary hover:underline">pilih file</span>
            </p>
            <p className="text-xs text-text-muted">
              PDF, PNG, JPG hingga {maxSizeMb} MB
            </p>
          </div>
        </div>
      )}

      {(error || validationError) && (
        <div className="flex items-center gap-1.5 text-xs text-danger font-semibold mt-1">
          <AlertCircle className="h-4 w-4 flex-shrink-0" />
          <span>{error || validationError}</span>
        </div>
      )}
    </div>
  );
}
