'use client';

import { useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import ProtectedRoute from '../../protected-route';
import SidebarLayout from '../../components/sidebar-layout';
import { useTranslations } from '../../hooks/useTranslations';
import SearchablePatientSelect from '../../components/SearchablePatientSelect';
import { 
  FileText, 
  Upload, 
  X, 
  ArrowLeft,
  Plus,
  Tag,
  Calendar,
  User,
  Shield,
  FileUp,
  Check
} from 'lucide-react';
import toast from 'react-hot-toast';

interface Patient {
  _id: string;
  firstName: string;
  lastName: string;
  email?: string;
}

export default function NewDocumentPage() {
  const router = useRouter();
  const { t, translationsLoaded } = useTranslations();
  const [loading, setLoading] = useState(false);
  const [patients, setPatients] = useState<Patient[]>([]);
  const [dragActive, setDragActive] = useState(false);
  
  // Form state
  const [formData, setFormData] = useState({
    title: '',
    description: '',
    category: 'other',
    patientId: '',
    patientName: '',
    status: 'active',
    priority: 'normal',
    expiryDate: '',
    tags: [] as string[],
    notes: '',
    accessControl: {
      isPublic: false,
      allowedRoles: ['admin', 'doctor', 'staff'] as string[],
      allowedUsers: [] as string[],
    },
  });
  const [file, setFile] = useState<File | null>(null);
  const [tagInput, setTagInput] = useState('');

  useEffect(() => {
    fetchPatients();
  }, []);

  const fetchPatients = async () => {
    try {
      const response = await fetch('/api/patients');
      if (response.ok) {
        const data = await response.json();
        setPatients(data);
      }
    } catch (error) {
      console.error('Error fetching patients:', error);
    }
  };

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

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

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

  const handlePatientSelect = (patient: Patient | null) => {
    if (patient) {
      setFormData({
        ...formData,
        patientId: patient._id,
        patientName: `${patient.firstName} ${patient.lastName}`,
      });
    } else {
      setFormData({
        ...formData,
        patientId: '',
        patientName: '',
      });
    }
  };

  const handleAddTag = () => {
    if (tagInput.trim() && !formData.tags.includes(tagInput.trim())) {
      setFormData({
        ...formData,
        tags: [...formData.tags, tagInput.trim()],
      });
      setTagInput('');
    }
  };

  const handleRemoveTag = (tag: string) => {
    setFormData({
      ...formData,
      tags: formData.tags.filter(t => t !== tag),
    });
  };

  const handleRoleToggle = (role: string) => {
    const roles = formData.accessControl.allowedRoles;
    if (roles.includes(role)) {
      setFormData({
        ...formData,
        accessControl: {
          ...formData.accessControl,
          allowedRoles: roles.filter(r => r !== role),
        },
      });
    } else {
      setFormData({
        ...formData,
        accessControl: {
          ...formData.accessControl,
          allowedRoles: [...roles, role],
        },
      });
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!formData.title.trim()) {
      toast.error(t('documents.validation.titleRequired') || 'Title is required');
      return;
    }

    setLoading(true);

    try {
      const submitData = new FormData();
      submitData.append('title', formData.title);
      submitData.append('description', formData.description);
      submitData.append('category', formData.category);
      submitData.append('status', formData.status);
      submitData.append('priority', formData.priority);
      submitData.append('notes', formData.notes);
      submitData.append('tags', JSON.stringify(formData.tags));
      submitData.append('accessControl', JSON.stringify(formData.accessControl));
      
      if (formData.patientId) {
        submitData.append('patientId', formData.patientId);
        submitData.append('patientName', formData.patientName);
      }
      
      if (formData.expiryDate) {
        submitData.append('expiryDate', formData.expiryDate);
      }
      
      if (file) {
        submitData.append('file', file);
      }

      const response = await fetch('/api/documents', {
        method: 'POST',
        body: submitData,
      });

      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.error || 'Failed to create document');
      }

      toast.success(t('documents.createSuccess') || 'Document created successfully');
      router.push('/documents');
    } catch (error) {
      console.error('Error creating document:', error);
      toast.error(error instanceof Error ? error.message : 'Failed to create document');
    } finally {
      setLoading(false);
    }
  };

  const formatFileSize = (bytes: number) => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  if (!translationsLoaded) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
      </div>
    );
  }

  return (
    <ProtectedRoute>
      <SidebarLayout 
        title={t('documents.newDocument') || 'New Document'} 
        description={t('documents.newDocumentDesc') || 'Upload and create a new document'}
      >
        <div className="max-w-4xl mx-auto">
          {/* Back Button */}
          <Link
            href="/documents"
            className="inline-flex items-center text-gray-600 hover:text-gray-900 mb-6"
          >
            <ArrowLeft className="h-5 w-5 mr-2" />
            {t('documents.backToDocuments') || 'Back to Documents'}
          </Link>

          <form onSubmit={handleSubmit} className="space-y-6">
            {/* File Upload Section */}
            <div className="bg-white rounded-lg shadow p-6">
              <h3 className="text-lg font-medium text-gray-900 mb-4 flex items-center">
                <FileUp className="h-5 w-5 mr-2 text-blue-600" />
                {t('documents.fileUpload') || 'File Upload'}
              </h3>
              
              <div
                className={`relative border-2 border-dashed rounded-lg p-8 text-center transition-colors ${
                  dragActive 
                    ? 'border-blue-500 bg-blue-50' 
                    : file 
                      ? 'border-green-500 bg-green-50' 
                      : 'border-gray-300 hover:border-gray-400'
                }`}
                onDragEnter={handleDrag}
                onDragLeave={handleDrag}
                onDragOver={handleDrag}
                onDrop={handleDrop}
              >
                <input
                  type="file"
                  id="file-upload"
                  className="hidden"
                  onChange={handleFileChange}
                  accept=".pdf,.doc,.docx,.xls,.xlsx,.txt,.jpg,.jpeg,.png,.gif"
                />
                
                {file ? (
                  <div className="flex items-center justify-center space-x-4">
                    <div className="flex items-center space-x-3">
                      <Check className="h-8 w-8 text-green-500" />
                      <div className="text-left">
                        <p className="text-sm font-medium text-gray-900">{file.name}</p>
                        <p className="text-xs text-gray-500">{formatFileSize(file.size)}</p>
                      </div>
                    </div>
                    <button
                      type="button"
                      onClick={() => setFile(null)}
                      className="p-2 text-red-500 hover:text-red-700 hover:bg-red-50 rounded-full transition-colors"
                    >
                      <X className="h-5 w-5" />
                    </button>
                  </div>
                ) : (
                  <label htmlFor="file-upload" className="cursor-pointer">
                    <Upload className="mx-auto h-12 w-12 text-gray-400" />
                    <p className="mt-2 text-sm text-gray-600">
                      {t('documents.dragAndDrop') || 'Drag and drop a file here, or click to browse'}
                    </p>
                    <p className="mt-1 text-xs text-gray-500">
                      {t('documents.supportedFormats') || 'PDF, DOC, DOCX, XLS, XLSX, TXT, JPG, PNG, GIF'}
                    </p>
                  </label>
                )}
              </div>
            </div>

            {/* Document Information */}
            <div className="bg-white rounded-lg shadow p-6">
              <h3 className="text-lg font-medium text-gray-900 mb-4 flex items-center">
                <FileText className="h-5 w-5 mr-2 text-blue-600" />
                {t('documents.documentInfo') || 'Document Information'}
              </h3>
              
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="md:col-span-2">
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    {t('documents.titleLabel') || 'Title'} <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="text"
                    value={formData.title}
                    onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                    placeholder={t('documents.titlePlaceholder') || 'Enter document title'}
                    required
                  />
                </div>

                <div className="md:col-span-2">
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    {t('documents.descriptionLabel') || 'Description'}
                  </label>
                  <textarea
                    value={formData.description}
                    onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                    rows={3}
                    placeholder={t('documents.descriptionPlaceholder') || 'Enter document description'}
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    {t('documents.category') || 'Category'} <span className="text-red-500">*</span>
                  </label>
                  <select
                    value={formData.category}
                    onChange={(e) => setFormData({ ...formData, category: e.target.value })}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                    required
                  >
                    <option value="consent-form">{t('documents.categories.consent-form') || 'Consent Form'}</option>
                    <option value="legal-document">{t('documents.categories.legal-document') || 'Legal Document'}</option>
                    <option value="medical-certificate">{t('documents.categories.medical-certificate') || 'Medical Certificate'}</option>
                    <option value="insurance">{t('documents.categories.insurance') || 'Insurance'}</option>
                    <option value="identification">{t('documents.categories.identification') || 'Identification'}</option>
                    <option value="referral">{t('documents.categories.referral') || 'Referral'}</option>
                    <option value="discharge-summary">{t('documents.categories.discharge-summary') || 'Discharge Summary'}</option>
                    <option value="prescription">{t('documents.categories.prescription') || 'Prescription'}</option>
                    <option value="lab-report">{t('documents.categories.lab-report') || 'Lab Report'}</option>
                    <option value="imaging-report">{t('documents.categories.imaging-report') || 'Imaging Report'}</option>
                    <option value="other">{t('documents.categories.other') || 'Other'}</option>
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    {t('documents.status') || 'Status'}
                  </label>
                  <select
                    value={formData.status}
                    onChange={(e) => setFormData({ ...formData, status: e.target.value })}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  >
                    <option value="draft">{t('documents.statusLabels.draft') || 'Draft'}</option>
                    <option value="active">{t('documents.statusLabels.active') || 'Active'}</option>
                    <option value="archived">{t('documents.statusLabels.archived') || 'Archived'}</option>
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    {t('documents.priority') || 'Priority'}
                  </label>
                  <select
                    value={formData.priority}
                    onChange={(e) => setFormData({ ...formData, priority: e.target.value })}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  >
                    <option value="low">{t('documents.priorityLabels.low') || 'Low'}</option>
                    <option value="normal">{t('documents.priorityLabels.normal') || 'Normal'}</option>
                    <option value="high">{t('documents.priorityLabels.high') || 'High'}</option>
                    <option value="urgent">{t('documents.priorityLabels.urgent') || 'Urgent'}</option>
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    {t('documents.expiryDate') || 'Expiry Date'}
                  </label>
                  <input
                    type="date"
                    value={formData.expiryDate}
                    onChange={(e) => setFormData({ ...formData, expiryDate: e.target.value })}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  />
                </div>
              </div>
            </div>

            {/* Patient Association */}
            <div className="bg-white rounded-lg shadow p-6">
              <h3 className="text-lg font-medium text-gray-900 mb-4 flex items-center">
                <User className="h-5 w-5 mr-2 text-blue-600" />
                {t('documents.patientAssociation') || 'Patient Association'}
              </h3>
              
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {t('documents.selectPatient') || 'Select Patient'} ({t('common.optional') || 'Optional'})
                </label>
                <SearchablePatientSelect
                  onSelect={handlePatientSelect}
                  selectedPatient={formData.patientId ? {
                    _id: formData.patientId,
                    firstName: formData.patientName.split(' ')[0],
                    lastName: formData.patientName.split(' ').slice(1).join(' '),
                  } : null}
                  placeholder={t('documents.searchPatient') || 'Search for a patient...'}
                />
              </div>
            </div>

            {/* Tags */}
            <div className="bg-white rounded-lg shadow p-6">
              <h3 className="text-lg font-medium text-gray-900 mb-4 flex items-center">
                <Tag className="h-5 w-5 mr-2 text-blue-600" />
                {t('documents.tags') || 'Tags'}
              </h3>
              
              <div className="flex flex-wrap gap-2 mb-4">
                {formData.tags.map((tag) => (
                  <span
                    key={tag}
                    className="inline-flex items-center px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-sm"
                  >
                    {tag}
                    <button
                      type="button"
                      onClick={() => handleRemoveTag(tag)}
                      className="ml-2 text-blue-600 hover:text-blue-800"
                    >
                      <X className="h-4 w-4" />
                    </button>
                  </span>
                ))}
              </div>
              
              <div className="flex gap-2">
                <input
                  type="text"
                  value={tagInput}
                  onChange={(e) => setTagInput(e.target.value)}
                  onKeyPress={(e) => e.key === 'Enter' && (e.preventDefault(), handleAddTag())}
                  className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  placeholder={t('documents.addTagPlaceholder') || 'Add a tag and press Enter'}
                />
                <button
                  type="button"
                  onClick={handleAddTag}
                  className="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors"
                >
                  <Plus className="h-5 w-5" />
                </button>
              </div>
            </div>

            {/* Access Control */}
            <div className="bg-white rounded-lg shadow p-6">
              <h3 className="text-lg font-medium text-gray-900 mb-4 flex items-center">
                <Shield className="h-5 w-5 mr-2 text-blue-600" />
                {t('documents.accessControl') || 'Access Control'}
              </h3>
              
              <div className="space-y-4">
                <div className="flex items-center">
                  <input
                    type="checkbox"
                    id="isPublic"
                    checked={formData.accessControl.isPublic}
                    onChange={(e) => setFormData({
                      ...formData,
                      accessControl: { ...formData.accessControl, isPublic: e.target.checked }
                    })}
                    className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                  />
                  <label htmlFor="isPublic" className="ml-2 text-sm text-gray-700">
                    {t('documents.isPublic') || 'Make this document publicly accessible'}
                  </label>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    {t('documents.allowedRoles') || 'Allowed Roles'}
                  </label>
                  <div className="flex flex-wrap gap-2">
                    {['admin', 'doctor', 'staff', 'patient'].map((role) => (
                      <button
                        key={role}
                        type="button"
                        onClick={() => handleRoleToggle(role)}
                        className={`px-3 py-1 rounded-full text-sm font-medium transition-colors ${
                          formData.accessControl.allowedRoles.includes(role)
                            ? 'bg-blue-600 text-white'
                            : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                        }`}
                      >
                        {t(`documents.roles.${role}`) || role.charAt(0).toUpperCase() + role.slice(1)}
                      </button>
                    ))}
                  </div>
                </div>
              </div>
            </div>

            {/* Notes */}
            <div className="bg-white rounded-lg shadow p-6">
              <h3 className="text-lg font-medium text-gray-900 mb-4">
                {t('documents.notes') || 'Notes'}
              </h3>
              
              <textarea
                value={formData.notes}
                onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                rows={4}
                placeholder={t('documents.notesPlaceholder') || 'Add any additional notes...'}
              />
            </div>

            {/* Submit Buttons */}
            <div className="flex justify-end space-x-4">
              <Link
                href="/documents"
                className="px-6 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
              >
                {t('common.cancel') || 'Cancel'}
              </Link>
              <button
                type="submit"
                disabled={loading}
                className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center"
              >
                {loading ? (
                  <>
                    <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white mr-2"></div>
                    {t('common.saving') || 'Saving...'}
                  </>
                ) : (
                  <>
                    <FileText className="h-5 w-5 mr-2" />
                    {t('documents.createDocument') || 'Create Document'}
                  </>
                )}
              </button>
            </div>
          </form>
        </div>
      </SidebarLayout>
    </ProtectedRoute>
  );
}
