File size: 7,218 Bytes
e2ce418
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
import React, { useEffect, useState } from 'react';
import { FileText, Download, Loader, Trash2, AlertCircle } from 'lucide-react';

interface FileListProps {
  supabase: any;
  darkMode: boolean;
  isAdmin?: boolean;
}

interface FileData {
  id: string;
  filename: string;
  storage_path: string;
  file_type: string;
  uploaded_at: string;
}

const FileList: React.FC<FileListProps> = ({ supabase, darkMode, isAdmin = false }) => {
  const [files, setFiles] = useState<FileData[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [downloading, setDownloading] = useState<string | null>(null);
  const [deleting, setDeleting] = useState<string | null>(null);

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

  const fetchFiles = async () => {
    try {
      setError(null);
      setLoading(true);

      // Check if Supabase is initialized properly
      if (!supabase) {
        throw new Error('Database connection not initialized');
      }

      // Test connection with a simple query first
      const { error: connectionError } = await supabase
        .from('codette_files')
        .select('count');

      if (connectionError) {
        throw connectionError;
      }

      // Proceed with actual data fetch
      const { data, error } = await supabase
        .from('codette_files')
        .select('*')
        .order('uploaded_at', { ascending: false });

      if (error) throw error;
      setFiles(data || []);
    } catch (err: any) {
      console.error('Error fetching files:', err);
      setError(err.message || 'Failed to fetch files. Please check your connection.');
      setFiles([]);
    } finally {
      setLoading(false);
    }
  };

  const handleDownload = async (file: FileData) => {
    try {
      setDownloading(file.id);
      setError(null);

      const { data, error } = await supabase.storage
        .from('codette-files')
        .download(file.storage_path);

      if (error) throw error;

      const url = window.URL.createObjectURL(data);
      const a = document.createElement('a');
      a.href = url;
      a.download = file.filename;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    } catch (err: any) {
      console.error('Error downloading file:', err);
      setError(err.message || 'Failed to download file. Please try again.');
    } finally {
      setDownloading(null);
    }
  };

  const handleDelete = async (file: FileData) => {
    if (!isAdmin) return;
    
    if (!confirm('Are you sure you want to delete this file?')) return;

    try {
      setDeleting(file.id);
      setError(null);

      // Delete from storage
      const { error: storageError } = await supabase.storage
        .from('codette-files')
        .remove([file.storage_path]);

      if (storageError) throw storageError;

      // Delete from database
      const { error: dbError } = await supabase
        .from('codette_files')
        .delete()
        .match({ id: file.id });

      if (dbError) throw dbError;

      // Update local state
      setFiles(files.filter(f => f.id !== file.id));
    } catch (err: any) {
      console.error('Error deleting file:', err);
      setError(err.message || 'Failed to delete file. Please try again.');
    } finally {
      setDeleting(null);
    }
  };

  const handleRetry = () => {
    fetchFiles();
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center p-4">
        <Loader className="animate-spin" size={24} />
      </div>
    );
  }

  if (error) {
    return (
      <div className={`p-4 rounded-lg ${darkMode ? 'bg-red-900/20' : 'bg-red-50'}`}>
        <div className="flex items-start space-x-2">
          <AlertCircle className={`flex-shrink-0 ${darkMode ? 'text-red-400' : 'text-red-500'}`} size={20} />
          <div className="flex-1">
            <p className={`text-sm font-medium ${darkMode ? 'text-red-400' : 'text-red-800'}`}>
              Connection Error
            </p>
            <p className={`text-sm mt-1 ${darkMode ? 'text-red-300' : 'text-red-600'}`}>
              {error}
            </p>
            <button
              onClick={handleRetry}
              className={`mt-3 px-3 py-1 rounded-md text-sm ${
                darkMode
                  ? 'bg-red-900/30 hover:bg-red-900/50 text-red-300'
                  : 'bg-red-100 hover:bg-red-200 text-red-700'
              }`}
            >
              Try Again
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-2">
      <h3 className="text-sm font-semibold mb-3">Uploaded Files</h3>
      {files.length === 0 ? (
        <p className={`text-sm ${darkMode ? 'text-gray-400' : 'text-gray-500'}`}>
          No files uploaded yet.
        </p>
      ) : (
        <div className="space-y-2">
          {files.map((file) => (
            <div
              key={file.id}
              className={`p-3 rounded-md ${
                darkMode ? 'bg-gray-700 hover:bg-gray-600' : 'bg-gray-100 hover:bg-gray-200'
              } transition-colors flex items-center justify-between`}
            >
              <div className="flex items-center space-x-2">
                <FileText size={16} className="text-blue-500" />
                <div>
                  <p className="text-sm font-medium truncate max-w-[150px]">
                    {file.filename}
                  </p>
                  <p className={`text-xs ${darkMode ? 'text-gray-400' : 'text-gray-500'}`}>
                    {new Date(file.uploaded_at).toLocaleDateString()}
                  </p>
                </div>
              </div>
              <div className="flex items-center space-x-2">
                <button
                  onClick={() => handleDownload(file)}
                  disabled={downloading === file.id}
                  className={`p-1 rounded-md transition-colors ${
                    darkMode
                      ? 'hover:bg-gray-500 text-gray-300'
                      : 'hover:bg-gray-300 text-gray-700'
                  }`}
                >
                  {downloading === file.id ? (
                    <Loader className="animate-spin" size={16} />
                  ) : (
                    <Download size={16} />
                  )}
                </button>
                {isAdmin && (
                  <button
                    onClick={() => handleDelete(file)}
                    disabled={deleting === file.id}
                    className={`p-1 rounded-md transition-colors ${
                      darkMode
                        ? 'hover:bg-red-500 text-gray-300'
                        : 'hover:bg-red-100 text-red-600'
                    }`}
                  >
                    {deleting === file.id ? (
                      <Loader className="animate-spin" size={16} />
                    ) : (
                      <Trash2 size={16} />
                    )}
                  </button>
                )}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

export default FileList;