'use client';

import React from 'react';
import { Document as PrismaDocument } from '@/types/types';
import { Button } from '@/components/ui/button';
import { Pencil, Trash2, FileText, Download, FileIcon, Plus, ChevronLeft, ChevronRight, Eye } from 'lucide-react';
import { useRouter } from 'next/navigation';
import FileInput from '@/components/form/input/FileInput';
import { createDocument, uploadFile } from '@/helpers/axios_helper';
import { Select, SelectTrigger, SelectContent, SelectItem, SelectValue } from '@/components/ui/select';
import { DocumentType } from '@/types/types';
import { Modal } from '@/components/ui/modal';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';

type DocumentWithPartner = PrismaDocument & { partner?: { name?: string; firstName?: string; lastName?: string } };

interface DocumentTableProps {
  documents: DocumentWithPartner[];
  onDelete: (id: number) => void;
  onRefresh?: () => void;
}

export default function DocumentTable({ documents, onDelete, onRefresh }: DocumentTableProps) {
  const router = useRouter();
  const [showAddSubDocModal, setShowAddSubDocModal] = React.useState(false);
  const [parentDoc, setParentDoc] = React.useState<DocumentWithPartner | null>(null);
  const [form, setForm] = React.useState({ name: '', documentType: '', file: null as File | null });
  const fileInputRef = React.useRef<HTMLInputElement>(null);
  const [view, setView] = React.useState<'table' | 'timeline'>('table');
  const yearsBarRef = React.useRef<HTMLDivElement>(null);

  const handleViewDocument = (path: string) => {
    window.open(path, '_blank');
  };

  const handleDownloadDocument = (path: string, name: string) => {
    const link = window.document.createElement('a');
    link.href = path;
    link.download = name;
    window.document.body.appendChild(link);
    link.click();
    window.document.body.removeChild(link);
  };

  const handleOpenSubDocModal = (doc: DocumentWithPartner) => {
    setParentDoc(doc);
    setForm({ name: '', documentType: '', file: null });
    setShowAddSubDocModal(true);
  };
  const handleCloseModal = () => {
    setShowAddSubDocModal(false);
    setParentDoc(null);
    setForm({ name: '', documentType: '', file: null });
    if (fileInputRef.current) fileInputRef.current.value = '';
  };
  const handleFormChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value, type } = e.target;
    if (type === 'file') {
      setForm(prev => ({ ...prev, file: (e.target as HTMLInputElement).files?.[0] || null }));
    } else {
      setForm(prev => ({ ...prev, [name]: value }));
    }
  };
  const handleTypeChange = (value: string) => {
    setForm(prev => ({ ...prev, documentType: value }));
  };
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!parentDoc) return;
    
    try {
      let documentPath = '';
      
      // Upload du fichier si présent
      if (form.file) {
        const uploadFormData = new FormData();
        uploadFormData.append('file', form.file);
        uploadFormData.append('name', form.name);
        uploadFormData.append('isPermanent', 'false');
        uploadFormData.append('documentType', form.documentType);
        
        const uploadResponse = await uploadFile(uploadFormData);
        documentPath = uploadResponse.path;
      }
      
             // Créer le document avec les données
       const documentData = {
         name: form.name,
         documentType: form.documentType as DocumentType,
         parentId: parentDoc.id,
         path: documentPath || '/uploads/placeholder.txt', // Path par défaut si pas de fichier
         isPermanent: false,
         uploadDate: new Date(),
         fileType: form.file?.type || 'text/plain',
         clientId: parentDoc.clientId, // Hériter du client du parent
         partnerId: parentDoc.partnerId // Hériter du partenaire du parent
       };
      
      await createDocument(documentData);
      handleCloseModal();
      
      // Recharger la liste des documents via une prop callback
      if (onRefresh) {
        onRefresh();
      } else {
        window.location.reload();
      }
    } catch (err) {
      console.error('Erreur lors de l\'ajout du sous-document:', err);
      alert('Erreur lors de l\'ajout du sous-document');
    }
  };

  // Timeline : regroupe les documents par année
  const docsByYear: { [year: string]: DocumentWithPartner[] } = {};
  documents.forEach(doc => {
    const year = new Date(doc.uploadDate).getFullYear();
    if (!docsByYear[year]) docsByYear[year] = [];
    docsByYear[year].push(doc);
  });
  const sortedYears = Object.keys(docsByYear).sort((a, b) => Number(b) - Number(a));

  // Timeline : affichage récursif hiérarchique
  const renderTimelineTree = (doc: DocumentWithPartner, level = 0) => [
    <div key={doc.id} style={{ marginLeft: level * 32 }} className="mb-2">
      <div className="flex items-center gap-2">
        <FileIcon className="h-5 w-5 text-gray-400" />
        <span className="font-semibold">{doc.name}</span>
        <span className="text-xs text-gray-500">({doc.documentType})</span>
        <Button size="icon" variant="ghost" onClick={() => handleOpenSubDocModal(doc)} title="Ajouter un sous-document">
          <Plus className="h-4 w-4" />
        </Button>
      </div>
      {documents.filter(d => d.parentId === doc.id).map(child => renderTimelineTree(child, level + 1))}
    </div>
  ];

  // Fonction récursive pour afficher un document et ses sous-documents
  const renderDocumentRow = (doc: DocumentWithPartner, level = 0) => [
    <tr key={doc.id} className="hover:bg-gray-50">
      <td className="px-6 py-4 whitespace-nowrap" style={{ paddingLeft: `${level * 32}px` }}>
        <div className="text-sm font-medium text-gray-900">{doc.name}</div>
      </td>
      <td className="px-6 py-4 whitespace-nowrap">
        <div className="text-sm text-gray-500">{doc.documentType}</div>
      </td>
      <td className="px-6 py-4 whitespace-nowrap">
        <div className="text-sm text-gray-500">{doc.partner?.name || (doc.partner?.firstName + ' ' + doc.partner?.lastName) || '-'}</div>
      </td>
      <td className="px-6 py-4 whitespace-nowrap">
        <div className="text-sm text-gray-500">{new Date(doc.uploadDate).toLocaleDateString()}</div>
      </td>
      <td className="px-6 py-4 whitespace-nowrap">
        <div className="flex items-center space-x-2">
          <FileIcon className="h-5 w-5 text-gray-400" />
          <div className="flex space-x-2">
                                                   <Button
                variant="ghost"
                size="sm"
                onClick={() => handleViewDocument(doc.path)}
                className="text-xs"
              >
                <FileText className="h-4 w-4 mr-1" />
                Voir
              </Button>
            <Button
              variant="ghost"
              size="sm"
              onClick={() => handleDownloadDocument(doc.path, doc.name)}
              className="text-xs"
            >
              <Download className="h-4 w-4 mr-1" />
              Télécharger
            </Button>
          </div>
        </div>
      </td>
      <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
        <div className="flex justify-end space-x-2">
          <Button
            variant="ghost"
            size="icon"
            onClick={() => router.push(`/admin/documents/${doc.id}`)}
          >
            <Eye className="h-4 w-4" />
          </Button>
          <Button
            variant="ghost"
            size="icon"
            onClick={() => router.push(`/admin/documents/${doc.id}/edit`)}
          >
            <Pencil className="h-4 w-4" />
          </Button>
          <Button
            variant="ghost"
            size="icon"
            onClick={() => onDelete(doc.id)}
          >
            <Trash2 className="h-4 w-4" />
          </Button>
          <Button
            variant="ghost"
            size="icon"
            onClick={() => handleOpenSubDocModal(doc)}
            title="Ajouter un sous-document"
          >
            <Plus className="h-4 w-4" />
          </Button>
        </div>
      </td>
    </tr>,
    ...(documents.filter(d => d.parentId === doc.id).flatMap(child => renderDocumentRow(child, level + 1)))
  ];

  // Documents racines (sans parent)
  const rootDocs = documents.filter(doc => !doc.parentId);

  return (
    <div className="overflow-x-auto">
      <Tabs value={view} onValueChange={v => setView(v as 'table' | 'timeline')} className="mb-4">
        <TabsList>
          <TabsTrigger value="table">Table</TabsTrigger>
          <TabsTrigger value="timeline">Timeline</TabsTrigger>
        </TabsList>
        <TabsContent value="table">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Nom du Document
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Type
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Partenaire associé
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Date d'ajout
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Pièce jointe
                </th>
                <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Actions
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {rootDocs.flatMap(doc => renderDocumentRow(doc))}
            </tbody>
          </table>
        </TabsContent>
        <TabsContent value="timeline">
          {/* Barre d'années horizontale avec première et dernière année fixes */}
          <div className="relative pb-8 mb-4 flex items-center gap-2">
            {/* Première année fixe */}
            {sortedYears.length > 0 && (
              <a
                href={`#timeline-year-${sortedYears[0]}`}
                className="bg-blue-900 text-white rounded-full w-10 h-10 flex items-center justify-center font-bold text-lg border-4 border-white shadow hover:bg-blue-700 transition z-10"
                style={{ minWidth: 40, minHeight: 40 }}
              >
                {sortedYears[0]}
              </a>
            )}
            {/* Trait entre la première année et la barre scrollable */}
            {sortedYears.length > 2 && <div className="h-1 w-8 bg-blue-700" style={{ minWidth: 32 }} />}
            {/* Barre scrollable centrale */}
            <div className="flex gap-2 overflow-x-auto items-center scrollbar-thin scrollbar-thumb-gray-300 scrollbar-track-gray-100" style={{ flex: 1, minWidth: 0 }} ref={yearsBarRef}>
              {sortedYears.slice(1, -1).map((year, idx) => (
                <React.Fragment key={year}>
                  <a
                    href={`#timeline-year-${year}`}
                    className="bg-blue-500 text-white rounded-full w-10 h-10 flex items-center justify-center font-bold text-lg border-4 border-white shadow hover:bg-blue-700 transition z-10"
                    style={{ minWidth: 40, minHeight: 40 }}
                  >
                    {year}
                  </a>
                  {idx < sortedYears.slice(1, -1).length - 1 && (
                    <div className="h-1 w-8 bg-blue-700" style={{ minWidth: 32 }} />
                  )}
                </React.Fragment>
              ))}
            </div>
            {/* Trait entre la barre scrollable et la dernière année */}
            {sortedYears.length > 2 && <div className="h-1 w-8 bg-blue-700" style={{ minWidth: 32 }} />}
            {/* Dernière année fixe */}
            {sortedYears.length > 1 && (
              <a
                href={`#timeline-year-${sortedYears[sortedYears.length - 1]}`}
                className="bg-blue-900 text-white rounded-full w-10 h-10 flex items-center justify-center font-bold text-lg border-4 border-white shadow hover:bg-blue-700 transition z-10"
                style={{ minWidth: 40, minHeight: 40 }}
              >
                {sortedYears[sortedYears.length - 1]}
              </a>
            )}
            {/* Ligne horizontale continue sous les bulles d'années */}
            <div className="absolute left-0 right-0 top-1/2 h-1 bg-blue-700 z-0" style={{ top: 28 }} />
          </div>
          {/* Timeline verticale par année (sans ligne verticale à gauche) */}
          <div className="flex flex-col w-full">
            {sortedYears.map((year) => (
              <div key={year} className="mb-8" id={`timeline-year-${year}`}> 
                <div className="ml-2">
                  {docsByYear[year]
                    .filter(doc => !doc.parentId)
                    .sort((a, b) => new Date(a.uploadDate).getTime() - new Date(b.uploadDate).getTime())
                    .flatMap(doc => renderTimelineTree(doc))}
                </div>
              </div>
            ))}
          </div>
        </TabsContent>
      </Tabs>
      <Modal isOpen={showAddSubDocModal} onClose={handleCloseModal}>
        <div className="p-4">
          <h2 className="text-lg font-semibold mb-4">Ajouter un sous-document à : {parentDoc?.name}</h2>
          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label className="block mb-1">Nom du sous-document</label>
              <input type="text" name="name" value={form.name} onChange={handleFormChange} className="w-full border rounded p-2" required />
            </div>
            <div>
              <label className="block mb-1">Type</label>
              <select
                name="documentType"
                value={form.documentType}
                onChange={handleFormChange}
                required
                className="w-full border rounded p-2"
              >
                <option value="">Sélectionner un type</option>
                {Object.values(DocumentType).map((type) => (
                  <option key={type} value={type}>
                    {type.replace(/_/g, ' ')}
                  </option>
                ))}
              </select>
            </div>
            <div>
              <label className="block mb-1">Document joint</label>
              <input type="file" name="file" onChange={handleFormChange} ref={fileInputRef} className="w-full border rounded p-2" />
            </div>
            <div className="flex gap-2 justify-end">
              <Button type="button" variant="outline" onClick={handleCloseModal}>Annuler</Button>
              <Button type="submit">Enregistrer</Button>
            </div>
          </form>
        </div>
      </Modal>
    </div>
  );
} 